content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading; using System.Threading.Tasks; using Elektronik.Data; using Elektronik.Data.Converters; using Elektronik.Offline; using Elektronik.Settings; using Elektronik.Threading; using UnityEngine; namespace Elektronik.PluginsSystem.UnitySide { public class PluginsPlayer : MonoBehaviour { public static ReadOnlyCollection<IElektronikPlugin> Plugins = PluginsLoader.ActivePlugins.AsReadOnly(); public CSConverter Converter; public PlayerEventsManager PlayerEvents; public GameObject ScreenLocker; public DataSourcesManager DataSourcesManager; public event Action PluginsStarted; public void ClearMap() { Camera.main.transform.parent = null; foreach (var dataSourceOffline in Plugins.OfType<IDataSourcePluginOffline>()) { dataSourceOffline.StopPlaying(); } DataSourcesManager.ClearMap(); } #region Unity events private void Start() { #if UNITY_EDITOR if (ModeSelector.Mode == Mode.Online) { Plugins = PluginsLoader.Plugins.Value .OfType<IDataSourcePluginOnline>() .Select(p => (IElektronikPlugin) p) .ToList() .AsReadOnly(); } #endif ScreenLocker.SetActive(true); foreach (var dataSource in Plugins.OfType<IDataSourcePlugin>()) { dataSource.Converter = Converter; DataSourcesManager.AddDataSource(dataSource.Data); } foreach (var dataSource in Plugins.OfType<IDataSourcePluginOffline>()) { PlayerEvents.SetDataSource(dataSource); } foreach (var plugin in Plugins) { var thread = new Thread(() => plugin.Start()); thread.Start(); _startupThreads.Add(thread); } PluginsStarted += () => ScreenLocker.SetActive(false); Task.Run(() => { foreach (var thread in _startupThreads) { thread.Join(); } MainThreadInvoker.Enqueue(() => PluginsStarted?.Invoke()); }); } private void Update() { foreach (var plugin in Plugins) { plugin.Update(Time.deltaTime); } } private void OnDestroy() { foreach (var plugin in Plugins) { plugin.Stop(); } } private void OnApplicationQuit() { #if !UNITY_EDITOR System.Diagnostics.Process.GetCurrentProcess().Kill(); #endif } #endregion #region Private private readonly List<Thread> _startupThreads = new List<Thread>(); #endregion } }
26.836207
111
0.549952
[ "MIT" ]
dioram/Elektronik
Assets/Scripts/PluginsSystem/UnitySide/PluginsPlayer.cs
3,115
C#
namespace GridDesktop.Examples.WorkingWithRowsandColumns { partial class RemovingRow { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.button1 = new System.Windows.Forms.Button(); this.gridDesktop1 = new Aspose.Cells.GridDesktop.GridDesktop(); this.SuspendLayout(); // // button1 // this.button1.Anchor = System.Windows.Forms.AnchorStyles.Bottom; this.button1.Location = new System.Drawing.Point(296, 411); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(101, 23); this.button1.TabIndex = 15; this.button1.Text = "Remove Row"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // gridDesktop1 // this.gridDesktop1.ActiveSheetIndex = 0; this.gridDesktop1.ActiveSheetNameFont = null; this.gridDesktop1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.gridDesktop1.CommentDisplayingFont = new System.Drawing.Font("Arial", 9F); this.gridDesktop1.IsHorizontalScrollBarVisible = true; this.gridDesktop1.IsVerticalScrollBarVisible = true; this.gridDesktop1.Location = new System.Drawing.Point(12, 12); this.gridDesktop1.Name = "gridDesktop1"; this.gridDesktop1.SheetNameFont = new System.Drawing.Font("Verdana", 8F); this.gridDesktop1.SheetTabWidth = 400; this.gridDesktop1.Size = new System.Drawing.Size(669, 393); this.gridDesktop1.TabIndex = 14; // // RemovingRow // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(693, 446); this.Controls.Add(this.button1); this.Controls.Add(this.gridDesktop1); this.Name = "RemovingRow"; this.Text = "Removing Row"; this.WindowState = System.Windows.Forms.FormWindowState.Maximized; this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button button1; private Aspose.Cells.GridDesktop.GridDesktop gridDesktop1; } }
41.939024
161
0.599302
[ "MIT" ]
Aspose/Aspose.Cells-for-.NET
Examples.GridDesktop/CSharp/GridDesktop.Examples/WorkingWithRowsandColumns/RemovingRow.Designer.cs
3,441
C#
using System.Collections; using System.Collections.Generic; using UnityEngine.SceneManagement; using UnityEngine; public class SpawnableBlock { public bool spawn; public int pos; public int rot; public SpawnableBlock(bool sp, int p, int r) { spawn = sp; pos = p; rot = r; } } public class SpawnLinkinParkBlocks : MonoBehaviour { // Constants public const int BLUE_BLOCK = 0; public const int RED_BLOCK = 1; public const int FAR_LEFT_TOP = 0; public const int FAR_LEFT_BOTTOM = 1; public const int CLOSE_LEFT_BOTTOM = 2; public const int CLOSE_RIGHT_BOTTOM = 3; public const int FAR_RIGHT_BOTTOM = 4; public const int FAR_RIGHT_TOP = 5; public const int ROT_UP = 0; public const int ROT_RIGHT = 1; public const int ROT_DOWN = 2; public const int ROT_LEFT = 3; AudioSource audioData; // Blocks the player can destroy (red or blue) public GameObject[] slashableBlocks; // The positions for spawning and object public Transform[] spawnBounds; public int timer = 0; public int indexable = 0; public int started = 0; // Level data hardcoded public SpawnableBlock[] redSpawn; public SpawnableBlock[] blueSpawn; // Update is called during fixed periods void FixedUpdate() { if (started > 0) { if (timer % 41 == 0) { if (indexable >= 0 && indexable < redSpawn.Length && redSpawn[indexable].spawn) { // Create random block (red/blue) with random position GameObject slashableBlock = Instantiate(slashableBlocks[RED_BLOCK], spawnBounds[redSpawn[indexable].pos]); slashableBlock.transform.localPosition = Vector3.zero; // It can be either up, down, left or right slashableBlock.transform.Rotate(transform.forward, 90 * redSpawn[indexable].rot); } if (indexable >= 0 && indexable < blueSpawn.Length && blueSpawn[indexable].spawn) { // Create random block (red/blue) with random position GameObject slashableBlock = Instantiate(slashableBlocks[BLUE_BLOCK], spawnBounds[blueSpawn[indexable].pos]); slashableBlock.transform.localPosition = Vector3.zero; // It can be either up, down, left or right slashableBlock.transform.Rotate(transform.forward, 90 * blueSpawn[indexable].rot); } // Indexable running at lower speed ++indexable; } // Start music timing if (indexable == 2) { audioData = GameObject.Find("MusicBox").GetComponent<AudioSource>(); audioData.Play(0); } // Level over successfully if (indexable > redSpawn.Length && indexable > blueSpawn.Length && started == 1) { started = 2; GoToMenuDelayed(); } // Increment timer ++timer; } } void GoToMenuDelayed() { // Manually clean up objects in our hand so they don't transfer over to next scene GameObject[] cleanup = GameObject.FindGameObjectsWithTag("CleanManuallyOnSceneChange"); foreach (GameObject cl in cleanup) { Destroy(cl, 0); } // Go to menu scene Invoke("GoToMenu", 0.5f); } void GoToMenu() { SceneManager.LoadScene("MainMenuScene", LoadSceneMode.Single); } SpawnableBlock sp(int p, int r) { return new SpawnableBlock(true, p, r); } SpawnableBlock np() { return new SpawnableBlock(false, 0, 0); } void Start() { timer = 0; indexable = 0; blueSpawn = new SpawnableBlock[340]; redSpawn = new SpawnableBlock[340]; blueSpawn[0] = sp(FAR_LEFT_BOTTOM, ROT_RIGHT); redSpawn[0] = sp(FAR_RIGHT_BOTTOM, ROT_LEFT); blueSpawn[1] = np(); redSpawn[1] = np(); blueSpawn[2] = np(); redSpawn[2] = sp(CLOSE_LEFT_BOTTOM, ROT_RIGHT); blueSpawn[3] = np(); redSpawn[3] = np(); blueSpawn[4] = np(); redSpawn[4] = sp(FAR_RIGHT_BOTTOM, ROT_LEFT); blueSpawn[5] = np(); redSpawn[5] = np(); blueSpawn[6] = np(); redSpawn[6] = np(); blueSpawn[7] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[7] = np(); blueSpawn[8] = np(); redSpawn[8] = np(); blueSpawn[9] = sp(CLOSE_LEFT_BOTTOM, ROT_DOWN); redSpawn[9] = np(); blueSpawn[10] = np(); redSpawn[10] = np(); blueSpawn[11] = np(); redSpawn[11] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[12] = np(); redSpawn[12] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); blueSpawn[13] = sp(CLOSE_LEFT_BOTTOM, ROT_DOWN); redSpawn[13] = np(); blueSpawn[14] = sp(FAR_LEFT_TOP, ROT_RIGHT); redSpawn[14] = np(); blueSpawn[15] = np(); redSpawn[15] = np(); blueSpawn[16] = np(); redSpawn[16] = np(); blueSpawn[17] = np(); redSpawn[17] = np(); blueSpawn[18] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[18] = np(); blueSpawn[19] = np(); redSpawn[19] = sp(FAR_RIGHT_TOP, ROT_LEFT); blueSpawn[20] = np(); redSpawn[20] = np(); blueSpawn[21] = np(); redSpawn[21] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[22] = sp(FAR_LEFT_TOP, ROT_RIGHT); redSpawn[22] = np(); blueSpawn[23] = np(); redSpawn[23] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); blueSpawn[24] = np(); redSpawn[24] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[25] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[25] = np(); blueSpawn[26] = np(); redSpawn[26] = np(); blueSpawn[27] = np(); redSpawn[27] = np(); blueSpawn[28] = sp(CLOSE_LEFT_BOTTOM, ROT_DOWN); redSpawn[28] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); blueSpawn[29] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[29] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[30] = sp(CLOSE_LEFT_BOTTOM, ROT_DOWN); redSpawn[30] = np(); blueSpawn[31] = np(); redSpawn[31] = sp(FAR_RIGHT_TOP, ROT_LEFT); blueSpawn[32] = np(); redSpawn[32] = np(); blueSpawn[33] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); redSpawn[33] = sp(FAR_RIGHT_BOTTOM, ROT_UP); blueSpawn[34] = np(); redSpawn[34] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); blueSpawn[35] = sp(FAR_LEFT_TOP, ROT_RIGHT); redSpawn[35] = np(); blueSpawn[36] = np(); redSpawn[36] = np(); blueSpawn[37] = sp(FAR_LEFT_BOTTOM, ROT_UP); redSpawn[37] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); blueSpawn[38] = sp(CLOSE_LEFT_BOTTOM, ROT_DOWN); redSpawn[38] = np(); blueSpawn[39] = np(); redSpawn[39] = sp(FAR_RIGHT_TOP, ROT_LEFT); blueSpawn[40] = np(); redSpawn[40] = np(); blueSpawn[41] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[41] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); //39 blueSpawn[42] = np(); redSpawn[42] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); blueSpawn[43] = sp(FAR_LEFT_TOP, ROT_RIGHT); redSpawn[43] = np(); blueSpawn[44] = np(); redSpawn[44] = np(); blueSpawn[45] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[45] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[46] = sp(CLOSE_LEFT_BOTTOM, ROT_DOWN); redSpawn[46] = np(); blueSpawn[47] = np(); redSpawn[47] = sp(FAR_RIGHT_TOP, ROT_LEFT); blueSpawn[48] = np(); redSpawn[48] = np(); blueSpawn[49] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); redSpawn[49] = sp(FAR_RIGHT_BOTTOM, ROT_UP); blueSpawn[50] = np(); redSpawn[50] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); blueSpawn[51] = sp(FAR_LEFT_TOP, ROT_RIGHT); redSpawn[51] = np(); blueSpawn[52] = np(); redSpawn[52] = np(); blueSpawn[53] = sp(FAR_LEFT_BOTTOM, ROT_UP); redSpawn[53] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); blueSpawn[54] = sp(CLOSE_LEFT_BOTTOM, ROT_DOWN); redSpawn[54] = np(); blueSpawn[55] = np(); redSpawn[55] = sp(FAR_RIGHT_TOP, ROT_LEFT); blueSpawn[56] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[56] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); // 45 blueSpawn[57] = np(); redSpawn[57] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); blueSpawn[58] = sp(FAR_LEFT_TOP, ROT_RIGHT); redSpawn[58] = np(); blueSpawn[59] = np(); redSpawn[59] = sp(CLOSE_RIGHT_BOTTOM, ROT_LEFT); blueSpawn[60] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[60] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); // 46 "I am" blueSpawn[61] = sp(CLOSE_LEFT_BOTTOM, ROT_DOWN); redSpawn[61] = np(); blueSpawn[62] = np(); redSpawn[62] = sp(CLOSE_RIGHT_BOTTOM, ROT_LEFT); blueSpawn[63] = np(); redSpawn[63] = np(); blueSpawn[64] = sp(FAR_LEFT_TOP, ROT_RIGHT); redSpawn[64] = np(); blueSpawn[65] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[65] = np(); blueSpawn[66] = np(); redSpawn[66] = sp(FAR_RIGHT_BOTTOM, ROT_UP); blueSpawn[67] = np(); redSpawn[67] = np(); blueSpawn[68] = np(); redSpawn[68] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); blueSpawn[69] = np(); redSpawn[69] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[70] = sp(CLOSE_LEFT_BOTTOM, ROT_DOWN); redSpawn[70] = np(); blueSpawn[71] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[71] = np(); blueSpawn[72] = np(); redSpawn[72] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); blueSpawn[73] = np(); redSpawn[73] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[74] = sp(CLOSE_LEFT_BOTTOM, ROT_DOWN); redSpawn[74] = np(); blueSpawn[75] = np(); redSpawn[75] = sp(FAR_RIGHT_TOP, ROT_LEFT); blueSpawn[76] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[76] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[77] = np(); redSpawn[77] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); blueSpawn[78] = sp(CLOSE_LEFT_BOTTOM, ROT_RIGHT); redSpawn[78] = np(); blueSpawn[79] = np(); redSpawn[79] = sp(FAR_RIGHT_TOP, ROT_LEFT); blueSpawn[80] = np(); redSpawn[80] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[81] = sp(FAR_LEFT_BOTTOM, ROT_UP); redSpawn[81] = np(); blueSpawn[82] = np(); redSpawn[82] = np(); blueSpawn[83] = np(); redSpawn[83] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); blueSpawn[84] = np(); redSpawn[84] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[85] = sp(CLOSE_LEFT_BOTTOM, ROT_DOWN); redSpawn[85] = np(); blueSpawn[86] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[86] = np(); // 57 "can't convince you" blueSpawn[87] = np(); redSpawn[87] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); blueSpawn[88] = np(); redSpawn[88] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[89] = sp(FAR_LEFT_TOP, ROT_RIGHT); redSpawn[89] = np(); blueSpawn[90] = np(); redSpawn[90] = sp(FAR_RIGHT_TOP, ROT_LEFT); blueSpawn[91] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[91] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[92] = sp(CLOSE_LEFT_BOTTOM, ROT_DOWN); redSpawn[92] = np(); blueSpawn[93] = np(); redSpawn[93] = sp(FAR_RIGHT_TOP, ROT_LEFT); blueSpawn[94] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[94] = np(); blueSpawn[95] = sp(FAR_LEFT_TOP, ROT_DOWN); redSpawn[95] = np(); blueSpawn[96] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[96] = np(); blueSpawn[97] = np(); redSpawn[97] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[98] = sp(CLOSE_LEFT_BOTTOM, ROT_DOWN); redSpawn[98] = np(); blueSpawn[99] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[99] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); blueSpawn[100] = np(); redSpawn[100] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[101] = sp(CLOSE_LEFT_BOTTOM, ROT_DOWN); redSpawn[101] = np(); blueSpawn[102] = np(); redSpawn[102] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); blueSpawn[103] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[103] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[104] = sp(FAR_LEFT_BOTTOM, ROT_RIGHT); redSpawn[104] = sp(FAR_RIGHT_BOTTOM, ROT_LEFT); blueSpawn[105] = sp(FAR_LEFT_BOTTOM, ROT_UP); redSpawn[105] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); // 1:05 "i got" blueSpawn[106] = sp(FAR_LEFT_BOTTOM, ROT_DOWN); redSpawn[106] = sp(FAR_RIGHT_BOTTOM, ROT_DOWN); blueSpawn[107] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); redSpawn[107] = sp(FAR_RIGHT_BOTTOM, ROT_UP); blueSpawn[108] = np(); redSpawn[108] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); blueSpawn[109] = sp(FAR_LEFT_TOP, ROT_RIGHT); redSpawn[109] = np(); blueSpawn[110] = np(); redSpawn[110] = sp(FAR_RIGHT_TOP, ROT_LEFT); blueSpawn[111] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[111] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[112] = np(); redSpawn[112] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); blueSpawn[113] = sp(FAR_LEFT_TOP, ROT_RIGHT); redSpawn[113] = np(); blueSpawn[114] = np(); redSpawn[114] = sp(FAR_RIGHT_TOP, ROT_LEFT); blueSpawn[115] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[115] = np(); blueSpawn[116] = np(); redSpawn[116] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[117] = sp(FAR_LEFT_BOTTOM, ROT_RIGHT); redSpawn[117] = np(); blueSpawn[118] = np(); redSpawn[118] = sp(FAR_RIGHT_TOP, ROT_LEFT); blueSpawn[119] = sp(FAR_LEFT_BOTTOM, ROT_UP); redSpawn[119] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); blueSpawn[120] = sp(FAR_LEFT_TOP, ROT_DOWN); redSpawn[120] = sp(FAR_RIGHT_TOP, ROT_DOWN); blueSpawn[121] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); redSpawn[121] = sp(FAR_RIGHT_BOTTOM, ROT_UP); blueSpawn[122] = np(); redSpawn[122] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); blueSpawn[123] = sp(FAR_LEFT_TOP, ROT_RIGHT); redSpawn[123] = np(); blueSpawn[124] = np(); redSpawn[124] = sp(FAR_RIGHT_TOP, ROT_LEFT); blueSpawn[125] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[125] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[126] = np(); redSpawn[126] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); blueSpawn[127] = sp(FAR_LEFT_TOP, ROT_RIGHT); redSpawn[127] = np(); blueSpawn[128] = np(); redSpawn[128] = sp(FAR_RIGHT_TOP, ROT_LEFT); blueSpawn[129] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[129] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[130] = sp(FAR_LEFT_BOTTOM, ROT_RIGHT); redSpawn[130] = np(); blueSpawn[131] = np(); redSpawn[131] = np(); blueSpawn[132] = np(); redSpawn[132] = sp(FAR_RIGHT_TOP, ROT_LEFT); blueSpawn[133] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[133] = np(); blueSpawn[134] = np(); redSpawn[134] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[135] = sp(CLOSE_LEFT_BOTTOM, ROT_DOWN); redSpawn[135] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); blueSpawn[136] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[136] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); // 1:18 "end of i dont wanna be ignored" blueSpawn[137] = np(); redSpawn[137] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); blueSpawn[138] = sp(CLOSE_LEFT_BOTTOM, ROT_RIGHT); redSpawn[138] = np(); blueSpawn[139] = np(); redSpawn[139] = np(); blueSpawn[140] = np(); redSpawn[140] = sp(FAR_RIGHT_TOP, ROT_LEFT); blueSpawn[141] = np(); redSpawn[141] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[142] = sp(FAR_LEFT_BOTTOM, ROT_UP); redSpawn[142] = np(); blueSpawn[143] = np(); redSpawn[143] = np(); blueSpawn[144] = sp(CLOSE_LEFT_BOTTOM, ROT_DOWN); redSpawn[144] = np(); blueSpawn[145] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[145] = np(); blueSpawn[146] = np(); redSpawn[146] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); blueSpawn[147] = np(); redSpawn[147] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[148] = sp(CLOSE_LEFT_BOTTOM, ROT_DOWN); redSpawn[148] = np(); blueSpawn[149] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[149] = np(); blueSpawn[150] = np(); redSpawn[150] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); blueSpawn[151] = sp(FAR_LEFT_TOP, ROT_RIGHT); redSpawn[151] = np(); blueSpawn[152] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[152] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[153] = sp(CLOSE_LEFT_BOTTOM, ROT_DOWN); redSpawn[153] = np(); blueSpawn[154] = np(); redSpawn[154] = sp(CLOSE_RIGHT_BOTTOM, ROT_LEFT); blueSpawn[155] = np(); redSpawn[155] = np(); blueSpawn[156] = sp(FAR_LEFT_TOP, ROT_RIGHT); redSpawn[156] = np(); blueSpawn[157] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[157] = np(); blueSpawn[158] = np(); redSpawn[158] = sp(FAR_RIGHT_BOTTOM, ROT_UP); blueSpawn[159] = sp(CLOSE_LEFT_BOTTOM, ROT_DOWN); redSpawn[159] = np(); blueSpawn[160] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[160] = np(); blueSpawn[161] = np(); redSpawn[161] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); blueSpawn[162] = np(); redSpawn[162] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[163] = sp(CLOSE_LEFT_BOTTOM, ROT_DOWN); redSpawn[163] = np(); blueSpawn[164] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[164] = np(); blueSpawn[165] = np(); redSpawn[165] = sp(FAR_RIGHT_TOP, ROT_LEFT); blueSpawn[166] = sp(FAR_LEFT_TOP, ROT_RIGHT); redSpawn[166] = np(); blueSpawn[167] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[167] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[168] = np(); redSpawn[168] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); // 1:30 "so I" blueSpawn[169] = sp(FAR_LEFT_TOP, ROT_RIGHT); redSpawn[169] = np(); blueSpawn[170] = np(); redSpawn[170] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[171] = np(); redSpawn[171] = sp(FAR_RIGHT_TOP, ROT_DOWN); blueSpawn[172] = np(); redSpawn[172] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[173] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[173] = np(); blueSpawn[174] = np(); redSpawn[174] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); blueSpawn[175] = sp(CLOSE_LEFT_BOTTOM, ROT_DOWN); redSpawn[175] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[176] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[176] = np(); blueSpawn[177] = np(); redSpawn[177] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); blueSpawn[178] = sp(CLOSE_LEFT_BOTTOM, ROT_DOWN); redSpawn[178] = np(); blueSpawn[179] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[179] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[180] = np(); redSpawn[180] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); blueSpawn[181] = sp(FAR_LEFT_TOP, ROT_RIGHT); redSpawn[181] = np(); blueSpawn[182] = np(); redSpawn[182] = sp(FAR_RIGHT_TOP, ROT_LEFT); blueSpawn[183] = np(); redSpawn[183] = np(); blueSpawn[184] = sp(CLOSE_LEFT_BOTTOM, ROT_DOWN); redSpawn[184] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); blueSpawn[185] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[185] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[186] = sp(FAR_LEFT_TOP, ROT_DOWN); redSpawn[186] = sp(FAR_RIGHT_TOP, ROT_DOWN); blueSpawn[187] = sp(FAR_LEFT_BOTTOM, ROT_UP); redSpawn[187] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); blueSpawn[188] = sp(CLOSE_LEFT_BOTTOM, ROT_DOWN); redSpawn[188] = np(); blueSpawn[189] = np(); redSpawn[189] = sp(FAR_RIGHT_TOP, ROT_LEFT); blueSpawn[190] = sp(FAR_LEFT_TOP, ROT_RIGHT); redSpawn[190] = np(); blueSpawn[191] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[191] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[192] = sp(CLOSE_LEFT_BOTTOM, ROT_DOWN); redSpawn[192] = np(); blueSpawn[193] = np(); redSpawn[193] = sp(FAR_RIGHT_TOP, ROT_LEFT); blueSpawn[194] = sp(FAR_LEFT_TOP, ROT_RIGHT); redSpawn[194] = np(); blueSpawn[195] = np(); redSpawn[195] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[196] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[196] = np(); blueSpawn[197] = np(); redSpawn[197] = sp(FAR_RIGHT_BOTTOM, ROT_LEFT); blueSpawn[198] = sp(FAR_LEFT_TOP, ROT_RIGHT); redSpawn[198] = np(); blueSpawn[199] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); redSpawn[199] = sp(FAR_RIGHT_BOTTOM, ROT_UP); blueSpawn[200] = sp(FAR_LEFT_TOP, ROT_DOWN); redSpawn[200] = sp(FAR_RIGHT_TOP, ROT_DOWN); blueSpawn[201] = sp(FAR_LEFT_BOTTOM, ROT_UP); redSpawn[201] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); // 1:43 "i wont be ignored" blueSpawn[202] = sp(CLOSE_LEFT_BOTTOM, ROT_DOWN); redSpawn[202] = np(); blueSpawn[203] = np(); redSpawn[203] = sp(FAR_RIGHT_TOP, ROT_LEFT); blueSpawn[204] = sp(FAR_LEFT_TOP, ROT_RIGHT); redSpawn[204] = np(); blueSpawn[205] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[205] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[206] = sp(CLOSE_LEFT_BOTTOM, ROT_DOWN); redSpawn[206] = np(); blueSpawn[207] = np(); redSpawn[207] = sp(FAR_RIGHT_TOP, ROT_LEFT); blueSpawn[208] = sp(FAR_LEFT_TOP, ROT_RIGHT); redSpawn[208] = np(); blueSpawn[209] = np(); redSpawn[209] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[210] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[210] = np(); blueSpawn[211] = np(); redSpawn[211] = sp(FAR_RIGHT_BOTTOM, ROT_LEFT); blueSpawn[212] = sp(FAR_LEFT_TOP, ROT_RIGHT); redSpawn[212] = np(); blueSpawn[213] = np(); redSpawn[213] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[214] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[214] = np(); blueSpawn[215] = sp(CLOSE_LEFT_BOTTOM, ROT_DOWN); redSpawn[215] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); blueSpawn[216] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); redSpawn[216] = sp(FAR_RIGHT_BOTTOM, ROT_UP); blueSpawn[217] = np(); redSpawn[217] = sp(FAR_RIGHT_BOTTOM, ROT_DOWN); blueSpawn[218] = sp(FAR_LEFT_TOP, ROT_RIGHT); redSpawn[218] = sp(FAR_LEFT_BOTTOM, ROT_RIGHT); blueSpawn[219] = sp(FAR_RIGHT_BOTTOM, ROT_LEFT); redSpawn[219] = sp(FAR_RIGHT_TOP, ROT_LEFT); blueSpawn[220] = sp(CLOSE_LEFT_BOTTOM, ROT_RIGHT); redSpawn[220] = np(); blueSpawn[221] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[221] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[222] = np(); redSpawn[222] = np(); blueSpawn[223] = sp(FAR_LEFT_TOP, ROT_RIGHT); redSpawn[223] = sp(FAR_RIGHT_TOP, ROT_LEFT); blueSpawn[224] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[224] = np(); blueSpawn[225] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); redSpawn[225] = sp(FAR_RIGHT_BOTTOM, ROT_UP); blueSpawn[226] = sp(FAR_LEFT_BOTTOM, ROT_UP); redSpawn[226] = np(); blueSpawn[227] = sp(CLOSE_LEFT_BOTTOM, ROT_DOWN); redSpawn[227] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); blueSpawn[228] = np(); redSpawn[228] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); blueSpawn[229] = sp(FAR_LEFT_BOTTOM, ROT_UP); redSpawn[229] = np(); blueSpawn[230] = sp(CLOSE_LEFT_BOTTOM, ROT_DOWN); redSpawn[230] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); blueSpawn[231] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); redSpawn[231] = sp(FAR_RIGHT_BOTTOM, ROT_UP); blueSpawn[232] = np(); redSpawn[232] = sp(FAR_RIGHT_BOTTOM, ROT_DOWN); blueSpawn[233] = sp(FAR_LEFT_TOP, ROT_RIGHT); redSpawn[233] = sp(FAR_LEFT_BOTTOM, ROT_RIGHT); blueSpawn[234] = sp(FAR_RIGHT_BOTTOM, ROT_LEFT); redSpawn[234] = sp(FAR_RIGHT_TOP, ROT_LEFT); blueSpawn[235] = sp(CLOSE_LEFT_BOTTOM, ROT_RIGHT); redSpawn[235] = np(); blueSpawn[236] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[236] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[237] = np(); redSpawn[237] = np(); blueSpawn[238] = sp(FAR_LEFT_TOP, ROT_RIGHT); redSpawn[238] = sp(FAR_RIGHT_TOP, ROT_LEFT); blueSpawn[239] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[239] = np(); blueSpawn[240] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); redSpawn[240] = sp(FAR_RIGHT_BOTTOM, ROT_UP); blueSpawn[241] = sp(FAR_LEFT_BOTTOM, ROT_UP); redSpawn[241] = np(); blueSpawn[242] = sp(CLOSE_LEFT_BOTTOM, ROT_DOWN); redSpawn[242] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); // 2:01 "listen to me" blueSpawn[243] = np(); redSpawn[243] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); blueSpawn[244] = sp(FAR_LEFT_BOTTOM, ROT_UP); redSpawn[244] = np(); blueSpawn[245] = sp(CLOSE_LEFT_BOTTOM, ROT_DOWN); redSpawn[245] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); blueSpawn[246] = np(); redSpawn[246] = sp(FAR_RIGHT_BOTTOM, ROT_LEFT); blueSpawn[247] = sp(FAR_LEFT_BOTTOM, ROT_RIGHT); redSpawn[247] = np(); blueSpawn[248] = np(); redSpawn[248] = sp(FAR_RIGHT_BOTTOM, ROT_LEFT); blueSpawn[249] = np(); redSpawn[249] = np(); blueSpawn[250] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[250] = np(); blueSpawn[251] = np(); redSpawn[251] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[252] = sp(CLOSE_LEFT_BOTTOM, ROT_RIGHT); redSpawn[252] = np(); blueSpawn[253] = np(); redSpawn[253] = np(); blueSpawn[254] = np(); redSpawn[254] = sp(CLOSE_RIGHT_BOTTOM, ROT_LEFT); blueSpawn[255] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[255] = np(); blueSpawn[256] = np(); redSpawn[256] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[257] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); redSpawn[257] = sp(CLOSE_LEFT_BOTTOM, ROT_DOWN); // 2:07 big pause blueSpawn[258] = np(); redSpawn[258] = np(); blueSpawn[259] = np(); redSpawn[259] = np(); blueSpawn[260] = np(); redSpawn[260] = np(); blueSpawn[261] = np(); redSpawn[261] = np(); blueSpawn[262] = np(); redSpawn[262] = np(); blueSpawn[263] = np(); redSpawn[263] = np(); blueSpawn[264] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); redSpawn[264] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); blueSpawn[265] = sp(FAR_LEFT_TOP, ROT_DOWN); redSpawn[265] = sp(FAR_RIGHT_TOP, ROT_DOWN); blueSpawn[266] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); redSpawn[266] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); blueSpawn[267] = np(); redSpawn[267] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); blueSpawn[268] = sp(FAR_LEFT_TOP, ROT_RIGHT); redSpawn[268] = np(); blueSpawn[269] = np(); redSpawn[269] = sp(FAR_RIGHT_TOP, ROT_LEFT); blueSpawn[270] = np(); redSpawn[270] = np(); blueSpawn[271] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[271] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[272] = np(); redSpawn[272] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); blueSpawn[273] = sp(FAR_LEFT_TOP, ROT_RIGHT); redSpawn[273] = np(); blueSpawn[274] = np(); redSpawn[274] = sp(FAR_RIGHT_TOP, ROT_LEFT); blueSpawn[275] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[275] = np(); blueSpawn[276] = np(); redSpawn[276] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[277] = sp(FAR_LEFT_BOTTOM, ROT_RIGHT); redSpawn[277] = np(); blueSpawn[278] = np(); redSpawn[278] = np(); blueSpawn[279] = np(); redSpawn[279] = sp(FAR_RIGHT_TOP, ROT_LEFT); blueSpawn[280] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); redSpawn[280] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); blueSpawn[281] = sp(FAR_LEFT_TOP, ROT_DOWN); redSpawn[281] = sp(FAR_RIGHT_TOP, ROT_DOWN); blueSpawn[282] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); redSpawn[282] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); blueSpawn[283] = np(); redSpawn[283] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); blueSpawn[284] = sp(FAR_LEFT_TOP, ROT_RIGHT); redSpawn[284] = np(); blueSpawn[285] = np(); redSpawn[285] = sp(FAR_RIGHT_TOP, ROT_LEFT); blueSpawn[286] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[286] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[287] = np(); redSpawn[287] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); blueSpawn[288] = sp(FAR_LEFT_TOP, ROT_RIGHT); redSpawn[288] = np(); blueSpawn[289] = np(); redSpawn[289] = sp(FAR_RIGHT_TOP, ROT_LEFT); blueSpawn[290] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[290] = np(); blueSpawn[291] = np(); redSpawn[291] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[292] = sp(FAR_LEFT_BOTTOM, ROT_RIGHT); redSpawn[292] = np(); blueSpawn[293] = np(); redSpawn[293] = np(); blueSpawn[294] = np(); redSpawn[294] = sp(CLOSE_RIGHT_BOTTOM, ROT_DOWN); blueSpawn[295] = sp(FAR_RIGHT_BOTTOM, ROT_LEFT); redSpawn[295] = sp(FAR_RIGHT_TOP, ROT_LEFT); blueSpawn[296] = sp(FAR_LEFT_TOP, ROT_RIGHT); redSpawn[296] = sp(FAR_LEFT_BOTTOM, ROT_RIGHT); blueSpawn[297] = sp(FAR_RIGHT_BOTTOM, ROT_LEFT); redSpawn[297] = sp(FAR_RIGHT_TOP, ROT_LEFT); blueSpawn[298] = sp(CLOSE_LEFT_BOTTOM, ROT_RIGHT); redSpawn[298] = np(); blueSpawn[299] = np(); redSpawn[299] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[300] = np(); redSpawn[300] = np(); blueSpawn[301] = sp(CLOSE_RIGHT_BOTTOM, ROT_LEFT); redSpawn[301] = np(); blueSpawn[302] = sp(FAR_LEFT_TOP, ROT_RIGHT); redSpawn[302] = np(); blueSpawn[303] = np(); redSpawn[303] = sp(FAR_RIGHT_TOP, ROT_LEFT); blueSpawn[304] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[304] = np(); blueSpawn[305] = sp(FAR_LEFT_TOP, ROT_DOWN); redSpawn[305] = np(); blueSpawn[306] = np(); redSpawn[306] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[307] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[307] = np(); blueSpawn[308] = np(); redSpawn[308] = np(); blueSpawn[309] = sp(CLOSE_LEFT_BOTTOM, ROT_DOWN); redSpawn[309] = np(); blueSpawn[310] = sp(FAR_RIGHT_BOTTOM, ROT_LEFT); redSpawn[310] = sp(FAR_RIGHT_TOP, ROT_LEFT); blueSpawn[311] = sp(FAR_LEFT_TOP, ROT_RIGHT); redSpawn[311] = sp(FAR_LEFT_BOTTOM, ROT_RIGHT); blueSpawn[312] = sp(FAR_RIGHT_BOTTOM, ROT_LEFT); redSpawn[312] = sp(FAR_RIGHT_TOP, ROT_LEFT); blueSpawn[313] = sp(CLOSE_LEFT_BOTTOM, ROT_RIGHT); redSpawn[313] = np(); blueSpawn[314] = np(); redSpawn[314] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[315] = np(); redSpawn[315] = np(); blueSpawn[316] = sp(CLOSE_RIGHT_BOTTOM, ROT_LEFT); redSpawn[316] = np(); blueSpawn[317] = sp(FAR_LEFT_TOP, ROT_RIGHT); redSpawn[317] = np(); blueSpawn[318] = np(); redSpawn[318] = sp(FAR_RIGHT_TOP, ROT_LEFT); blueSpawn[319] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[319] = np(); blueSpawn[320] = sp(FAR_LEFT_TOP, ROT_DOWN); redSpawn[320] = np(); blueSpawn[321] = np(); redSpawn[321] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[322] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[322] = np(); blueSpawn[323] = np(); redSpawn[323] = sp(FAR_RIGHT_TOP, ROT_LEFT); blueSpawn[324] = sp(CLOSE_LEFT_BOTTOM, ROT_DOWN); redSpawn[324] = np(); blueSpawn[325] = np(); redSpawn[325] = sp(CLOSE_LEFT_BOTTOM, ROT_RIGHT); blueSpawn[326] = np(); redSpawn[326] = sp(FAR_RIGHT_TOP, ROT_LEFT); blueSpawn[327] = sp(CLOSE_LEFT_BOTTOM, ROT_UP); redSpawn[327] = np(); blueSpawn[328] = np(); redSpawn[328] = sp(CLOSE_RIGHT_BOTTOM, ROT_UP); blueSpawn[329] = sp(FAR_LEFT_TOP, ROT_RIGHT); redSpawn[329] = np(); blueSpawn[330] = np(); redSpawn[330] = np(); blueSpawn[331] = np(); redSpawn[331] = np(); blueSpawn[332] = np(); redSpawn[332] = np(); blueSpawn[333] = np(); redSpawn[333] = np(); blueSpawn[334] = np(); redSpawn[334] = np(); blueSpawn[335] = np(); redSpawn[335] = np(); blueSpawn[336] = np(); redSpawn[336] = np(); blueSpawn[337] = np(); redSpawn[337] = np(); blueSpawn[338] = np(); redSpawn[338] = np(); blueSpawn[339] = np(); redSpawn[339] = np(); started = 1; } }
65.123431
144
0.63542
[ "MIT" ]
fitancinpet/BeatSlasher
Assets/Scripts/SpawnLinkinParkBlocks.cs
31,131
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Kopigi.Utils.Extensions; using NFluent; using Xunit; namespace Kopigi.Utils.Tests.Extensions { public class ObservableCollectionExtensionsShould { [Fact] public void return_three_object_when_a_list_with_three_elements_are_added_to_observable_collection() { var list = new List<string>() { "first", "second", "third" }; var observable = new ObservableCollection<string>(); observable.AddRange(list); Check.That(observable.Count).IsEqualTo(3); } [Fact] public void check_that_first_element_in_observable_collection_is_the_same_in_list() { var list = new List<string>() { "first", "second", "third" }; var observable = new ObservableCollection<string>(); observable.AddRange(list); Check.That(observable.First()).IsEqualTo(list.First()); } } }
26.73913
108
0.582927
[ "MIT" ]
mplessis/kUtils
Kopigi.Utils.Tests/Extensions/ObservableCollectionExtensionsShould.cs
1,232
C#
namespace SPNATI_Character_Editor { partial class PersistentMarkerControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.recField = new Desktop.CommonControls.RecordField(); this.txtValue = new Desktop.Skinning.SkinnedTextBox(); this.cboOperator = new Desktop.Skinning.SkinnedComboBox(); this.skinnedLabel1 = new Desktop.Skinning.SkinnedLabel(); this.SuspendLayout(); // // recField // this.recField.AllowCreate = true; this.recField.Location = new System.Drawing.Point(192, 1); this.recField.Name = "recField"; this.recField.PlaceholderText = null; this.recField.Record = null; this.recField.RecordContext = null; this.recField.RecordFilter = null; this.recField.RecordKey = null; this.recField.RecordType = null; this.recField.Size = new System.Drawing.Size(98, 20); this.recField.TabIndex = 1; this.recField.UseAutoComplete = false; // // txtValue // this.txtValue.BackColor = System.Drawing.Color.White; this.txtValue.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F); this.txtValue.ForeColor = System.Drawing.Color.Black; this.txtValue.Location = new System.Drawing.Point(358, 0); this.txtValue.Name = "txtValue"; this.txtValue.Size = new System.Drawing.Size(78, 20); this.txtValue.TabIndex = 3; // // cboOperator // this.cboOperator.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.None; this.cboOperator.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.None; this.cboOperator.BackColor = System.Drawing.Color.White; this.cboOperator.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboOperator.FieldType = Desktop.Skinning.SkinnedFieldType.Surface; this.cboOperator.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F); this.cboOperator.FormattingEnabled = true; this.cboOperator.Location = new System.Drawing.Point(296, 0); this.cboOperator.Name = "cboOperator"; this.cboOperator.SelectedIndex = -1; this.cboOperator.SelectedItem = null; this.cboOperator.Size = new System.Drawing.Size(56, 21); this.cboOperator.Sorted = false; this.cboOperator.TabIndex = 2; // // skinnedLabel1 // this.skinnedLabel1.AutoSize = true; this.skinnedLabel1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F); this.skinnedLabel1.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(127)))), ((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(0))))); this.skinnedLabel1.Highlight = Desktop.Skinning.SkinnedHighlight.Label; this.skinnedLabel1.Level = Desktop.Skinning.SkinnedLabelLevel.Normal; this.skinnedLabel1.Location = new System.Drawing.Point(148, 3); this.skinnedLabel1.Name = "skinnedLabel1"; this.skinnedLabel1.Size = new System.Drawing.Size(43, 13); this.skinnedLabel1.TabIndex = 13; this.skinnedLabel1.Text = "Marker:"; // // PersistentMarkerControl // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.skinnedLabel1); this.Controls.Add(this.txtValue); this.Controls.Add(this.cboOperator); this.Controls.Add(this.recField); this.Name = "PersistentMarkerControl"; this.Size = new System.Drawing.Size(605, 21); this.Controls.SetChildIndex(this.recField, 0); this.Controls.SetChildIndex(this.cboOperator, 0); this.Controls.SetChildIndex(this.txtValue, 0); this.Controls.SetChildIndex(this.skinnedLabel1, 0); this.ResumeLayout(false); this.PerformLayout(); } #endregion private Desktop.CommonControls.RecordField recField; private Desktop.Skinning.SkinnedTextBox txtValue; private Desktop.Skinning.SkinnedComboBox cboOperator; private Desktop.Skinning.SkinnedLabel skinnedLabel1; } }
37.705882
154
0.72164
[ "MIT" ]
laytonc32/spnati
editor source/SPNATI Character Editor/Controls/EditControls/VariableControls/PersistentMarkerControl.Designer.cs
4,489
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; namespace Microsoft.Owin { /// <summary> /// A wrapper for the request Cookie header /// </summary> public class RequestCookieCollection : IEnumerable<KeyValuePair<string, string>> { /// <summary> /// Create a new wrapper /// </summary> /// <param name="store"></param> public RequestCookieCollection(IDictionary<string, string> store) { if (store == null) { throw new ArgumentNullException("store"); } Store = store; } private IDictionary<string, string> Store { get; set; } /// <summary> /// Returns null rather than throwing KeyNotFoundException /// </summary> /// <param name="key"></param> /// <returns></returns> public string this[string key] { get { string value; if (Store.TryGetValue(key, out value) || Store.TryGetValue(Uri.EscapeDataString(key), out value)) { return value; } return null; } } /// <summary> /// /// </summary> /// <returns></returns> public IEnumerator<KeyValuePair<string, string>> GetEnumerator() { return Store.GetEnumerator(); } /// <summary> /// /// </summary> /// <returns></returns> System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
27.477612
113
0.521456
[ "Apache-2.0" ]
Bouke/AspNetKatana
src/Microsoft.Owin/RequestCookieCollection.cs
1,843
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ClientManager : MonoBehaviour { public RealtimeManager realtime; public GameObject msgPrefab; public Button b_CreateSession; public Button b_SendMessage; public InputField inputField; public Transform msgBox; public Text t_KeepAliveCounter; private int keepAliveCounter; public Text t_GroupAliveCounter; private int groupAliveCounter; public Image toggle; private List<GameObject> msgs; void Start() { msgs = new List<GameObject>(); b_CreateSession.onClick.AddListener(() => CreateSession()); b_SendMessage.onClick.AddListener(() => SendMessage()); toggle.GetComponent<Button>().onClick.AddListener(() => ToggleTLS()); t_KeepAliveCounter.text = ""; t_GroupAliveCounter.text = ""; if(realtime.usingTLS) toggle.color = Color.blue; else toggle.color = Color.red; } void ToggleTLS() { if(realtime.isConnected()) return; if(realtime.usingTLS) { toggle.color = Color.red; realtime.usingTLS = false; } else { toggle.color = Color.blue; realtime.usingTLS = true; } } public void MessageReceived(string text) { GameObject x = Instantiate(msgPrefab, new Vector3(0,0,0), Quaternion.identity); x.transform.SetParent(msgBox, false); x.GetComponentInChildren<Text>().text = text; msgs.Add(x); if(msgs.Count > 7) { Destroy(msgs[0].gameObject); msgs.Remove(msgs[0]); msgs.TrimExcess(); } } void CreateSession() { realtime.StartSession(); b_CreateSession.onClick.RemoveAllListeners(); b_CreateSession.onClick.AddListener(() => JoinGroup()); b_CreateSession.GetComponentInChildren<Text>().text = "Join Group"; } void JoinGroup() { realtime.JoinGroupTen(); b_CreateSession.gameObject.SetActive(false); } void SendMessage() { if(!realtime.isConnected()) return; realtime.SendMessagePayload(inputField.text); inputField.text = ""; } public void KeepAlive() { keepAliveCounter++; t_KeepAliveCounter.text = ($"KeepAlives: {keepAliveCounter}"); } public void GroupAlive() { groupAliveCounter++; t_GroupAliveCounter.text = ($"GroupAlives: {groupAliveCounter}"); } }
25.019048
87
0.604872
[ "MIT" ]
SkyTech6/AWSRealTimeTLSTester
Assets/Scripts/ClientManager.cs
2,629
C#
//DPBMARK_FILE Open using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using Microsoft.AspNetCore.Mvc; using System.Xml; using System.Xml.Linq; using Senparc.Weixin.MP.MessageHandlers; using Senparc.Weixin.MP.MvcExtension; using Senparc.Weixin.Sample.CommonService.CustomMessageHandler; using Senparc.Weixin.Sample.CommonService.MessageHandlers.OpenMessageHandler; using Senparc.Weixin.Sample.CommonService.OpenTicket; using Senparc.Weixin.Open; using Senparc.Weixin.Open.MessageHandlers; using Senparc.Weixin.Sample.CommonService.ThirdPartyMessageHandlers; using Senparc.Weixin.Open.ComponentAPIs; using Senparc.Weixin.Open.Containers; using Senparc.Weixin.Open.Entities.Request; using Senparc.Weixin.HttpUtility; using Senparc.CO2NET.HttpUtility; using Senparc.Weixin.Open.AccountAPIs; using Senparc.CO2NET.Utilities; using System.Threading.Tasks; using Senparc.Weixin.MP.MessageContexts; using Senparc.CO2NET.AspNet.HttpUtility; namespace Senparc.Weixin.Sample.NetCore3.Controllers { /// <summary> /// 第三方开放平台演示 /// </summary> public class OpenController : Controller { private string component_AppId = Senparc.Weixin.Config.SenparcWeixinSetting.Component_Appid; private string component_Secret = Senparc.Weixin.Config.SenparcWeixinSetting.Component_Secret; private string component_Token = Senparc.Weixin.Config.SenparcWeixinSetting.Component_Token; private string component_EncodingAESKey = Senparc.Weixin.Config.SenparcWeixinSetting.Component_EncodingAESKey; /// <summary> /// 发起授权页的体验URL /// </summary> /// <returns></returns> public async Task<IActionResult> OAuth() { //获取预授权码 var preAuthCode = await ComponentContainer.TryGetPreAuthCodeAsync(component_AppId, component_Secret, true); var callbackUrl = "http://sdk.weixin.senparc.com/OpenOAuth/OpenOAuthCallback";//成功回调地址 var url = ComponentApi.GetComponentLoginPageUrl(component_AppId, preAuthCode, callbackUrl); return Redirect(url); } /// <summary> /// 发起小程序快速注册授权 /// </summary> /// <returns></returns> public ActionResult FastRegisterAuth() { var url = AccountApi.FastRegisterAuth(component_AppId, Config.SenparcWeixinSetting.WeixinAppId, true, "https://sdk.weixin.senparc.com"); return Redirect(url); } /// <summary> /// 微信服务器会不间断推送最新的Ticket(10分钟一次),需要在此方法中更新缓存 /// </summary> /// <returns></returns> [HttpPost] public ActionResult Notice(PostModel postModel) { var logPath = ServerUtility.ContentRootMapPath(string.Format("~/App_Data/Open/{0}/", SystemTime.Now.ToString("yyyy-MM-dd"))); if (!Directory.Exists(logPath)) { Directory.CreateDirectory(logPath); } //using (TextWriter tw = new StreamWriter(Path.Combine(logPath, string.Format("{0}_RequestStream.txt", SystemTime.Now.Ticks)))) //{ // using (var sr = new StreamReader(Request.InputStream)) // { // tw.WriteLine(sr.ReadToEnd()); // tw.Flush(); // } //} //Request.InputStream.Seek(0, SeekOrigin.Begin); try { postModel.Token = component_Token; postModel.EncodingAESKey = component_EncodingAESKey;//根据自己后台的设置保持一致 postModel.AppId = component_AppId;//根据自己后台的设置保持一致 var messageHandler = new CustomThirdPartyMessageHandler(Request.GetRequestMemoryStream(), postModel);//初始化 //注意:在进行“全网发布”时使用上面的CustomThirdPartyMessageHandler,发布完成之后使用正常的自定义的MessageHandler,例如下面一行。 //var messageHandler = new CommonService.CustomMessageHandler.CustomMessageHandler(Request.GetRequestMemoryStream(), // postModel, 10); //记录RequestMessage日志(可选) //messageHandler.EcryptRequestDocument.Save(Path.Combine(logPath, string.Format("{0}_Request.txt", SystemTime.Now.Ticks))); messageHandler.RequestDocument.Save(Path.Combine(logPath, string.Format("{0}_Request_{1}.txt", SystemTime.Now.Ticks, messageHandler.RequestMessage.AppId))); messageHandler.Execute();//执行 //记录ResponseMessage日志(可选) using (TextWriter tw = new StreamWriter(Path.Combine(logPath, string.Format("{0}_Response_{1}.txt", SystemTime.Now.Ticks, messageHandler.RequestMessage.AppId)))) { tw.WriteLine(messageHandler.ResponseMessageText); tw.Flush(); tw.Close(); } return Content(messageHandler.ResponseMessageText); } catch //(Exception ex) { throw; //return Content("error:" + ex.Message); } } /// <summary> /// 授权事件接收URL /// </summary> /// <param name="appId"></param> /// <returns></returns> [HttpPost] public async Task<ActionResult> Callback(Senparc.Weixin.MP.Entities.Request.PostModel postModel) { //此处的URL格式类型为:http://sdk.weixin.senparc.com/Open/Callback/$APPID$, 在RouteConfig中进行了配置,你也可以用自己的格式,只要和开放平台设置的一致。 //处理微信普通消息,可以直接使用公众号的MessageHandler。此处的URL也可以直接填写公众号普通的URL,如本Demo中的/Weixin访问地址。 var logPath = ServerUtility.ContentRootMapPath(string.Format("~/App_Data/Open/{0}/", SystemTime.Now.ToString("yyyy-MM-dd"))); if (!Directory.Exists(logPath)) { Directory.CreateDirectory(logPath); } postModel.Token = component_Token; postModel.EncodingAESKey = component_EncodingAESKey; //根据自己后台的设置保持一致 postModel.AppId = component_AppId; //根据自己后台的设置保持一致 var maxRecordCount = 10; MessageHandler<CustomMessageContext> messageHandler = null; try { var checkPublish = false; //是否在“全网发布”阶段 if (checkPublish) { messageHandler = new OpenCheckMessageHandler(Request.GetRequestMemoryStream(), postModel, 10); } else { messageHandler = new CustomMessageHandler(Request.GetRequestMemoryStream(), postModel, maxRecordCount); } messageHandler.SaveRequestMessageLog();//记录 Request 日志(可选) await messageHandler.ExecuteAsync(new System.Threading.CancellationToken());//执行微信处理过程(关键) messageHandler.SaveResponseMessageLog();//记录 Response 日志(可选) return new FixWeixinBugWeixinResult(messageHandler); } catch (Exception ex) { using ( TextWriter tw = new StreamWriter(ServerUtility.ContentRootMapPath("~/App_Data/Open/Error_" + SystemTime.Now.Ticks + ".txt"))) { tw.WriteLine("ExecptionMessage:" + ex.Message); tw.WriteLine(ex.Source); tw.WriteLine(ex.StackTrace); //tw.WriteLine("InnerExecptionMessage:" + ex.InnerException.Message); if (messageHandler.ResponseDocument != null) { tw.WriteLine(messageHandler.ResponseDocument.ToString()); } if (ex.InnerException != null) { tw.WriteLine("========= InnerException ========="); tw.WriteLine(ex.InnerException.Message); tw.WriteLine(ex.InnerException.Source); tw.WriteLine(ex.InnerException.StackTrace); } tw.Flush(); tw.Close(); return Content(""); } } } } }
39.668293
177
0.603296
[ "Apache-2.0" ]
554393109/WeiXinMPSDK
Samples/netcore3.1-mvc/Senparc.Weixin.Sample.NetCore3/Controllers/Weixin/Open/OpenController.cs
8,776
C#
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Linq; namespace Graphs.Elements { [DebuggerDisplay("{SourceId} : {TargetId}")] [JsonObject("edge")] public sealed class Edge<TId> : MutableElement<TId> , IEdge<TId> , IEquatable<Edge<TId>> , IEqualityComparer<Edge<TId>> where TId : struct, IComparable, IComparable<TId>, IEquatable<TId>, IFormattable { /// <summary> /// Creates an edge from two nodes. Defaults to directed edge. /// </summary> /// <param name="source"><see cref="Node"/></param> /// <param name="target"><see cref="Node"/></param> /// <returns><see cref="Edge"/></returns> internal static Edge<TId> Couple(IIdGenerator<TId> idGenerator, Node<TId> source, Node<TId> target) { return Couple(idGenerator, source, target, true); } /// <summary> /// Creates an edge from two nodes. /// </summary> /// <param name="source"><see cref="Node"/></param> /// <param name="target"><see cref="Node"/></param> /// <param name="isDirected"><see cref="Boolean"/></param> /// <returns><see cref="Edge"/></returns> internal static Edge<TId> Couple(IIdGenerator<TId> idGenerator, Node<TId> source, Node<TId> target, bool isDirected) { if (idGenerator is null) { throw new ArgumentNullException(nameof(idGenerator)); } if (source is null) { throw new ArgumentNullException(nameof(source)); } if (target is null) { throw new ArgumentNullException(nameof(target)); } var edge = new Edge<TId>(idGenerator.NewId(), source.Id, target.Id, isDirected); source.Couple(edge); target.Couple(edge); return edge; } internal void Decouple(Node<TId> node1, Node<TId> node2) { if (node1 is null) { throw new ArgumentNullException(nameof(node1)); } if (node2 is null) { throw new ArgumentNullException(nameof(node2)); } if (!this.Nodes.Contains(node1.Id)) { throw new InvalidOperationException($"{nameof(Node<TId>)} with id '{node1.Id}' is not incident to edge with id '{this.Id}'."); } if (!this.Nodes.Contains(node2.Id)) { throw new InvalidOperationException($"{nameof(Node<TId>)} with id '{node2.Id}' is not incident to edge with id '{this.Id}'."); } node1.Decouple(this); node2.Decouple(this); } [Required] [JsonProperty("directed")] public bool IsDirected { get; } [Pure] [JsonIgnore] public IEnumerable<TId> Nodes { get { yield return this.SourceId; yield return this.TargetId; } } [Required] [JsonProperty("source")] public TId SourceId { get; } [Required] [JsonProperty("target")] public TId TargetId { get; } // internal for testing [JsonConstructor] internal Edge(TId id, TId sourceId, TId targetId, bool isDirected) : base(id) { this.SourceId = sourceId; this.TargetId = targetId; this.IsDirected = isDirected; } private Edge([DisallowNull] Edge<TId> other) : base(other) { this.SourceId = other.SourceId; this.TargetId = other.TargetId; this.IsDirected = other.IsDirected; } [Pure] public override object Clone() { return new Edge<TId>(this); } [Pure] public bool IsIncident(TId nodeId) { return this.SourceId.Equals(nodeId) || this.TargetId.Equals(nodeId); } [Pure] public bool Equals([Pure] Edge<TId> other) { return other != null && this.Id.Equals(other.Id) && this.SourceId.Equals(other.SourceId) && this.TargetId.Equals(other.TargetId) && this.IsDirected == other.IsDirected; } [Pure] public bool Equals([Pure] Edge<TId> x, [Pure] Edge<TId> y) { return x != null && x.Equals(y); } [Pure] public override bool Equals([Pure] object obj) { return obj is Edge<TId> edge && this.Equals(edge); } [Pure] public int GetHashCode([DisallowNull, Pure] Edge<TId> obj) { return obj is null ? throw new ArgumentNullException(nameof(obj)) : obj.GetHashCode(); } [Pure] public override int GetHashCode() { return HashCode.Combine( this.Id, this.SourceId, this.TargetId, this.IsDirected); } } }
29.36612
142
0.520841
[ "MIT" ]
marklauter/giraffe
src/Graph.Elements/Elements/Edges/Edge{TId}.cs
5,376
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //Internal.Runtime.Augments //------------------------------------------------- // Why does this exist?: // Internal.Reflection.Execution cannot physically live in System.Private.CoreLib.dll // as it has a dependency on System.Reflection.Metadata. It's inherently // low-level nature means, however, it is closely tied to System.Private.CoreLib.dll. // This contract provides the two-communication between those two .dll's. // // // Implemented by: // System.Private.CoreLib.dll // // Consumed by: // Reflection.Execution.dll using System; namespace Internal.Runtime.Augments { [CLSCompliant(false)] public abstract class ReflectionExecutionDomainCallbacks { /// <summary> /// Register reflection module. Not thread safe with respect to reflection runtime. /// </summary> /// <param name="moduleHandle">Handle of module to register</param> public abstract void RegisterModule(IntPtr moduleHandle); // Api's that are exposed in System.Runtime but are really reflection apis. public abstract Object ActivatorCreateInstance(Type type, Object[] args); public abstract Type GetType(String typeName, bool throwOnError, bool ignoreCase); // Access to reflection mapping tables. public abstract bool TryGetArrayTypeForElementType(RuntimeTypeHandle elementTypeHandle, out RuntimeTypeHandle arrayTypeHandle); public abstract bool TryGetArrayTypeElementType(RuntimeTypeHandle arrayTypeHandle, out RuntimeTypeHandle elementTypeHandle); public abstract bool TryGetMultiDimArrayTypeForElementType(RuntimeTypeHandle elementTypeHandle, int rank, out RuntimeTypeHandle arrayTypeHandle); public abstract bool TryGetMultiDimArrayTypeElementType(RuntimeTypeHandle arrayTypeHandle, int rank, out RuntimeTypeHandle elementTypeHandle); public abstract bool TryGetPointerTypeForTargetType(RuntimeTypeHandle targetTypeHandle, out RuntimeTypeHandle pointerTypeHandle); public abstract bool TryGetPointerTypeTargetType(RuntimeTypeHandle pointerTypeHandle, out RuntimeTypeHandle targetTypeHandle); public abstract bool TryGetConstructedGenericTypeComponents(RuntimeTypeHandle runtimeTypeHandle, out RuntimeTypeHandle genericTypeDefinitionHandle, out RuntimeTypeHandle[] genericTypeArgumentHandles); public abstract bool TryGetConstructedGenericTypeForComponents(RuntimeTypeHandle genericTypeDefinitionHandle, RuntimeTypeHandle[] genericTypeArgumentHandles, out RuntimeTypeHandle runtimeTypeHandle); public abstract IntPtr TryGetDefaultConstructorForType(RuntimeTypeHandle runtimeTypeHandle); public abstract IntPtr TryGetDefaultConstructorForTypeUsingLocator(object canonEquivalentEntryLocator); public abstract IntPtr TryGetStaticClassConstructionContext(RuntimeTypeHandle runtimeTypeHandle); public abstract bool IsReflectionBlocked(RuntimeTypeHandle typeHandle); public abstract bool TryGetMetadataNameForRuntimeTypeHandle(RuntimeTypeHandle rtth, out string name); // Generic Virtual Method Support public abstract bool TryGetGenericVirtualTargetForTypeAndSlot(RuntimeTypeHandle targetHandle, ref RuntimeTypeHandle declaringType, RuntimeTypeHandle[] genericArguments, ref string methodName, ref IntPtr methodSignature, out IntPtr methodPointer, out IntPtr dictionaryPointer, out bool slotUpdated); // Flotsam and jetsam. public abstract Exception CreateMissingMetadataException(Type typeWithMissingMetadata); public abstract Exception CreateMissingArrayTypeException(Type elementType, bool isMultiDim, int rank); public abstract Exception CreateMissingConstructedGenericTypeException(Type genericTypeDefinition, Type[] genericTypeArguments); public abstract Type CreateShadowRuntimeInspectionOnlyNamedTypeIfAvailable(RuntimeTypeHandle runtimeTypeHandle); public abstract EnumInfo GetEnumInfoIfAvailable(Type enumType); public abstract String GetBetterDiagnosticInfoIfAvailable(RuntimeTypeHandle runtimeTypeHandle); public abstract String GetMethodNameFromStartAddressIfAvailable(IntPtr methodStartAddress); public abstract int ValueTypeGetHashCodeUsingReflection(object valueType); public abstract bool ValueTypeEqualsUsingReflection(object left, object right); } }
61.148649
306
0.787403
[ "MIT" ]
ZZHGit/corert
src/System.Private.CoreLib/src/Internal/Runtime/Augments/ReflectionExecutionDomainCallbacks.cs
4,527
C#
namespace Microsoft.Band.Portable.Sensors { public class BandPedometerReading : IBandSensorReading { internal BandPedometerReading(long total, long stepsToday) { TotalSteps = total; StepsToday = stepsToday; } public long TotalSteps { get; private set; } public long StepsToday { get; private set; } public override string ToString() { return $"TotalSteps={TotalSteps}, StepsToday={StepsToday}"; } } }
27.105263
71
0.605825
[ "Apache-2.0" ]
cahernanz/MS-Band-SDK
Microsoft.Band.Portable/Microsoft.Band.Portable/Sensors/BandPedometerReading.cs
517
C#
using System; using System.Threading; using Microsoft.Extensions.Logging; namespace Inasync.Logging { /// <summary> /// ログをメッセージに変換し、<see cref="MessageProcessor{TMessage}"/> のキューに追加するロガー。 /// </summary> public sealed class LogMessageLogger : ILogger { private readonly string _categoryName; private readonly MessageProcessor<LogMessage> _messageProcessor; /// <summary> /// <see cref="LogMessageLogger"/> クラスの新しいインスタンスを初期化します。 /// </summary> /// <param name="categoryName">カテゴリ名。</param> /// <param name="messageProcessor">ログ メッセージをバックグラウンドで処理するメッセージ プロセッサー。</param> public LogMessageLogger(string categoryName, MessageProcessor<LogMessage> messageProcessor) { _categoryName = categoryName ?? throw new ArgumentNullException(nameof(categoryName)); _messageProcessor = messageProcessor ?? throw new ArgumentNullException(nameof(messageProcessor)); } /// <inheritdoc /> public IDisposable BeginScope<TState>(TState state) { return NullScope.Instance; } /// <inheritdoc /> public bool IsEnabled(LogLevel logLevel) { if (logLevel == LogLevel.None) { return false; } return true; } /// <inheritdoc /> public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter) { if (formatter == null) { throw new ArgumentNullException(nameof(formatter)); } if (!IsEnabled(logLevel)) { return; } var message = formatter(state, exception); if (string.IsNullOrEmpty(message) && exception == null) { return; } _messageProcessor.TryPost(new LogMessage(_categoryName, logLevel, eventId, message, exception, DateTimeOffset.Now), timeout: Timeout.Infinite); } } }
39.791667
155
0.651832
[ "MIT" ]
in-async/Logging.BackgroundLogger
Inasync.Logging.Chatwork/Inasync.Logging/LogMessageLogger.cs
2,084
C#
/* 2011 - This file is part of AcaLabelPrint AcaLabelPrint is free Software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. AcaLabelprint is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with AcaLabelPrint. If not, see <http:www.gnu.org/licenses/>. We encourage you to use and extend the functionality of AcaLabelPrint, and send us an e-mail on the outlines of the extension you build. If it's generic, maybe we could add it to the project. Send your mail to the projectadmin at http:sourceforge.net/projects/labelprint/ */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace ACA.LabelX.Managers { public class LabelXRemoteControlManager { private static bool moetstoppen = false; public LabelXRemoteControlManager() { } public static void DoThreadWork() { LabelXRemoteControlManager theManager; theManager = new LabelXRemoteControlManager(); theManager.Start(); } public static void Stop() { moetstoppen = true; } public bool Start() { bool bRet = true; moetstoppen = false; string AppPath = GlobalDataStore.AppPath; GlobalDataStore.Logger.Warning("Starting the controller listener..."); try { ACA.LabelX.ClientEngine.Remote.AcaLabelXClientRemoteEngine eg = new ACA.LabelX.ClientEngine.Remote.AcaLabelXClientRemoteEngine(); eg.Start(AppPath + @"ACALabelXClientRemote.config.xml"); GlobalDataStore.Logger.Info("The controller listener is listening."); //This thread must be kept allive untit stoppen = true; while (!moetstoppen) { Thread.Sleep(100); } } catch (Exception e) { GlobalDataStore.Logger.Error(string.Format("Error: {0} Target site: {1} Stack trace: {2}", e.Message, e.TargetSite, e.StackTrace)); bRet = false; } return bRet; } } } /* AcaLabelPrint Copyright (C) 2011 Retailium Software Development BV. This program comes with ABSOLUTELY NO WARRANTY; This is free Software, and you are welcome to redistribute it under certain conditions. See the License.txt file or GNU GPL 3.0 License at <http://www.gnu.org/licenses>*/
35.707317
147
0.647883
[ "Apache-2.0" ]
mvendert/LabelPrint
ACALabelXClient/LabelXRemoteControlManager.cs
2,928
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using System.Threading.Tasks.Dataflow; using System.Windows.Controls; using Microsoft.VisualStudio.PlatformUI; using Microsoft.VisualStudio.ProjectSystem.Debug; using Moq; using Moq.Protected; using Xunit; namespace Microsoft.VisualStudio.ProjectSystem.VS.PropertyPages { public class DebugPageViewModelTests { private class ViewModelData { public IList<ILaunchProfile>? Profiles { get; set; } public ILaunchSettingsProvider? ProfileProvider { get; set; } public ILaunchSettings? LaunchProfiles { get; set; } public IList<Lazy<ILaunchSettingsUIProvider, IOrderPrecedenceMetadataView>> UIProviders { get; set; } = new List<Lazy<ILaunchSettingsUIProvider, IOrderPrecedenceMetadataView>>(); public TaskCompletionSource<bool>? FirstSnapshotComplete { get; set; } } private class EmptyDisposable : IDisposable { public void Dispose() {} } private static Mock<DebugPageViewModel> CreateViewModel(ViewModelData data) { // Setup the debug profiles var mockSourceBlock = new Mock<IReceivableSourceBlock<ILaunchSettings>>(); var mockProfiles = new Mock<ILaunchSettings>(); var project = UnconfiguredProjectFactory.Create(filePath: @"C:\Foo\foo.proj"); data.FirstSnapshotComplete = new TaskCompletionSource<bool>(); var viewModel = new Mock<DebugPageViewModel>(data.FirstSnapshotComplete, project); mockSourceBlock.Setup(m => m.LinkTo(It.IsAny<ITargetBlock<ILaunchSettings>>(), It.IsAny<DataflowLinkOptions>())).Callback ( (ITargetBlock<ILaunchSettings> targetBlock, DataflowLinkOptions options) => { targetBlock.Post(mockProfiles.Object); targetBlock.Complete(); } ).Returns(() => new EmptyDisposable()); mockProfiles.Setup(m => m.Profiles).Returns(() => { return data.Profiles?.ToImmutableList() ?? ImmutableList<ILaunchProfile>.Empty; }); data.LaunchProfiles = mockProfiles.Object; var mockProfileProvider = new Mock<ILaunchSettingsProvider>(); mockProfileProvider.SetupGet(m => m.SourceBlock).Returns(mockSourceBlock.Object); mockProfileProvider.SetupGet(m => m.CurrentSnapshot).Returns(data.LaunchProfiles); mockProfileProvider.Setup(m => m.UpdateAndSaveSettingsAsync(It.IsAny<ILaunchSettings>())).Callback((ILaunchSettings newProfiles) => { data.Profiles = new List<ILaunchProfile>(newProfiles.Profiles); } ).ReturnsAsync(() => { }).Verifiable(); data.ProfileProvider = mockProfileProvider.Object; viewModel.CallBase = true; viewModel.Protected().Setup<ILaunchSettingsProvider>("GetDebugProfileProvider").Returns(mockProfileProvider.Object); viewModel.Protected().Setup<IEnumerable<Lazy<ILaunchSettingsUIProvider, IOrderPrecedenceMetadataView>>>("GetUIProviders").Returns(data.UIProviders); return viewModel; } [Fact] public void DebugPageViewModel_UICommands() { var project = UnconfiguredProjectFactory.Create(filePath: @"C:\Foo\foo.proj"); var viewModel = new DebugPageViewModel(null, project); Assert.IsType<DelegateCommand>(viewModel.BrowseDirectoryCommand); Assert.IsType<DelegateCommand>(viewModel.BrowseExecutableCommand); Assert.IsType<DelegateCommand>(viewModel.NewProfileCommand); Assert.IsType<DelegateCommand>(viewModel.DeleteProfileCommand); } [Fact] public async Task DebugPageViewModel_NoProfiles() { var profiles = new List<ILaunchProfile>(); var viewModelData = new ViewModelData() { Profiles = profiles, }; var viewModel = CreateViewModel(viewModelData); await viewModel.Object.Initialize(); Assert.False(viewModel.Object.HasProfiles); Assert.False(viewModel.Object.IsProfileSelected); Assert.False(viewModel.Object.SupportsExecutable); Assert.False(viewModel.Object.HasLaunchOption); Assert.Equal(string.Empty, viewModel.Object.WorkingDirectory); Assert.Equal(string.Empty, viewModel.Object.LaunchPage); Assert.Equal(string.Empty, viewModel.Object.ExecutablePath); Assert.Equal(string.Empty, viewModel.Object.CommandLineArguments); } [Fact] public async Task DebugPageViewModel_PropertyChange() { var profiles = new List<ILaunchProfile>() { new LaunchProfile {Name="p1", CommandName="test", DoNotPersist = true} }; var viewModelData = new ViewModelData() { Profiles = profiles, UIProviders = new List<Lazy<ILaunchSettingsUIProvider, IOrderPrecedenceMetadataView>>() { new Lazy<ILaunchSettingsUIProvider, IOrderPrecedenceMetadataView>(() => { var uiProvider = new Mock<ILaunchSettingsUIProvider>(); uiProvider.Setup(m => m.CustomUI).Returns((UserControl?)null); uiProvider.Setup(m => m.ShouldEnableProperty(It.IsAny<string>())).Returns(true); uiProvider.Setup(m => m.CommandName).Returns("test"); return uiProvider.Object; }, new Mock<IOrderPrecedenceMetadataView>().Object) } }; var viewModel = CreateViewModel(viewModelData); await viewModel.Object.Initialize(); Assert.NotNull(viewModelData.FirstSnapshotComplete); await viewModelData.FirstSnapshotComplete!.Task; Assert.True(viewModel.Object.HasProfiles); Assert.True(viewModel.Object.IsProfileSelected); Assert.True(viewModel.Object.SelectedDebugProfile.IsInMemoryObject()); // Change a property, should trigger the selected profile to no longer be in-memory viewModel.Object.CommandLineArguments = "-arg"; Assert.False(viewModel.Object.SelectedDebugProfile.IsInMemoryObject()); } } }
46.624161
191
0.61998
[ "Apache-2.0" ]
MSLukeWest/project-system
tests/Microsoft.VisualStudio.ProjectSystem.Managed.VS.UnitTests/ProjectSystem/VS/PropertyPages/DebugPageViewModelTests.cs
6,801
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.FindUsages; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser.Lists; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using IServiceProvider = System.IServiceProvider; using Task = System.Threading.Tasks.Task; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser { internal abstract partial class AbstractObjectBrowserLibraryManager : AbstractLibraryManager, IDisposable { internal readonly VisualStudioWorkspace Workspace; internal ILibraryService LibraryService => _libraryService.Value; private readonly IServiceProvider _serviceProvider; private readonly Lazy<ILibraryService> _libraryService; private readonly string _languageName; private readonly __SymbolToolLanguage _preferredLanguage; private uint _classVersion; private uint _membersVersion; private uint _packageVersion; private ObjectListItem _activeListItem; private AbstractListItemFactory _listItemFactory; private object _classMemberGate = new object(); private readonly IEnumerable<Lazy<IStreamingFindUsagesPresenter>> _streamingPresenters; protected AbstractObjectBrowserLibraryManager( string languageName, Guid libraryGuid, __SymbolToolLanguage preferredLanguage, IServiceProvider serviceProvider, IComponentModel componentModel, VisualStudioWorkspace workspace) : base(libraryGuid, serviceProvider) { _languageName = languageName; _preferredLanguage = preferredLanguage; _serviceProvider = serviceProvider; Workspace = workspace; Workspace.WorkspaceChanged += OnWorkspaceChanged; _libraryService = new Lazy<ILibraryService>(() => Workspace.Services.GetLanguageServices(_languageName).GetService<ILibraryService>()); _streamingPresenters = componentModel.DefaultExportProvider.GetExports<IStreamingFindUsagesPresenter>(); } internal abstract AbstractDescriptionBuilder CreateDescriptionBuilder( IVsObjectBrowserDescription3 description, ObjectListItem listItem, Project project); internal abstract AbstractListItemFactory CreateListItemFactory(); private AbstractListItemFactory GetListItemFactory() { if (_listItemFactory == null) { _listItemFactory = CreateListItemFactory(); } return _listItemFactory; } public void Dispose() { this.Workspace.WorkspaceChanged -= OnWorkspaceChanged; } private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs e) { switch (e.Kind) { case WorkspaceChangeKind.DocumentChanged: // Ensure the text version actually changed. This is necessary to not // cause Class View to update simply when a document is opened. var oldDocument = e.OldSolution.GetDocument(e.DocumentId); var newDocument = e.NewSolution.GetDocument(e.DocumentId); // make sure we do this in background thread. we don't care about ordering of events // we just need to refresh OB at some point if it ever needs to be updated // link to the bug tracking root cause - https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=169649&_a=edit Task.Run(() => DocumentChangedAsync(oldDocument, newDocument)); break; case WorkspaceChangeKind.ProjectAdded: case WorkspaceChangeKind.ProjectChanged: case WorkspaceChangeKind.ProjectReloaded: case WorkspaceChangeKind.ProjectRemoved: UpdatePackageVersion(); break; case WorkspaceChangeKind.SolutionAdded: case WorkspaceChangeKind.SolutionChanged: case WorkspaceChangeKind.SolutionCleared: case WorkspaceChangeKind.SolutionReloaded: case WorkspaceChangeKind.SolutionRemoved: UpdatePackageVersion(); break; } } private async Task DocumentChangedAsync(Document oldDocument, Document newDocument) { try { var oldTextVersion = await oldDocument.GetTextVersionAsync(CancellationToken.None).ConfigureAwait(false); var newTextVersion = await newDocument.GetTextVersionAsync(CancellationToken.None).ConfigureAwait(false); if (oldTextVersion != newTextVersion) { UpdateClassAndMemberVersions(); } } catch (Exception e) when (FatalError.Report(e)) { // make it crash VS on any exception } } internal uint ClassVersion { get { lock (_classMemberGate) { return _classVersion; } } } internal uint MembersVersion { get { lock (_classMemberGate) { return _membersVersion; } } } internal uint PackageVersion { get { return _packageVersion; } } internal void UpdateClassAndMemberVersions() { lock (_classMemberGate) { UpdateClassVersion(); UpdateMembersVersion(); } } private void UpdateClassVersion() { _classVersion = unchecked(_classVersion + 1); } private void UpdateMembersVersion() { _membersVersion = unchecked(_membersVersion + 1); } internal void UpdatePackageVersion() { _packageVersion = unchecked(_packageVersion + 1); } internal void SetActiveListItem(ObjectListItem listItem) { _activeListItem = listItem; } private bool IsFindAllReferencesSupported() { if (_activeListItem == null) { return false; } return _activeListItem.SupportsFindAllReferences; } internal Project GetProject(ProjectId projectId) { return this.Workspace.CurrentSolution.GetProject(projectId); } internal Project GetProject(ObjectListItem listItem) { var projectId = listItem.ProjectId; if (projectId == null) { return null; } return this.GetProject(projectId); } internal Compilation GetCompilation(ProjectId projectId) { var project = GetProject(projectId); if (project == null) { return null; } return project .GetCompilationAsync(CancellationToken.None) .WaitAndGetResult_ObjectBrowser(CancellationToken.None); } public override uint GetLibraryFlags() { // Note: the legacy C# code also included LF_SUPPORTSLISTREFERENCES, // but that should be handled now by the FindResults LibraryManager. return (uint)_LIB_FLAGS.LF_PROJECT | (uint)_LIB_FLAGS.LF_EXPANDABLE | (uint)_LIB_FLAGS2.LF_SUPPORTSFILTERING | (uint)_LIB_FLAGS2.LF_SUPPORTSBASETYPES | (uint)_LIB_FLAGS2.LF_SUPPORTSINHERITEDMEMBERS | (uint)_LIB_FLAGS2.LF_SUPPORTSPRIVATEMEMBERS | (uint)_LIB_FLAGS2.LF_SUPPORTSPROJECTREFERENCES | (uint)_LIB_FLAGS2.LF_SUPPORTSCLASSDESIGNER; } protected override uint GetSupportedCategoryFields(uint category) { switch (category) { case (uint)LIB_CATEGORY.LC_MEMBERTYPE: return (uint)_LIBCAT_MEMBERTYPE.LCMT_METHOD | (uint)_LIBCAT_MEMBERTYPE.LCMT_FIELD | (uint)_LIBCAT_MEMBERTYPE.LCMT_PROPERTY; case (uint)LIB_CATEGORY.LC_MEMBERACCESS: return (uint)_LIBCAT_MEMBERACCESS.LCMA_PUBLIC | (uint)_LIBCAT_MEMBERACCESS.LCMA_PRIVATE | (uint)_LIBCAT_MEMBERACCESS.LCMA_PROTECTED | (uint)_LIBCAT_MEMBERACCESS.LCMA_PACKAGE | (uint)_LIBCAT_MEMBERACCESS.LCMA_SEALED; case (uint)_LIB_CATEGORY2.LC_MEMBERINHERITANCE: return (uint)_LIBCAT_MEMBERINHERITANCE.LCMI_IMMEDIATE | (uint)_LIBCAT_MEMBERINHERITANCE.LCMI_INHERITED; case (uint)LIB_CATEGORY.LC_CLASSACCESS: return (uint)_LIBCAT_CLASSACCESS.LCCA_PUBLIC | (uint)_LIBCAT_CLASSACCESS.LCCA_PROTECTED | (uint)_LIBCAT_CLASSACCESS.LCCA_PACKAGE | (uint)_LIBCAT_CLASSACCESS.LCCA_PRIVATE | (uint)_LIBCAT_CLASSACCESS.LCCA_SEALED; case (uint)LIB_CATEGORY.LC_CLASSTYPE: return (uint)_LIBCAT_CLASSTYPE.LCCT_CLASS | (uint)_LIBCAT_CLASSTYPE.LCCT_INTERFACE | (uint)_LIBCAT_CLASSTYPE.LCCT_ENUM | (uint)_LIBCAT_CLASSTYPE.LCCT_STRUCT | (uint)_LIBCAT_CLASSTYPE.LCCT_UNION | (uint)_LIBCAT_CLASSTYPE.LCCT_DELEGATE | (uint)_LIBCAT_CLASSTYPE.LCCT_MODULE; case (uint)LIB_CATEGORY.LC_ACTIVEPROJECT: return (uint)_LIBCAT_ACTIVEPROJECT.LCAP_SHOWALWAYS; case (uint)LIB_CATEGORY.LC_LISTTYPE: return (uint)_LIB_LISTTYPE.LLT_CLASSES | (uint)_LIB_LISTTYPE.LLT_NAMESPACES | (uint)_LIB_LISTTYPE.LLT_MEMBERS | (uint)_LIB_LISTTYPE.LLT_HIERARCHY | (uint)_LIB_LISTTYPE.LLT_PACKAGE; case (uint)LIB_CATEGORY.LC_VISIBILITY: return (uint)_LIBCAT_VISIBILITY.LCV_VISIBLE | (uint)_LIBCAT_VISIBILITY.LCV_HIDDEN; case (uint)LIB_CATEGORY.LC_MODIFIER: return (uint)_LIBCAT_MODIFIERTYPE.LCMDT_FINAL | (uint)_LIBCAT_MODIFIERTYPE.LCMDT_STATIC; case (uint)_LIB_CATEGORY2.LC_HIERARCHYTYPE: return (uint)_LIBCAT_HIERARCHYTYPE.LCHT_BASESANDINTERFACES | (uint)_LIBCAT_HIERARCHYTYPE.LCHT_PROJECTREFERENCES; case (uint)_LIB_CATEGORY2.LC_PHYSICALCONTAINERTYPE: return (uint)_LIBCAT_PHYSICALCONTAINERTYPE.LCPT_GLOBAL | (uint)_LIBCAT_PHYSICALCONTAINERTYPE.LCPT_PROJECT | (uint)_LIBCAT_PHYSICALCONTAINERTYPE.LCPT_PROJECTREFERENCE; } Debug.Fail("Unknown category: " + category.ToString()); return 0; } protected override IVsSimpleObjectList2 GetList(uint listType, uint flags, VSOBSEARCHCRITERIA2[] pobSrch) { var listKind = Helpers.ListTypeToObjectListKind(listType); if (Helpers.IsFindSymbol(flags)) { var projectAndAssemblySet = this.GetAssemblySet(this.Workspace.CurrentSolution, _languageName, CancellationToken.None); return GetSearchList(listKind, flags, pobSrch, projectAndAssemblySet); } if (listKind == ObjectListKind.Hierarchy) { return null; } Debug.Assert(listKind == ObjectListKind.Projects); return new ObjectList(ObjectListKind.Projects, flags, this, this.GetProjectListItems(this.Workspace.CurrentSolution, _languageName, flags, CancellationToken.None)); } protected override uint GetUpdateCounter() { return _packageVersion; } protected override int CreateNavInfo(SYMBOL_DESCRIPTION_NODE[] rgSymbolNodes, uint ulcNodes, out IVsNavInfo ppNavInfo) { Debug.Assert(rgSymbolNodes != null || ulcNodes > 0, "Invalid input parameters into CreateNavInfo"); ppNavInfo = null; var count = 0; string libraryName = null; string referenceOwnerName = null; if (rgSymbolNodes[0].dwType != (uint)_LIB_LISTTYPE.LLT_PACKAGE) { Debug.Fail("Symbol description should always contain LLT_PACKAGE node as first node"); return VSConstants.E_INVALIDARG; } else { count++; // If second node is also a package node, the below is the inference Node for // which NavInfo is generated is a 'referenced' node in CV // First package node ---> project item under which referenced node is displayed // Second package node ---> actual lib item node i.e., referenced assembly if (ulcNodes > 1 && rgSymbolNodes[1].dwType == (uint)_LIB_LISTTYPE.LLT_PACKAGE) { count++; referenceOwnerName = rgSymbolNodes[0].pszName; libraryName = rgSymbolNodes[1].pszName; } else { libraryName = rgSymbolNodes[0].pszName; } } var namespaceName = SharedPools.Default<StringBuilder>().AllocateAndClear(); var className = SharedPools.Default<StringBuilder>().AllocateAndClear(); var memberName = string.Empty; // Populate namespace, class and member names // Generate flattened names for nested namespaces and classes for (; count < ulcNodes; count++) { switch (rgSymbolNodes[count].dwType) { case (uint)_LIB_LISTTYPE.LLT_NAMESPACES: if (namespaceName.Length > 0) { namespaceName.Append("."); } namespaceName.Append(rgSymbolNodes[count].pszName); break; case (uint)_LIB_LISTTYPE.LLT_CLASSES: if (className.Length > 0) { className.Append("."); } className.Append(rgSymbolNodes[count].pszName); break; case (uint)_LIB_LISTTYPE.LLT_MEMBERS: if (memberName.Length > 0) { Debug.Fail("Symbol description cannot contain more than one LLT_MEMBERS node."); } memberName = rgSymbolNodes[count].pszName; break; } } // TODO: Make sure we pass the right value for Visual Basic. ppNavInfo = this.LibraryService.NavInfoFactory.Create(libraryName, referenceOwnerName, namespaceName.ToString(), className.ToString(), memberName); SharedPools.Default<StringBuilder>().ClearAndFree(namespaceName); SharedPools.Default<StringBuilder>().ClearAndFree(className); return VSConstants.S_OK; } internal IVsNavInfo GetNavInfo(SymbolListItem symbolListItem, bool useExpandedHierarchy) { var project = GetProject(symbolListItem); if (project == null) { return null; } var compilation = symbolListItem.GetCompilation(this.Workspace); if (compilation == null) { return null; } var symbol = symbolListItem.ResolveSymbol(compilation); if (symbol == null) { return null; } if (symbolListItem is MemberListItem) { return this.LibraryService.NavInfoFactory.CreateForMember(symbol, project, compilation, useExpandedHierarchy); } else if (symbolListItem is TypeListItem) { return this.LibraryService.NavInfoFactory.CreateForType((INamedTypeSymbol)symbol, project, compilation, useExpandedHierarchy); } else if (symbolListItem is NamespaceListItem) { return this.LibraryService.NavInfoFactory.CreateForNamespace((INamespaceSymbol)symbol, project, compilation, useExpandedHierarchy); } return this.LibraryService.NavInfoFactory.CreateForProject(project); } protected override bool TryQueryStatus(Guid commandGroup, uint commandId, ref OLECMDF commandFlags) { if (commandGroup == VsMenus.guidStandardCommandSet97) { switch (commandId) { case (uint)VSConstants.VSStd97CmdID.FindReferences: if (IsFindAllReferencesSupported()) { commandFlags = OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED; } else { commandFlags = OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_INVISIBLE; } return true; } } return false; } protected override bool TryExec(Guid commandGroup, uint commandId) { if (commandGroup == VsMenus.guidStandardCommandSet97) { switch (commandId) { case (uint)VSConstants.VSStd97CmdID.FindReferences: var streamingPresenter = _streamingPresenters.FirstOrDefault()?.Value; var symbolListItem = _activeListItem as SymbolListItem; if (streamingPresenter != null && symbolListItem?.ProjectId != null) { var project = this.Workspace.CurrentSolution.GetProject(symbolListItem.ProjectId); if (project != null) { // Note: we kick of FindReferencesAsync in a 'fire and forget' manner. // We don't want to block the UI thread while we compute the references, // and the references will be asynchronously added to the FindReferences // window as they are computed. The user also knows something is happening // as the window, with the progress-banner will pop up immediately. var task = FindReferencesAsync(streamingPresenter, symbolListItem, project); return true; } } break; } } return false; } private async Task FindReferencesAsync( IStreamingFindUsagesPresenter presenter, SymbolListItem symbolListItem, Project project) { try { // Let the presented know we're starting a search. It will give us back // the context object that the FAR service will push results into. var context = presenter.StartSearch( EditorFeaturesResources.Find_References, supportsReferences: true); var cancellationToken = context.CancellationToken; // Kick off the work to do the actual finding on a BG thread. That way we don' // t block the calling (UI) thread too long if we happen to do our work on this // thread. await Task.Run(async () => { await FindReferencesAsync(symbolListItem, project, context, cancellationToken).ConfigureAwait(false); }, cancellationToken).ConfigureAwait(false); // Note: we don't need to put this in a finally. The only time we might not hit // this is if cancellation or another error gets thrown. In the former case, // that means that a new search has started. We don't care about telling the // context it has completed. In the latter case something wrong has happened // and we don't want to run any more code in this particular context. await context.OnCompletedAsync().ConfigureAwait(false); } catch (OperationCanceledException) { } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { } } private static async Task FindReferencesAsync(SymbolListItem symbolListItem, Project project, CodeAnalysis.FindUsages.FindUsagesContext context, CancellationToken cancellationToken) { var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var symbol = symbolListItem.ResolveSymbol(compilation); if (symbol != null) { await AbstractFindUsagesService.FindSymbolReferencesAsync( context, symbol, project, cancellationToken).ConfigureAwait(false); } } } }
39.808362
189
0.568972
[ "Apache-2.0" ]
coreyramsey/roslyn
src/VisualStudio/Core/Def/Implementation/Library/ObjectBrowser/AbstractObjectBrowserLibraryManager.cs
22,852
C#
using System.Runtime.Serialization; using MFiles.VAF.Configuration; namespace ComplexConfiguration.ShowingAndHidingConfigurationOptions { [DataContract] public class HidingConfigurationOptions { /// <summary> /// Used as a trigger to show <see cref="AdvancedConfiguration"/>. /// </summary> /// <remarks>If true, <see cref="AdvancedConfiguration"/> will be shown in the administration area. If false then it will not.</remarks> [DataMember] [JsonConfEditor( DefaultValue = true, HelpText = "If true, the AdvancedConfiguration settings will be shown. If false (or not set) then it will not.")] public bool UsesAdvancedConfiguration { get; set; } = true; /// <summary> /// Shown only if <see cref="UsesAdvancedConfiguration"/> is true. /// </summary> [DataMember] [JsonConfEditor( Hidden = false, HideWhen = ".parent._children{.key == 'UsesAdvancedConfiguration' && .value != true }", HelpText = "This is hidden by default but shown if UsesAdvancedConfiguration is set to true.")] public AdvancedConfiguration AdvancedConfiguration { get; set; } } /// <summary> /// A dummy "advanced configuration" class. /// </summary> [DataContract] public class AdvancedConfiguration { /// <summary> /// A sample value that should only be populated in advanced configurations. /// </summary> [DataMember] public string Value { get; set; } } }
31.795455
139
0.708363
[ "MIT" ]
GeraldYoung/MFilesSamplesAndLibraries
Samples/VAF/ComplexConfiguration/ComplexConfiguration/ShowingAndHidingConfigurationOptions/HidingConfigurationOptions.cs
1,401
C#
using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Raven.Client.Documents.Session; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace RavenDbDotNetCore31APITemplate.Controllers { [ApiController] [Route("[controller]")] public class TestController : ControllerBase { private readonly IDocumentSession session; private readonly ILogger<TestController> _logger; public TestController(ILogger<TestController> logger, IDocumentSession documentSession) { _logger = logger; session = documentSession; } [HttpGet] public Test Create() { var test = new Test() { TestString = "blah blah blah" }; session.Store(test); session.SaveChanges(); return test; } } public class Test { public string TestString { get; set; } } }
22.688889
95
0.614104
[ "MIT" ]
ChristopherLlewellyn/RavenDbDotNetCore3.1APITemplate
RavenDbDotNetCore3.1APITemplate/Controllers/TestController.cs
1,023
C#
using System; namespace StoredProcedureEFCore { struct Prop { public int ColumnOrdinal { get; set; } public Action<object, object> Setter { get; set; } } }
15.636364
54
0.668605
[ "MIT" ]
h0wXD/StoredProcedureEFCore
StoredProcedureEFCore/Prop.cs
174
C#
// // NtlmAuthLevel.cs // // Author: // Martin Baulig <martin.baulig@xamarin.com> // // Copyright (c) 2012 Xamarin Inc. (http://www.xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; namespace Xamarin.WebTests.TestProvider.Ntlm { /* * On Windows, this is controlled by a registry setting * (http://msdn.microsoft.com/en-us/library/ms814176.aspx) * * This can be configured by setting the static * Type3Message.DefaultAuthLevel property, the default value * is LM_and_NTLM_and_try_NTLMv2_Session. */ enum NtlmAuthLevel { /* Use LM and NTLM, never use NTLMv2 session security. */ LM_and_NTLM, /* Use NTLMv2 session security if the server supports it, * otherwise fall back to LM and NTLM. */ LM_and_NTLM_and_try_NTLMv2_Session, /* Use NTLMv2 session security if the server supports it, * otherwise fall back to NTLM. Never use LM. */ NTLM_only, /* Use NTLMv2 only. */ NTLMv2_only, } }
35.642857
80
0.736473
[ "MIT" ]
stefb965/web-tests
Xamarin.WebTests.TestProvider/Xamarin.WebTests.TestProvider.Ntlm/NtlmAuthLevel.cs
1,998
C#
#pragma warning disable 1591 namespace Sanakan.Services.SlotMachine { public class SlotWickedRandom : ISlotRandom { public int Next(int min, int max) { double sum = 0; double rMax = 100; double[] chance = new double[max]; for (int i = 0; i < (max + 1); i++) sum += i; for (int i = 0; i < max; i++) chance[i] = (max-i)*(rMax/sum); int low = 0; int high = 0; int next = Services.Fun.GetRandomValue(min, (int)(rMax * 10)); for (int i = 0; i < max; i++) { if (i > 0) low = (int)(chance[i-1] * 10); high += (int)(chance[i] * 10); if (next >= low && next < high) return i; } return 0; } } }
28.793103
74
0.427545
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
Ainheg/sanakan
src/Services/SlotMachine/SlotWickedRandom.cs
835
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/msxml.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; using static TerraFX.Interop.Windows; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="DOMDocument" /> struct.</summary> public static unsafe class DOMDocumentTests { /// <summary>Validates that the <see cref="Guid" /> of the <see cref="DOMDocument" /> struct is correct.</summary> [Test] public static void GuidOfTest() { Assert.That(typeof(DOMDocument).GUID, Is.EqualTo(CLSID_DOMDocument)); } /// <summary>Validates that the <see cref="DOMDocument" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<DOMDocument>(), Is.EqualTo(sizeof(DOMDocument))); } /// <summary>Validates that the <see cref="DOMDocument" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(DOMDocument).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="DOMDocument" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { Assert.That(sizeof(DOMDocument), Is.EqualTo(1)); } } }
37
145
0.651051
[ "MIT" ]
phizch/terrafx.interop.windows
tests/Interop/Windows/um/msxml/DOMDocumentTests.cs
1,667
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using AYN.Data.Common.Models; using AYN.Data.Models.Enumerations; using Microsoft.AspNetCore.Identity; using static AYN.Common.AttributeConstraints; namespace AYN.Data.Models; public class ApplicationUser : IdentityUser, IAuditInfo, IDeletableEntity { public ApplicationUser() { this.Id = Guid .NewGuid() .ToString(); } public string ThumbnailImageUrl { get; set; } public string AvatarImageUrl { get; set; } [MaxLength(ApplicationUserSocialContactUrlMaxLength)] public string FacebookUrl { get; set; } [MaxLength(ApplicationUserSocialContactUrlMaxLength)] public string InstagramUrl { get; set; } [MaxLength(ApplicationUserSocialContactUrlMaxLength)] public string TikTokUrl { get; set; } [MaxLength(ApplicationUserSocialContactUrlMaxLength)] public string TwitterUrl { get; set; } [MaxLength(ApplicationUserSocialContactUrlMaxLength)] public string WebsiteUrl { get; set; } [Required] [MaxLength(ApplicationUserAboutMaxLength)] public string About { get; set; } [Required] [MaxLength(ApplicationUserFirstNameMaxLength)] public string FirstName { get; set; } [MaxLength(ApplicationUserMiddleNameMaxLength)] public string MiddleName { get; set; } [Required] [MaxLength(ApplicationUserLastNameMaxLength)] public string LastName { get; set; } [Required] public int TownId { get; set; } public virtual Town Town { get; set; } public DateTime? BirthDay { get; set; } [Required] public Gender Gender { get; set; } // Audit info [Required] public DateTime CreatedOn { get; set; } public DateTime? ModifiedOn { get; set; } // Deletable entity [Required] public bool IsDeleted { get; set; } public DateTime? DeletedOn { get; set; } [Required] public bool IsBanned { get; set; } public DateTime? BannedOn { get; set; } [MaxLength(ApplicationUserBlockReasonMaxLength)] public string BlockReason { get; set; } public virtual ICollection<IdentityUserRole<string>> Roles { get; set; } = new HashSet<IdentityUserRole<string>>(); public virtual ICollection<IdentityUserClaim<string>> Claims { get; set; } = new HashSet<IdentityUserClaim<string>>(); public virtual ICollection<IdentityUserLogin<string>> Logins { get; set; } = new HashSet<IdentityUserLogin<string>>(); public virtual ICollection<Ad> Ads { get; set; } = new HashSet<Ad>(); public virtual ICollection<FollowerFollowee> Followers { get; set; } = new HashSet<FollowerFollowee>(); public virtual ICollection<FollowerFollowee> Followings { get; set; } = new HashSet<FollowerFollowee>(); public virtual ICollection<Post> Posts { get; set; } = new HashSet<Post>(); public virtual ICollection<PostVote> PostVotes { get; set; } = new HashSet<PostVote>(); public virtual ICollection<PostReact> PostReacts { get; set; } = new HashSet<PostReact>(); public virtual ICollection<Wishlist> Wishlist { get; set; } = new HashSet<Wishlist>(); public virtual ICollection<UserAdView> UserAdViews { get; set; } = new HashSet<UserAdView>(); public ICollection<Message> SentMessages { get; set; } = new HashSet<Message>(); public ICollection<Message> ReceivedMessages { get; set; } = new HashSet<Message>(); }
28.296
78
0.681934
[ "MIT" ]
georgidelchev/AYN-
Data/AYN.Data.Models/ApplicationUser.cs
3,539
C#
/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using JsonSubTypes; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; namespace Org.OpenAPITools.Model { /// <summary> /// ChildCat /// </summary> [DataContract(Name = "ChildCat")] [JsonConverter(typeof(JsonSubtypes), "PetType")] public partial class ChildCat : ParentPet, IEquatable<ChildCat>, IValidatableObject { /// <summary> /// Defines PetType /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum PetTypeEnum { /// <summary> /// Enum ChildCat for value: ChildCat /// </summary> [EnumMember(Value = "ChildCat")] ChildCat = 1 } /// <summary> /// Gets or Sets PetType /// </summary> [DataMember(Name = "pet_type", IsRequired = true, EmitDefaultValue = false)] public PetTypeEnum PetType { get{ return _PetType;} set { _PetType = value; _flagPetType = true; } } private PetTypeEnum _PetType; private bool _flagPetType; /// <summary> /// Returns false as PetType should not be serialized given that it's read-only. /// </summary> /// <returns>false (boolean)</returns> public bool ShouldSerializePetType() { return _flagPetType; } /// <summary> /// Initializes a new instance of the <see cref="ChildCat" /> class. /// </summary> [JsonConstructorAttribute] protected ChildCat() { this.AdditionalProperties = new Dictionary<string, object>(); } /// <summary> /// Initializes a new instance of the <see cref="ChildCat" /> class. /// </summary> /// <param name="name">name.</param> /// <param name="petType">petType (required) (default to PetTypeEnum.ChildCat).</param> public ChildCat(string name = default(string), PetTypeEnum petType = PetTypeEnum.ChildCat) : base() { this._PetType = petType; this._Name = name; this.AdditionalProperties = new Dictionary<string, object>(); } /// <summary> /// Gets or Sets Name /// </summary> [DataMember(Name = "name", EmitDefaultValue = false)] public string Name { get{ return _Name;} set { _Name = value; _flagName = true; } } private string _Name; private bool _flagName; /// <summary> /// Returns false as Name should not be serialized given that it's read-only. /// </summary> /// <returns>false (boolean)</returns> public bool ShouldSerializeName() { return _flagName; } /// <summary> /// Gets or Sets additional properties /// </summary> [JsonExtensionData] public IDictionary<string, object> AdditionalProperties { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class ChildCat {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" PetType: ").Append(PetType).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public override string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return OpenAPIClientUtils.compareLogic.Compare(this, input as ChildCat).AreEqual; } /// <summary> /// Returns true if ChildCat instances are equal /// </summary> /// <param name="input">Instance of ChildCat to be compared</param> /// <returns>Boolean</returns> public bool Equals(ChildCat input) { return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = base.GetHashCode(); if (this.Name != null) hashCode = hashCode * 59 + this.Name.GetHashCode(); hashCode = hashCode * 59 + this.PetType.GetHashCode(); if (this.AdditionalProperties != null) hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext) { return this.BaseValidate(validationContext); } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> protected IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> BaseValidate(ValidationContext validationContext) { foreach(var x in BaseValidate(validationContext)) yield return x; yield break; } } }
33.830986
159
0.577435
[ "Apache-2.0" ]
AlexMog/openapi-generator
samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ChildCat.cs
7,206
C#
using System.ComponentModel.DataAnnotations; namespace Core.Data.Models { public class RegisterModel { [Required] public string UserName { get; set; } [Required] [EmailAddress] public string Email { get; set; } [Required] [DataType(DataType.Password)] public string Password { get; set; } [Required] [Compare("Password")] [DataType(DataType.Password)] public string ConfirmPassword { get; set; } public bool SetAsAdmin { get; set; } } public class ChangePasswordModel { [Required] public string UserName { get; set; } [Required] [DataType(DataType.Password)] [Display(Name = "Current password")] public string OldPassword { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 4)] [DataType(DataType.Password)] [Display(Name = "New password")] public string NewPassword { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm new password")] [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } }
28.595745
125
0.600446
[ "MIT" ]
BattlerockStudios/Blogifier
src/Core/Data/Models/AccountModel.cs
1,346
C#
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // 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("Example")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Example")] [assembly: AssemblyCopyright("Copyright © 2016")] [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)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // 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")]
43.303571
99
0.689897
[ "MIT" ]
Epxoxy/Epx017
Example/Properties/AssemblyInfo.cs
2,428
C#
using System.Collections; using System.Collections.Generic; using ActionsList; using Actions; using Arcs; namespace Ship { namespace SecondEdition.YV666LightFreighter { public class YV666LightFreighter : FirstEdition.YV666.YV666 { public YV666LightFreighter() : base() { ShipInfo.ShipName = "YV-666 Light Freighter"; ShipInfo.ArcInfo = new ShipArcsInfo(ArcType.FullFront, 3); ShipInfo.Hull = 9; ShipInfo.Shields = 3; ShipInfo.ActionIcons.AddActions(new ActionInfo(typeof(ReinforceAction))); IconicPilots[Faction.Scum] = typeof(Bossk); ManeuversImageUrl = "https://vignette.wikia.nocookie.net/xwing-miniatures-second-edition/images/2/2f/Maneuver_yv-666.png"; OldShipTypeName = "YV-666"; } } } }
29.966667
138
0.612903
[ "MIT" ]
GeneralVryth/FlyCasual
Assets/Scripts/Model/Content/SecondEdition/Ships/YV666LightFreighter.cs
901
C#
//------------------------------------------------------------------------------ // <auto-generated> // Este código fue generado por una herramienta. // Versión de runtime: 4.0.30319.42000 // // Los cambios de este archivo pueden provocar un comportamiento inesperado y se perderán si // el código se vuelve a generar. // </auto-generated> //------------------------------------------------------------------------------ namespace EstructurasBasicas.Properties { /// <summary> /// Clase de recurso fuertemente tipado para buscar cadenas traducidas, etc. /// </summary> // StronglyTypedResourceBuilder generó automáticamente esta clase // a través de una herramienta como ResGen o Visual Studio. // Para agregar o quitar un miembro, edite el archivo .ResX y, a continuación, vuelva a ejecutar ResGen // con la opción /str o recompile su proyecto de VS. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Devuelve la instancia ResourceManager almacenada en caché utilizada por esta clase. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("EstructurasBasicas.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Invalida la propiedad CurrentUICulture del subproceso actual para todas las /// búsquedas de recursos usando esta clase de recursos fuertemente tipados. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
40.583333
184
0.618412
[ "MIT" ]
kurotori/CSharpBachillerato
01 - EstructurasBasicas/EstructurasBasicas/Properties/Resources.Designer.cs
2,935
C#
using UnityEngine; namespace UnityEngine.Rendering.Universal { /// <summary> /// Interface for determining what kind of debug settings are currently active. /// </summary> public interface IDebugDisplaySettingsQuery { /// <summary> /// Checks whether ANY of the debug settings are currently active. /// </summary> bool AreAnySettingsActive { get; } /// <summary> /// Checks whether the current state of these settings allows post-processing. /// </summary> bool IsPostProcessingAllowed { get; } /// <summary> /// Checks whether lighting is active for these settings. /// </summary> bool IsLightingActive { get; } /// <summary> /// Attempts to get the color used to clear the screen for this debug setting. /// </summary> /// <param name="color">A reference to the screen clear color to use.</param> /// <returns>"true" if we updated the color, "false" if we didn't change anything.</returns> bool TryGetScreenClearColor(ref Color color); } }
33.757576
100
0.617594
[ "MIT" ]
Liaoer/ToonShader
Packages/com.unity.render-pipelines.universal@12.1.3/Runtime/Debug/IDebugDisplaySettingsQuery.cs
1,114
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.ApplicationInsights.Query { using Microsoft.Rest; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// Events operations. /// </summary> public partial class Events : IServiceOperations<ApplicationInsightsDataClient>, IEvents { /// <summary> /// Initializes a new instance of the Events class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public Events(ApplicationInsightsDataClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the ApplicationInsightsDataClient /// </summary> public ApplicationInsightsDataClient Client { get; private set; } /// <summary> /// Execute OData query /// </summary> /// <remarks> /// Executes an OData query for events /// </remarks> /// <param name='appId'> /// ID of the application. This is Application ID from the API Access settings /// blade in the Azure portal. /// </param> /// <param name='eventType'> /// The type of events to query; either a standard event type (`traces`, /// `customEvents`, `pageViews`, `requests`, `dependencies`, `exceptions`, /// `availabilityResults`) or `$all` to query across all event types. Possible /// values include: '$all', 'traces', 'customEvents', 'pageViews', /// 'browserTimings', 'requests', 'dependencies', 'exceptions', /// 'availabilityResults', 'performanceCounters', 'customMetrics' /// </param> /// <param name='timespan'> /// Optional. The timespan over which to retrieve events. This is an ISO8601 /// time period value. This timespan is applied in addition to any that are /// specified in the Odata expression. /// </param> /// <param name='filter'> /// An expression used to filter the returned events /// </param> /// <param name='search'> /// A free-text search expression to match for whether a particular event /// should be returned /// </param> /// <param name='orderby'> /// A comma-separated list of properties with \"asc\" (the default) or \"desc\" /// to control the order of returned events /// </param> /// <param name='select'> /// Limits the properties to just those requested on each returned event /// </param> /// <param name='skip'> /// The number of items to skip over before returning events /// </param> /// <param name='top'> /// The number of events to return /// </param> /// <param name='format'> /// Format for the returned events /// </param> /// <param name='count'> /// Request a count of matching items included with the returned events /// </param> /// <param name='apply'> /// An expression used for aggregation over returned events /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<EventsResults>> GetByTypeWithHttpMessagesAsync(string appId, string eventType, string timespan = default(string), string filter = default(string), string search = default(string), string orderby = default(string), string select = default(string), int? skip = default(int?), int? top = default(int?), string format = default(string), bool? count = default(bool?), string apply = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (appId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "appId"); } if (eventType == null) { throw new ValidationException(ValidationRules.CannotBeNull, "eventType"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("appId", appId); tracingParameters.Add("eventType", eventType); tracingParameters.Add("timespan", timespan); tracingParameters.Add("filter", filter); tracingParameters.Add("search", search); tracingParameters.Add("orderby", orderby); tracingParameters.Add("select", select); tracingParameters.Add("skip", skip); tracingParameters.Add("top", top); tracingParameters.Add("format", format); tracingParameters.Add("count", count); tracingParameters.Add("apply", apply); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetByType", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "apps/{appId}/events/{eventType}").ToString(); _url = _url.Replace("{appId}", System.Uri.EscapeDataString(appId)); _url = _url.Replace("{eventType}", System.Uri.EscapeDataString(eventType)); List<string> _queryParameters = new List<string>(); if (timespan != null) { _queryParameters.Add(string.Format("timespan={0}", System.Uri.EscapeDataString(timespan))); } if (filter != null) { _queryParameters.Add(string.Format("$filter={0}", System.Uri.EscapeDataString(filter))); } if (search != null) { _queryParameters.Add(string.Format("$search={0}", System.Uri.EscapeDataString(search))); } if (orderby != null) { _queryParameters.Add(string.Format("$orderby={0}", System.Uri.EscapeDataString(orderby))); } if (select != null) { _queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(select))); } if (skip != null) { _queryParameters.Add(string.Format("$skip={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(skip, Client.SerializationSettings).Trim('"')))); } if (top != null) { _queryParameters.Add(string.Format("$top={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(top, Client.SerializationSettings).Trim('"')))); } if (format != null) { _queryParameters.Add(string.Format("$format={0}", System.Uri.EscapeDataString(format))); } if (count != null) { _queryParameters.Add(string.Format("$count={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(count, Client.SerializationSettings).Trim('"')))); } if (apply != null) { _queryParameters.Add(string.Format("$apply={0}", System.Uri.EscapeDataString(apply))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<EventsResults>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<EventsResults>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get an event /// </summary> /// <remarks> /// Gets the data for a single event /// </remarks> /// <param name='appId'> /// ID of the application. This is Application ID from the API Access settings /// blade in the Azure portal. /// </param> /// <param name='eventType'> /// The type of events to query; either a standard event type (`traces`, /// `customEvents`, `pageViews`, `requests`, `dependencies`, `exceptions`, /// `availabilityResults`) or `$all` to query across all event types. Possible /// values include: '$all', 'traces', 'customEvents', 'pageViews', /// 'browserTimings', 'requests', 'dependencies', 'exceptions', /// 'availabilityResults', 'performanceCounters', 'customMetrics' /// </param> /// <param name='eventId'> /// ID of event. /// </param> /// <param name='timespan'> /// Optional. The timespan over which to retrieve events. This is an ISO8601 /// time period value. This timespan is applied in addition to any that are /// specified in the Odata expression. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<EventsResults>> GetWithHttpMessagesAsync(string appId, string eventType, string eventId, string timespan = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (appId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "appId"); } if (eventType == null) { throw new ValidationException(ValidationRules.CannotBeNull, "eventType"); } if (eventId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "eventId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("appId", appId); tracingParameters.Add("eventType", eventType); tracingParameters.Add("timespan", timespan); tracingParameters.Add("eventId", eventId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "apps/{appId}/events/{eventType}/{eventId}").ToString(); _url = _url.Replace("{appId}", System.Uri.EscapeDataString(appId)); _url = _url.Replace("{eventType}", System.Uri.EscapeDataString(eventType)); _url = _url.Replace("{eventId}", System.Uri.EscapeDataString(eventId)); List<string> _queryParameters = new List<string>(); if (timespan != null) { _queryParameters.Add(string.Format("timespan={0}", System.Uri.EscapeDataString(timespan))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<EventsResults>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<EventsResults>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get OData metadata /// </summary> /// <remarks> /// Gets OData EDMX metadata describing the event data model /// </remarks> /// <param name='appId'> /// ID of the application. This is Application ID from the API Access settings /// blade in the Azure portal. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<object>> GetOdataMetadataWithHttpMessagesAsync(string appId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (appId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "appId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("appId", appId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetOdataMetadata", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "apps/{appId}/events/$metadata").ToString(); _url = _url.Replace("{appId}", System.Uri.EscapeDataString(appId)); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<object>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<object>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
44.719325
563
0.557499
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/applicationinsights/Microsoft.Azure.ApplicationInsights.Query/src/Generated/Events.cs
29,157
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Windows.Data; namespace Devkoes.Core.WPF.ValueConverters { [ValueConversion(typeof(object), typeof(bool))] public class NullToTrueConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } [ValueConversion(typeof(string), typeof(bool))] public class NullOrEmptyToTrueConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } [ValueConversion(typeof(string), typeof(bool))] public class NullOrNoneToTrueConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
30.596154
103
0.674419
[ "Apache-2.0" ]
tomkuijsten/devkoes-core
Devkoes.Core/WPF/ValueConverters/NothingConverters.cs
1,593
C#
using UnityEngine; public class Player : MonoBehaviour { [Header("Movement")] public float moveForce; public float maxVelocity; public float turnSpeed; public bool grounded; private float _verticalInput, _horizontalInput; [Header("Shooting")] public GameObject bullet; public GameObject bulletSpawnPoint; public float bulletForce; public AudioSource shootSFX; [Header("Health")] public bool dead; private Rigidbody _rigid; #region Engine private void Start() { _rigid = GetComponent<Rigidbody>(); } private void FixedUpdate() { if (dead) return; Movement(); } private void Update() { if (dead) return; Inputs(); Shoot(); } #endregion #region Movement private void Inputs() { _verticalInput = Input.GetAxis("Vertical"); _horizontalInput = Input.GetAxis("Horizontal"); } private void Movement() { if (_rigid.velocity.magnitude < maxVelocity) _rigid.AddForce(transform.rotation * Vector3.forward * moveForce * _verticalInput); transform.Rotate(0, _horizontalInput * turnSpeed, 0); if (transform.position.y < -1f) Die(); } #endregion #region Grounded Check private void OnCollisionExit(Collision collision) => CheckGrounded(collision); private void OnCollisionStay(Collision collision) => CheckGrounded(collision); private void CheckGrounded(Collision collision) { if (collision.collider.CompareTag(GameManager.FLOOR_TAG)) { if (collision.contactCount > 0) grounded = true; else grounded = false; } } #endregion #region Shooting private void Shoot() { if (Input.GetKeyDown(KeyCode.Space)) { Rigidbody rigid = Instantiate(bullet, bulletSpawnPoint.transform.position, bulletSpawnPoint.transform.rotation, null).GetComponent<Rigidbody>(); rigid.AddForce(rigid.transform.rotation * Vector3.forward * bulletForce, ForceMode.Impulse); shootSFX.Play(); } } #endregion private void Die() { dead = true; } }
23.56701
156
0.611111
[ "MIT" ]
salehb02/Platform-Fall
Assets/Scripts/Player.cs
2,286
C#
using System; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; namespace alexnown { public class RadialSlider : Selectable, IDragHandler, IInitializePotentialDragHandler, IRadialElement, ISlider { public event Action<float> ChangedNormValue; /// <summary> /// Stops the slider when crossing over the 0-1 border. Set it value to 0 for smooth slider moving across start-end border. /// </summary> [Range(0, 0.5f)] public float BorderCrossingResistance = 0.5f; /// <summary> /// Allows you to setting max slider angle (for 180 and 90 angle sliders as example). /// </summary> [SerializeField, Range(10, 360)] private float _angleLimit = 360; [SerializeField] private bool _clockwiseDirection = true; [SerializeField] private float _minValue = 0.0f; [SerializeField] private float _maxValue = 1f; [SerializeField] private bool _wholeNumbers = false; [SerializeField] private float _value; [SerializeField, HideInInspector] private float _normValue; [Space] [SerializeField] private Slider.SliderEvent _onValueChanged = new Slider.SliderEvent(); /// <summary> /// Allows you to ignore some clicks in the center and outside the slider circle. /// </summary> [Header("View")] public Vector2 RaycastLimits; [SerializeField] private RectTransform _rotatedTransform = null; private Camera _cachedMainCamera; private Canvas _parentCanvas; private bool _ignoreDrag; public Slider.SliderEvent ValueChanged { get => _onValueChanged; set => _onValueChanged = value; } public bool ClockwiseDirection { get => _clockwiseDirection; set { _clockwiseDirection = value; UpdateHanglerRotation(); } } public float MaxAngle { get => _angleLimit; set => _angleLimit = value; } public float Value { get => _value; set { ApplyNormValue(RemapValueToNormValue(value)); } } public float NormalizedValue { get => _normValue; set { ApplyNormValue(value); } } public float Angle { get => NormalizedValue * MaxAngle; set => ApplyNormValue(value / MaxAngle); } public float MinValue { get => _minValue; set => _minValue = value; } public float MaxValue { get => _maxValue; set => _maxValue = value; } public void OnInitializePotentialDrag(PointerEventData eventData) { _ignoreDrag = !HitPositionInRaycastLimits(eventData.position); if (_ignoreDrag) return; var normValue = CalculateNormValueByInput(eventData.position); if (BorderCrossingResistance > 0 && MaxAngle >= 360) normValue = ApplyBroderCrossingResistanceToNewNormValue(normValue, _normValue, 0.02f); SetNormValueOnInitializeDrag(normValue); } public virtual void OnDrag(PointerEventData eventData) { if (_ignoreDrag) return; var normValue = CalculateNormValueByInput(eventData.position); normValue = ApplyBroderCrossingResistanceToNewNormValue(normValue, _normValue, BorderCrossingResistance); ApplyNormValue(normValue); } protected virtual void SetNormValueOnInitializeDrag(float normValue) { ApplyNormValue(normValue); } protected void ApplyNormValue(float normValue) { _normValue = Mathf.Clamp01(normValue); float newValue = RemapNormValueToSliderValue(_normValue); if (_wholeNumbers) { newValue = Mathf.Round(newValue); _normValue = RemapValueToNormValue(newValue); } _value = newValue; if (_onValueChanged != null) _onValueChanged.Invoke(_value); if (ChangedNormValue != null) ChangedNormValue.Invoke(_normValue); UpdateHanglerRotation(); } private float RemapNormValueToSliderValue(float normValue) { if (_minValue == _maxValue) return _minValue; var remaped = _minValue + (_maxValue - _minValue) * normValue; return remaped; } private float RemapValueToNormValue(float value) { if (_maxValue == _minValue) return 0; float remaped = (value - _minValue) / (_maxValue - _minValue); return remaped; } private float ApplyBroderCrossingResistanceToNewNormValue(float normValue, float prevValue, float resistance) { if (normValue < resistance) { if (prevValue > 0.75f) normValue = 1; } else if (normValue > 1 - resistance) { if (prevValue < 0.25f) normValue = 0; } return normValue; } private void UpdateHanglerRotation() { if (_rotatedTransform == null) return; var angle = transform.eulerAngles.z - _normValue * MaxAngle * (_clockwiseDirection ? 1 : -1); if (!_clockwiseDirection) angle = angle - MaxAngle; _rotatedTransform.rotation = Quaternion.Euler(0, 0, angle); } private bool HitPositionInRaycastLimits(Vector2 pos) { if (RaycastLimits.x == 0 && RaycastLimits.y == 0) return true; var cam = GetCanvasCamera(); Vector2 localPos; bool isOverlay = _parentCanvas.renderMode == RenderMode.ScreenSpaceOverlay; if (isOverlay) pos = cam.WorldToScreenPoint(pos); RectTransformUtility.ScreenPointToLocalPointInRectangle(transform as RectTransform, pos, cam, out localPos); var length = localPos.magnitude; return length >= RaycastLimits.x && length <= RaycastLimits.y; } private float CalculateNormValueByInput(Vector2 pos) { var cam = GetCanvasCamera(); bool isOverlay = _parentCanvas.renderMode == RenderMode.ScreenSpaceOverlay; if (isOverlay) pos = cam.WorldToScreenPoint(pos); Vector2 diff = pos - RectTransformUtility.WorldToScreenPoint(cam, transform.position); var angle = Mathf.Atan2(diff.y, diff.x) * Mathf.Rad2Deg; var normValue = Mathf.Repeat((transform.eulerAngles.z - angle + 720f) / 360f, 1f) * 360 / MaxAngle; if (MaxAngle < 360 && normValue > 1) { var center = (360 / MaxAngle - 1) / 2 + 1; if (normValue < center) normValue = 1; else if (normValue >= center) normValue = 0; } if (!_clockwiseDirection) normValue = 1 - normValue; return normValue; } protected override void Awake() { base.Awake(); _parentCanvas = GetComponentInParent<Canvas>(); } private Camera GetCanvasCamera() { var cam = _parentCanvas.worldCamera; if (cam != null) return cam; if (_cachedMainCamera == null) _cachedMainCamera = Camera.main; return _cachedMainCamera; } #if UNITY_EDITOR protected override void OnValidate() { base.OnValidate(); if (_minValue > _maxValue) { float max = _minValue; _minValue = _maxValue; _maxValue = max; } ClockwiseDirection = _clockwiseDirection; Value = _value; } private void OnDrawGizmos() { if (UnityEditor.Selection.activeGameObject != gameObject || RaycastLimits.Equals(Vector2.zero)) return; Gizmos.color = Color.red; var rectTransform = transform as RectTransform; var worldOffset = rectTransform.TransformPoint(RaycastLimits.x, 0, 0) - rectTransform.position; Gizmos.DrawWireSphere(rectTransform.position, worldOffset.magnitude); worldOffset = rectTransform.TransformPoint(RaycastLimits.y, 0, 0) - rectTransform.position; Gizmos.DrawWireSphere(rectTransform.position, worldOffset.magnitude); } #endif } }
34.951613
131
0.582833
[ "MIT" ]
alexnown/UI-Forge
Assets/Scripts/RadialElement/Implementation/RadialSlider.cs
8,670
C#
namespace Dalmatian.Web.ViewModels.Home { using System.Collections.Generic; public class IndexViewModel { public IEnumerable<IndexDogsViewModel> Dogs { get; set; } } }
19.4
65
0.690722
[ "MIT" ]
angelneychev/Dalmatian
src/Web/Dalmatian.Web.ViewModels/Home/IndexViewModel.cs
196
C#
using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; public class Born : MonoBehaviour { // 属性 public bool isPlayer; private int[] enemyList = new int[] {0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,2}; // 引用 public GameObject PlayerPrefab; public GameObject[] enemyPrefabList; // Use this for initialization void Start () { Invoke("BornTank",0.8f); Destroy(gameObject,0.8f); } // Update is called once per frame void Update () { } private void BornTank(){ if(isPlayer){ Instantiate(PlayerPrefab,transform.position,Quaternion.identity); }else{ enemyList = enemyList.OrderBy(c => System.Guid.NewGuid()).ToArray<int>(); int num = Random.Range(0, enemyList.Length); Instantiate(enemyPrefabList[enemyList[num]],transform.position,Quaternion.identity); } } }
24.411765
87
0.709639
[ "MIT" ]
WarrenMondeville/LockStepTank
Client/Assets/tank/Scripts/Born.cs
840
C#
using Augustus.Web.Portal.ViewModels; using Microsoft.Owin.Security; using Microsoft.Owin.Security.Cookies; using Microsoft.Owin.Security.OpenIdConnect; using System.Web; using System.Web.Mvc; namespace Augustus.Web.Portal.Controllers { public class AuthenticationController : Controller { public void SignIn() { // Send an OpenID Connect sign-in request. if (!Request.IsAuthenticated) { HttpContext.GetOwinContext().Authentication.Challenge( new AuthenticationProperties { RedirectUri = Url.Action("ActiveAccounts", "Organization") }, OpenIdConnectAuthenticationDefaults.AuthenticationType); } } public void SignOut() { string callbackUrl = Url.Action("SignOutCallback", "Authentication", routeValues: null, protocol: Request.Url.Scheme); HttpContext.GetOwinContext().Authentication.SignOut( new AuthenticationProperties { RedirectUri = callbackUrl }, OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType); } public ActionResult SignOutCallback() { if (Request.IsAuthenticated) { return RedirectToAction("Index", "Home"); } else { return RedirectToAction("Index", "Home", new { signOut = true }); } } } }
32.791667
130
0.591487
[ "MIT" ]
gothandy/Augustus
Augustus.Web.Portal/Controllers/AuthenticationController.cs
1,576
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> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("Sum_PrevNum")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("Sum_PrevNum")] [assembly: System.Reflection.AssemblyTitleAttribute("Sum_PrevNum")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
40.958333
80
0.648016
[ "MIT" ]
WuWeiSage/Softuni-Contest-Problems
C#/ForLoop/Sum_PrevNum/Sum_PrevNum/obj/Debug/netcoreapp3.1/Sum_PrevNum.AssemblyInfo.cs
983
C#
using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using Channel9.Extensions; namespace Channel9.Models { public class MediaGroup { public Lesson Lesson { get; } private MediaGroup(Lesson lesson) { Lesson = lesson; } public XElement Raw { get; private set; } public List<MediaContent> Contents { get; private set; } public MediaContent Max => Contents.OrderByDescending(mediaContent => mediaContent.FileSize).First(); #region Build public static readonly XName ElementName = XName.Get("group", RSS.MediaNamespace.NamespaceName); private static MediaGroup BuildCore(Lesson lesson, XElement mediaGroupElement) { Throw.IfElementNameIsNotMatch(mediaGroupElement, ElementName); var mediaGroup = new MediaGroup(lesson) { Raw = mediaGroupElement, }; mediaGroup.Contents = MediaContent.Build(mediaGroup); return mediaGroup; } public static MediaGroup Build(Lesson lesson) { Throw.IfIsNull(lesson, nameof(lesson)); var mediaGroupElement = lesson.Raw.Element(ElementName); if (mediaGroupElement == null) { return null; } return BuildCore(lesson, mediaGroupElement); } #endregion Build } }
28.27451
109
0.608183
[ "MIT" ]
linianhui/Channel9.RSSDownloader
src/channel9/Models/MediaGroup.cs
1,444
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.Web.Latest { /// <summary> /// Swift Virtual Network Contract. This is used to enable the new Swift way of doing virtual network integration. /// </summary> public partial class WebAppSwiftVirtualNetworkConnection : Pulumi.CustomResource { /// <summary> /// Kind of resource. /// </summary> [Output("kind")] public Output<string?> Kind { get; private set; } = null!; /// <summary> /// Resource Name. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// The Virtual Network subnet's resource ID. This is the subnet that this Web App will join. This subnet must have a delegation to Microsoft.Web/serverFarms defined first. /// </summary> [Output("subnetResourceId")] public Output<string?> SubnetResourceId { get; private set; } = null!; /// <summary> /// A flag that specifies if the scale unit this Web App is on supports Swift integration. /// </summary> [Output("swiftSupported")] public Output<bool?> SwiftSupported { get; private set; } = null!; /// <summary> /// Resource type. /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Create a WebAppSwiftVirtualNetworkConnection 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 WebAppSwiftVirtualNetworkConnection(string name, WebAppSwiftVirtualNetworkConnectionArgs args, CustomResourceOptions? options = null) : base("azure-nextgen:web/latest:WebAppSwiftVirtualNetworkConnection", name, args ?? new WebAppSwiftVirtualNetworkConnectionArgs(), MakeResourceOptions(options, "")) { } private WebAppSwiftVirtualNetworkConnection(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-nextgen:web/latest:WebAppSwiftVirtualNetworkConnection", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:web/v20180201:WebAppSwiftVirtualNetworkConnection"}, new Pulumi.Alias { Type = "azure-nextgen:web/v20181101:WebAppSwiftVirtualNetworkConnection"}, new Pulumi.Alias { Type = "azure-nextgen:web/v20190801:WebAppSwiftVirtualNetworkConnection"}, new Pulumi.Alias { Type = "azure-nextgen:web/v20200601:WebAppSwiftVirtualNetworkConnection"}, }, }; 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 WebAppSwiftVirtualNetworkConnection 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="options">A bag of options that control this resource's behavior</param> public static WebAppSwiftVirtualNetworkConnection Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new WebAppSwiftVirtualNetworkConnection(name, id, options); } } public sealed class WebAppSwiftVirtualNetworkConnectionArgs : Pulumi.ResourceArgs { /// <summary> /// Kind of resource. /// </summary> [Input("kind")] public Input<string>? Kind { get; set; } /// <summary> /// Name of the app. /// </summary> [Input("name", required: true)] public Input<string> Name { get; set; } = null!; /// <summary> /// Name of the resource group to which the resource belongs. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; /// <summary> /// The Virtual Network subnet's resource ID. This is the subnet that this Web App will join. This subnet must have a delegation to Microsoft.Web/serverFarms defined first. /// </summary> [Input("subnetResourceId")] public Input<string>? SubnetResourceId { get; set; } /// <summary> /// A flag that specifies if the scale unit this Web App is on supports Swift integration. /// </summary> [Input("swiftSupported")] public Input<bool>? SwiftSupported { get; set; } public WebAppSwiftVirtualNetworkConnectionArgs() { } } }
43.335821
180
0.625108
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/Web/Latest/WebAppSwiftVirtualNetworkConnection.cs
5,807
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Cake.Core; namespace Cake.Frosting.Internal { internal sealed class RawArguments : ICakeArguments { private readonly Dictionary<string, string> _arguments; /// <summary> /// Gets the arguments. /// </summary> /// <value>The arguments.</value> public IReadOnlyDictionary<string, string> Arguments => _arguments; /// <summary> /// Initializes a new instance of the <see cref="RawArguments" /> class. /// </summary> /// <param name="options">The options.</param> public RawArguments(CakeHostOptions options) { _arguments = new Dictionary<string, string>( (options ?? new CakeHostOptions()).Arguments ?? new Dictionary<string, string>(), StringComparer.OrdinalIgnoreCase); } /// <inheritdoc/> public bool HasArgument(string name) { return _arguments.ContainsKey(name); } /// <inheritdoc/> public ICollection<string> GetArguments(string name) { return _arguments.ContainsKey(name) ? new[] { _arguments[name] } : Array.Empty<string>(); } } }
31.489362
97
0.602027
[ "MIT" ]
Acidburn0zzz/cake
src/Cake.Frosting/Internal/RawArguments.cs
1,482
C#
//********************************************************* // LLaser.Component project - WindowModel.cs // Created at 2013-6-23 // Author: Bob Bao jar.bob@gmail.com // // All rights reserved. Please follow license agreement to // rewrite and copy this code. // //********************************************************* using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Media; using System.Windows.Media.Imaging; namespace LLaser.Component { [Serializable] public class WindowModel : BmpMakerBase { public enum WindowTypes { Single, Cross, Matrix, Window2, Frame, Checker } public enum WindowBackgroundTypes { Inside, Outside } #region constructor public WindowModel() { WindowType = WindowTypes.Single; } #endregion #region properties and fields private bool _isWindowEnabled = false; public bool IsWindowEnabled { get { return _isWindowEnabled; } set { SetBmpProperty(ref _isWindowEnabled, value); } } private WindowTypes _windowType; public WindowTypes WindowType { get { return _windowType; } set { IsPoint1Enabled = false; IsPoint2Enabled = false; IsLengthEnabled = false; IsSpaceEnabled = false; switch (value) { case WindowTypes.Single: case WindowTypes.Frame: IsPoint1Enabled = true; IsPoint2Enabled = true; break; case WindowTypes.Cross: case WindowTypes.Window2: IsPoint1Enabled = true; break; case WindowTypes.Matrix: IsPoint1Enabled = true; IsPoint2Enabled = true; IsLengthEnabled = true; IsSpaceEnabled = true; break; case WindowTypes.Checker: IsLengthEnabled = true; break; } SetBmpProperty(ref _windowType, value); } } private WindowBackgroundTypes _windowBackgroundType = WindowBackgroundTypes.Inside; public WindowBackgroundTypes WindowBackgroundType { get { return _windowBackgroundType; } set { SetBmpProperty(ref _windowBackgroundType, value); } } private Color _windowColor = Colors.Black; public Color WindowColor { get { return _windowColor; } set { SetBmpProperty(ref _windowColor, value); } } private int _grayStep = 255; public int GrayStep { get { return _grayStep; } set { SetBmpProperty(ref _grayStep, value); } } private int _x1 = 100; public int X1 { get { return _x1; } set { SetBmpProperty(ref _x1, value); } } private int _y1 = 100; public int Y1 { get { return _y1; } set { SetBmpProperty(ref _y1, value); } } private int _x2 = 200; public int X2 { get { return _x2; } set { SetBmpProperty(ref _x2, value); } } private int _y2 = 200; public int Y2 { get { return _y2; } set { SetBmpProperty(ref _y2, value); } } private int _hLength = 1; public int HLength { get { return _hLength; } set { SetBmpProperty(ref _hLength, value); } } private int _vLength = 1; public int VLength { get { return _vLength; } set { SetBmpProperty(ref _vLength, value); } } private int _hSpace; public int HSpace { get { return _hSpace; } set { SetBmpProperty(ref _hSpace, value); } } private int _vSpace; public int VSpace { get { return _vSpace; } set { SetBmpProperty(ref _vSpace, value); } } private bool _isPoint1Enabled; public bool IsPoint1Enabled { get { return _isPoint1Enabled; } set { SetProperty(ref _isPoint1Enabled, value); } } private bool _isPoint2Enabled; public bool IsPoint2Enabled { get { return _isPoint2Enabled; } set { SetProperty(ref _isPoint2Enabled, value); } } private bool _isLengthEnabled; public bool IsLengthEnabled { get { return _isLengthEnabled; } set { SetProperty(ref _isLengthEnabled, value); } } private bool _isSpaceEnabled; public bool IsSpaceEnabled { get { return _isSpaceEnabled; } set { SetProperty(ref _isSpaceEnabled, value); } } #endregion #region methods public override void ExecuteEffect(ref WriteableBitmap bmp) { if (!IsWindowEnabled) return; double r = GrayStep / 255.0; Color windowColor = Color.FromArgb(0xff, (byte)(WindowColor.R * r), (byte)(WindowColor.G * r), (byte)(WindowColor.B * r)); bmp.ForEach((x, y, color) => { switch (WindowType) { case WindowTypes.Single: if (X2 > X1 && Y2 > Y1 && x >= X1 && x <= X2 && y >= Y1 && y <= Y2) return WindowBackgroundType == WindowBackgroundTypes.Inside ? windowColor : color; else return WindowBackgroundType == WindowBackgroundTypes.Inside ? color : windowColor; case WindowTypes.Cross: if (x == X1 || y == Y1) return WindowBackgroundType == WindowBackgroundTypes.Inside ? windowColor : color; else return WindowBackgroundType == WindowBackgroundTypes.Inside ? color : windowColor; case WindowTypes.Window2: if ((x <= X1 && y <= Y1) || (x > X1 && y > Y1)) return WindowBackgroundType == WindowBackgroundTypes.Inside ? windowColor : color; else return WindowBackgroundType == WindowBackgroundTypes.Inside ? color : windowColor; case WindowTypes.Frame: if (X2 > X1 && Y2 > Y1 && x >= X1 && x <= X2 && y >= Y1 && y <= Y2 && (x == X1 || x == X2 || y == Y1 || y == Y2)) return WindowBackgroundType == WindowBackgroundTypes.Inside ? windowColor : color; else return WindowBackgroundType == WindowBackgroundTypes.Inside ? color : windowColor; case WindowTypes.Checker: int checkerInnerX = x % (2 * HLength); int checkerInnerY = y % (2 * VLength); if ((checkerInnerX < HLength && checkerInnerY < VLength) || (checkerInnerX >= HLength && checkerInnerY >= VLength)) return WindowBackgroundType == WindowBackgroundTypes.Inside ? windowColor : color; else return WindowBackgroundType == WindowBackgroundTypes.Inside ? color : windowColor; case WindowTypes.Matrix: if (X2 > X1 && Y2 > Y1 && x >= X1 && x <= X2 && y >= Y1 && y <= Y2) { int matrixInnerX = x % (HSpace + HLength); int matrixInnerY = y % (VSpace + VLength); if (matrixInnerX < HLength && matrixInnerY < VLength) return WindowBackgroundType == WindowBackgroundTypes.Inside ? windowColor : color; else return WindowBackgroundType == WindowBackgroundTypes.Inside ? color : windowColor; } else return WindowBackgroundType == WindowBackgroundTypes.Inside ? color : windowColor; } return color; }); } public void Copy(WindowModel target) { this.IsWindowEnabled = target.IsWindowEnabled; this.WindowType = target.WindowType; this.GrayStep = target.GrayStep; this.WindowColor = target.WindowColor; this.WindowBackgroundType = target.WindowBackgroundType; this.X1 = target.X1; this.X2 = target.X2; this.Y1 = target.Y1; this.Y2 = target.Y2; this.HLength = target.HLength; this.VLength = target.VLength; this.HSpace = target.HSpace; this.VSpace = target.VSpace; this.IsPoint1Enabled = target.IsPoint1Enabled; this.IsPoint2Enabled = target.IsPoint2Enabled; this.IsLengthEnabled = target.IsLengthEnabled; this.IsSpaceEnabled = target.IsSpaceEnabled; } #endregion } }
35.232727
157
0.494375
[ "MIT" ]
Jarrey/LLaser
src/dev/LLaser.Component/BmpMaker/WindowModel.cs
9,691
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> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: Microsoft.AspNetCore.Mvc.ApplicationParts.RelatedAssemblyAttribute("ModelApp.MVC.Views")] // Generated by the MSBuild WriteCodeFragment class.
32.944444
100
0.53457
[ "MIT" ]
fesnarriaga/courses
desenvolvedor-io/02_dominando-o-aspnet-mvc-core/04 - Model App/ModelApp/src/ModelApp.MVC/obj/Debug/net5.0/ModelApp.MVC.RazorAssemblyInfo.cs
593
C#
using System; using System.Net; namespace SimpsLib.HTTP { public class AdvancedWebClient : WebClient { /// <summary> /// Request timeout in milliseconds. By default: 10 seconds (10 000 ms). /// </summary> public int Timeout { get; set; } = 10 * 1000; /// <summary> /// Request read-write timeout in milliseconds. By default: 10 seconds (10 000 ms). /// </summary> public int ReadWriteTimeout { get; set; } = 10 * 1000; /// <summary> /// Decompression methods. By default: GZip and Deflate. /// </summary> public DecompressionMethods DecompressionMethods { get; set; } = DecompressionMethods.GZip | DecompressionMethods.Deflate; /// <summary> /// Check SSL Certificate before request. By default: all certificates allowed (false). /// </summary> public bool ServerCertificateValidation { get; set; } = false; protected override WebRequest GetWebRequest(Uri uri) { var webRequest = base.GetWebRequest(uri); if (webRequest == null) throw new NullReferenceException($"Null reference: unable to get instance of {nameof(WebRequest)} in {nameof(AdvancedWebClient)}."); webRequest.Timeout = Timeout; var httpWebRequest = (HttpWebRequest)webRequest; httpWebRequest.ReadWriteTimeout = ReadWriteTimeout; httpWebRequest.AutomaticDecompression = DecompressionMethods; if (!ServerCertificateValidation) httpWebRequest.ServerCertificateValidationCallback += (sender, certificate, chain, errors) => true; return webRequest; } } }
36.020833
148
0.621168
[ "MIT" ]
YungSamzy/SimpsLib
HTTP/~Http/AdvancedWebClient.cs
1,731
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 Fixtures.Azure.Fluent.Lro.Models { using Newtonsoft.Json; using System.Linq; /// <summary> /// Defines headers for postAsyncNoRetrySucceeded operation. /// </summary> public partial class LROsPostAsyncNoRetrySucceededHeadersInner { /// <summary> /// Initializes a new instance of the /// LROsPostAsyncNoRetrySucceededHeadersInner class. /// </summary> public LROsPostAsyncNoRetrySucceededHeadersInner() { CustomInit(); } /// <summary> /// Initializes a new instance of the /// LROsPostAsyncNoRetrySucceededHeadersInner class. /// </summary> /// <param name="azureAsyncOperation">Location to poll for result /// status: will be set to /// /lro/putasync/retry/succeeded/operationResults/200</param> /// <param name="location">Location to poll for result status: will be /// set to /lro/putasync/retry/succeeded/operationResults/200</param> /// <param name="retryAfter">Number of milliseconds until the next poll /// should be sent, will be set to zero</param> public LROsPostAsyncNoRetrySucceededHeadersInner(string azureAsyncOperation = default(string), string location = default(string), int? retryAfter = default(int?)) { AzureAsyncOperation = azureAsyncOperation; Location = location; RetryAfter = retryAfter; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets location to poll for result status: will be set to /// /lro/putasync/retry/succeeded/operationResults/200 /// </summary> [JsonProperty(PropertyName = "Azure-AsyncOperation")] public string AzureAsyncOperation { get; set; } /// <summary> /// Gets or sets location to poll for result status: will be set to /// /lro/putasync/retry/succeeded/operationResults/200 /// </summary> [JsonProperty(PropertyName = "Location")] public string Location { get; set; } /// <summary> /// Gets or sets number of milliseconds until the next poll should be /// sent, will be set to zero /// </summary> [JsonProperty(PropertyName = "Retry-After")] public int? RetryAfter { get; set; } } }
37.311688
170
0.634528
[ "MIT" ]
ChristianEder/autorest.csharp
test/azurefluent/Expected/Lro/Generated/Models/LROsPostAsyncNoRetrySucceededHeadersInner.cs
2,873
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 2.2.27.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.ContainerRegistry.Fluent.Models { using Microsoft.Rest; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// The configuration of service URI and custom headers for the webhook. /// </summary> public partial class CallbackConfigInner { /// <summary> /// Initializes a new instance of the CallbackConfigInner class. /// </summary> public CallbackConfigInner() { CustomInit(); } /// <summary> /// Initializes a new instance of the CallbackConfigInner class. /// </summary> /// <param name="serviceUri">The service URI for the webhook to post /// notifications.</param> /// <param name="customHeaders">Custom headers that will be added to /// the webhook notifications.</param> public CallbackConfigInner(string serviceUri, IDictionary<string, string> customHeaders = default(IDictionary<string, string>)) { ServiceUri = serviceUri; CustomHeaders = customHeaders; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets the service URI for the webhook to post notifications. /// </summary> [JsonProperty(PropertyName = "serviceUri")] public string ServiceUri { get; set; } /// <summary> /// Gets or sets custom headers that will be added to the webhook /// notifications. /// </summary> [JsonProperty(PropertyName = "customHeaders")] public IDictionary<string, string> CustomHeaders { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (ServiceUri == null) { throw new ValidationException(ValidationRules.CannotBeNull, "ServiceUri"); } } } }
33.493671
135
0.610733
[ "MIT" ]
AntoineGa/azure-libraries-for-net
src/ResourceManagement/ContainerRegistry/Generated/Models/CallbackConfigInner.cs
2,646
C#
using System; using System.Collections.Generic; using System.Linq; using SchemaForge.Crucible; using SchemaForge.Crucible.Extensions; using Xunit; namespace Extensions { public class ArrayExtensionTests { [Fact] public void CloneNullArrayTest() { int[] emptyArray = null; Assert.Throws<ArgumentNullException>(() => emptyArray.CloneArray()); } [Fact] public void CloneArrayValueTypeTest() { int[] firstArray = { 3, 7, 5, 11 }; int[] secondArray = firstArray.CloneArray(); bool allMatch = true; for (int i = secondArray.Length; i-- > 0;) { if (firstArray[i] != secondArray[i]) { allMatch = false; } } Assert.True(allMatch); } [Fact] public void CloneArrayReferenceTypeTest() { string[] firstArray = { "All", "my", "friends", "are", "watching" }; string[] secondArray = firstArray.CloneArray(); bool allMatch = true; for (int i = secondArray.Length; i-- > 0;) { if (firstArray[i] != secondArray[i]) { allMatch = false; } } Assert.True(allMatch); } [Fact] public void CloneEmptyArrayTest() { string[] firstArray = Array.Empty<string>(); string[] secondArray = firstArray.CloneArray(); Assert.True(secondArray.Length == 0); } [Theory] [InlineData(new int[] { 3, 5, 7 }, new int[] { 7, 5, 3 })] // Odd number of items. [InlineData(new int[] { 3, 5, 8, 6 }, new int[] { 6, 8, 5, 3 })] // Even number of items. [InlineData(new int[] { }, new int[] { })] // Empty arrays. public void ReverseArrayTests(int[] originalArray, int[] expectedArray) => Assert.Equal(expectedArray, originalArray.Reverse()); } }
25.753623
132
0.584693
[ "MIT" ]
schema-forge/crucible-dotnet
OSHA/CrucibleTests/ExtensionTests/ArrayExtensionTests.cs
1,779
C#
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // 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.Runtime.InteropServices; namespace SharpDX.Win32 { [Guid("0000000c-0000-0000-C000-000000000046")] internal class ComStreamProxy : CallbackBase, IStream { private Stream sourceStream; byte[] tempBuffer = new byte[0x1000]; public ComStreamProxy(Stream sourceStream) { this.sourceStream = sourceStream; } public unsafe int Read(IntPtr buffer, int numberOfBytesToRead) { int totalRead = 0; while (numberOfBytesToRead > 0) { int countRead = Math.Min(numberOfBytesToRead, tempBuffer.Length); int count = sourceStream.Read(tempBuffer, 0, countRead); if (count == 0) return totalRead; Utilities.Write(new IntPtr(totalRead + (byte*)buffer), tempBuffer, 0, count); numberOfBytesToRead -= count; totalRead += count; } return totalRead; } public unsafe int Write(IntPtr buffer, int numberOfBytesToWrite) { int totalWrite = 0; while (numberOfBytesToWrite > 0) { int countWrite = Math.Min(numberOfBytesToWrite, tempBuffer.Length); Utilities.Read(new IntPtr(totalWrite + (byte*)buffer), tempBuffer, 0, countWrite); sourceStream.Write(tempBuffer, 0, countWrite); numberOfBytesToWrite -= countWrite; totalWrite += countWrite; } return totalWrite; } public long Seek(long offset, SeekOrigin origin) { return sourceStream.Seek(offset, origin); } public void SetSize(long newSize) { } public unsafe long CopyTo(IStream streamDest, long numberOfBytesToCopy, out long bytesWritten) { bytesWritten = 0; fixed (void* pBuffer = tempBuffer) { while (numberOfBytesToCopy > 0) { int countCopy = (int)Math.Min(numberOfBytesToCopy, tempBuffer.Length); int count = sourceStream.Read(tempBuffer, 0, countCopy); if (count == 0) break; streamDest.Write((IntPtr)pBuffer, count); numberOfBytesToCopy -= count; bytesWritten += count; } } return bytesWritten; } public void Commit(CommitFlags commitFlags) { sourceStream.Flush(); } public void Revert() { throw new NotImplementedException(); } public void LockRegion(long offset, long numberOfBytesToLock, LockType dwLockType) { throw new NotImplementedException(); } public void UnlockRegion(long offset, long numberOfBytesToLock, LockType dwLockType) { throw new NotImplementedException(); } public StorageStatistics GetStatistics(StorageStatisticsFlags storageStatisticsFlags) { long length = sourceStream.Length; if (length == 0) length = 0x7fffffff; return new StorageStatistics { Type = 2, // IStream CbSize = length, GrfLocksSupported = 2, // exclusive GrfMode = 0x00000002, // read-write }; } public IStream Clone() { return new ComStreamProxy(sourceStream); } protected override void Dispose(bool disposing) { sourceStream = null; base.Dispose(disposing); } } }
34.213793
102
0.586777
[ "MIT" ]
Altair7610/SharpDX
Source/SharpDX/Win32/ComStreamProxy.cs
4,963
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class House : MonoBehaviour { // Protected vars readonly float parked_velocity_threshold = 0.5f; readonly float parking_distance = 4f; readonly float time_til_park = 1f; bool was_recently_parked = false; float time_of_last_park = float.PositiveInfinity; Transform mailbox = null; private void Awake () { mailbox = transform.Find("Mailbox"); if(!mailbox) Debug.LogWarning("CAN'T FIND MAILBOX"); } // Trigger event for car parking in front of house private void OnTriggerStay (Collider other) { Rigidbody car_rb = other.GetComponentInParent<Rigidbody>(); bool below_parked_threshold = car_rb.velocity.sqrMagnitude < parked_velocity_threshold; // If at parked speed and not recently parked, perform parking procedure if(below_parked_threshold && !was_recently_parked) { // If time_of_last_park is greater than current time, parking has just started if(time_of_last_park > Time.time) { print("Starting parking"); time_of_last_park = Time.time; } else if(Time.time - time_of_last_park >= time_til_park) { Park(car_rb); } } // If was recently parked but above parked threshold speed, repark else if(!below_parked_threshold && was_recently_parked) { Unpark(); } } private void OnTriggerExit (Collider other) { Unpark(); } void Park(Rigidbody car_rb) { print("PARKED"); was_recently_parked = true; // Stop the car car_rb.velocity = Vector3.zero; // Position in front of mailbox (will be smoother in the future) Vector3 parked_position = mailbox.position + parking_distance * mailbox.forward; parked_position.y = car_rb.transform.position.y + 0.1f; car_rb.transform.position = parked_position; // Adjust the camera towards mailbox (will also be smoother) Camera.main.transform.LookAt(new Vector3(mailbox.position.x, Camera.main.transform.position.y, mailbox.position.z), Vector3.up); } void Unpark() { if(!was_recently_parked) return; print("UNPARKED"); was_recently_parked = false; // Re-adjust the camera to normal Camera.main.transform.localRotation = Quaternion.identity; // Reset time_of_last_park time_of_last_park = float.PositiveInfinity; } }
35.356164
136
0.648198
[ "MIT" ]
nkrim/mailman-simulator
Assets/House.cs
2,583
C#
namespace EnvironmentAssessment.Common.VimApi { public class VmFailedUpdatingSecondaryConfig : VmEvent { } }
16
55
0.8125
[ "MIT" ]
octansIt/environmentassessment
EnvironmentAssessment.Wizard/Common/VimApi/V/VmFailedUpdatingSecondaryConfig.cs
112
C#
using System.ComponentModel; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Mn.Framework.Common.Forms.Validation { public enum ElementValidationType { None, Required, Range, Numeric, MaxLength, Email } public class BaseElementValidator { public BaseElementValidator() { } public BaseElementValidator(ElementValidationType type) { SeedElementValidator(type); } private void SeedElementValidator(ElementValidationType type) { Type = type; switch (type) { case ElementValidationType.Numeric: { Message = "You must enter an Integer!"; break; } case ElementValidationType.Required: { Message = "The filed can not be empty!"; break; } case ElementValidationType.Email: { Message = "This e-mail address is not valid"; break; } } } [JsonConverter(typeof(StringEnumConverter))] public ElementValidationType Type { get; set; } [DisplayName("Error message")] public string Message { get; set; } public bool IsChecked { get; set; } } }
24.359375
69
0.497755
[ "MIT" ]
navaei/MnFramework
Framework.Common/Forms/Validation/BaseElementValidator.cs
1,561
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders { [Trait(Traits.Feature, Traits.Features.Completion)] public class ReferenceDirectiveCompletionProviderTests : AbstractInteractiveCSharpCompletionProviderTests { internal override Type GetCompletionProviderType() => typeof(ReferenceDirectiveCompletionProvider); protected override IEqualityComparer<string> GetStringComparer() => StringComparer.OrdinalIgnoreCase; private protected override Task VerifyWorkerAsync( string code, int position, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription = null, bool? isComplexTextEdit = null, List<CompletionFilter> matchingFilters = null, CompletionItemFlags? flags = null) { return BaseVerifyWorkerAsync( code, position, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags); } [Fact] public async Task IsCommitCharacterTest() { var commitCharacters = PathUtilities.IsUnixLikePlatform ? new[] { '"', '/' } : new[] { '"', '\\', '/', ',' }; await VerifyCommitCharactersAsync("#r \"$$", textTypedSoFar: "", validChars: commitCharacters, sourceCodeKind: SourceCodeKind.Script); } [Theory] [InlineData("#r \"$$/")] [InlineData("#r \"$$\\")] [InlineData("#r \"$$,")] [InlineData("#r \"$$A")] [InlineData("#r \"$$!")] [InlineData("#r \"$$(")] public void IsTextualTriggerCharacterTest(string markup) => VerifyTextualTriggerCharacter(markup, shouldTriggerWithTriggerOnLettersEnabled: true, shouldTriggerWithTriggerOnLettersDisabled: true, SourceCodeKind.Script); [ConditionalTheory(typeof(WindowsOnly))] [InlineData(EnterKeyRule.Never)] [InlineData(EnterKeyRule.AfterFullyTypedWord)] [InlineData(EnterKeyRule.Always)] // note: GAC completion helper uses its own EnterKeyRule public async Task SendEnterThroughToEditorTest(EnterKeyRule enterKeyRule) => await VerifySendEnterThroughToEnterAsync("#r \"System$$", "System", enterKeyRule, expected: false); [ConditionalFact(typeof(WindowsOnly))] public async Task GacReference() => await VerifyItemExistsAsync("#r \"$$", "System.Windows.Forms", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); [ConditionalFact(typeof(WindowsOnly))] public async Task GacReferenceFullyQualified() { await VerifyItemExistsAsync( "#r \"System.Windows.Forms,$$", "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [ConditionalFact(typeof(WindowsOnly))] public async Task FileSystemReference() { var systemDir = Path.GetFullPath(Environment.SystemDirectory); var windowsDir = Directory.GetParent(systemDir); var windowsRoot = Directory.GetDirectoryRoot(systemDir); // we need to get the exact casing from the file system: var normalizedWindowsPath = Directory.GetDirectories(windowsRoot, windowsDir.Name).Single(); var windowsFolderName = Path.GetFileName(normalizedWindowsPath); var code = "#r \"" + windowsRoot + "$$"; await VerifyItemExistsAsync(code, windowsFolderName, expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Theory] [InlineData("$$", false)] [InlineData("#$$", false)] [InlineData("#r$$", false)] [InlineData("#r\"$$", true)] [InlineData(" # r \"$$", true)] [InlineData(" # r \"$$\"", true)] [InlineData(" # r \"\"$$", true)] [InlineData("$$ # r \"\"", false)] [InlineData(" # $$r \"\"", false)] [InlineData(" # r $$\"\"", false)] public void ShouldTriggerCompletion(string textWithPositionMarker, bool expectedResult) { var position = textWithPositionMarker.IndexOf("$$"); var text = textWithPositionMarker.Replace("$$", ""); using var workspace = new TestWorkspace(composition: FeaturesTestCompositions.Features); var provider = workspace.ExportProvider.GetExports<CompletionProvider, CompletionProviderMetadata>().Single(p => p.Metadata.Language == LanguageNames.CSharp && p.Metadata.Name == nameof(ReferenceDirectiveCompletionProvider)).Value; var languageServices = workspace.Services.GetLanguageServices(LanguageNames.CSharp); Assert.Equal(expectedResult, provider.ShouldTriggerCompletion(languageServices, SourceText.From(text), position, trigger: default, CompletionOptions.Default, OptionValueSet.Empty)); } } }
50.322581
243
0.688462
[ "MIT" ]
AlexanderSemenyak/roslyn
src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ReferenceDirectiveCompletionProviderTests.cs
6,242
C#
using System; namespace NetMicro.Core.Randoms { /// <summary> /// 随机数生成器 /// </summary> public interface IRandomBuilder { /// <summary> /// 生成随机字符串 /// </summary> /// <param name="maxLength">最大长度</param> /// <param name="text">如果传入该参数,则从该文本中随机抽取</param> string GenerateString( int maxLength, string text = null ); /// <summary> /// 生成随机字母 /// </summary> /// <param name="maxLength">最大长度</param> string GenerateLetters( int maxLength ); /// <summary> /// 生成随机汉字 /// </summary> /// <param name="maxLength">最大长度</param> string GenerateChinese( int maxLength ); /// <summary> /// 生成随机数字 /// </summary> /// <param name="maxLength">最大长度</param> string GenerateNumbers( int maxLength ); /// <summary> /// 生成随机布尔值 /// </summary> bool GenerateBool(); /// <summary> /// 生成随机整数 /// </summary> /// <param name="maxValue">最大值</param> int GenerateInt( int maxValue ); /// <summary> /// 生成随机日期 /// </summary> /// <param name="beginYear">起始年份</param> /// <param name="endYear">结束年份</param> DateTime GenerateDate( int beginYear = 1980, int endYear = 2080 ); /// <summary> /// 生成随机枚举 /// </summary> /// <typeparam name="TEnum">枚举类型</typeparam> TEnum GenerateEnum<TEnum>(); } }
29.588235
74
0.502982
[ "MIT" ]
LittleMaoTou/NetMicro
src/core/NetMicro.Core/Randoms/IRandomBuilder.cs
1,721
C#
using GraphQL.Types; using LightOps.Commerce.Proto.Types; namespace LightOps.Commerce.Gateways.Storefront.Domain.GraphModels.Enum { public class ContentPageSortKeyGraphType : EnumerationGraphType<ContentPageSortKey> { } }
26.111111
87
0.8
[ "MIT" ]
SorenA/lightops-commerce-gateways-storefront
src/LightOps.Commerce.Gateways.Storefront/Domain/GraphModels/Enum/ContentPageSortKeyGraphType.cs
237
C#
namespace Accounting.Application.Common.Interfaces; public interface IBlobService { Task UploadBloadAsync(string name, Stream stream); }
24.5
55
0.782313
[ "MIT" ]
marinasundstrom/accounting-app
Accounting/Accounting/Application/Common/Interfaces/IBlobService.cs
149
C#
namespace Zaaby.DDD; public static partial class ZaabyIServiceCollectionExtensions { public static IServiceCollection AddRepository(this IServiceCollection services) => services.Register<IRepository>(ServiceLifetime.Scoped) .Register<RepositoryAttribute>(ServiceLifetime.Scoped); }
38.25
87
0.794118
[ "MIT" ]
Mutuduxf/Zaaby
src/DDD/Zaaby.DDD/Zaaby.IServiceCollection.Extensions.Repository.cs
306
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> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("Stats.Tests")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Release")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("Stats.Tests")] [assembly: System.Reflection.AssemblyTitleAttribute("Stats.Tests")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
41.041667
80
0.645685
[ "MIT" ]
koryakinp/Stats
Stats.Tests/obj/Release/netcoreapp2.0/Stats.Tests.AssemblyInfo.cs
985
C#
using PoLaKoSz.WeAreOne.EndPoints; namespace PoLaKoSz.WeAreOne { /// <summary> /// Provides access to the whole library. /// </summary> public interface IWeAreOne { /// <summary> /// Access the TechoBase.FM page. /// </summary> IRadioStation TechoBase { get; } /// <summary> /// Access the HouseTime.FM page. /// </summary> IRadioStation HouseTime { get; } /// <summary> /// Access the HardBase.FM page. /// </summary> IRadioStation HardBase { get; } /// <summary> /// Access the TranceBase.FM page. /// </summary> IRadioStation TranceBase { get; } /// <summary> /// Access the CoreTime.FM page. /// </summary> IRadioStation CoreTime { get; } /// <summary> /// Access the ClubTime.FM page. /// </summary> IRadioStation ClubTime { get; } /// <summary> /// Access the TeaTime.FM page. /// </summary> IRadioStation TeaTime { get; } } }
23.673913
45
0.511478
[ "MIT" ]
PoLaKoSz/WeAreOne.Scraper
src/IWeAreOne.cs
1,091
C#
using System.Collections.Generic; using Discord; namespace DiscordHackWeek.Interactive.Paginator { public class PaginatedMessage { public IEnumerable<object> Pages { get; set; } public string Content { get; set; } = ""; public EmbedAuthorBuilder Author { get; set; } = null; public Color Color { get; set; } = Color.Default; public string Title { get; set; } = ""; public PaginatedAppearanceOptions Options { get; set; } = PaginatedAppearanceOptions.Default; } }
29.277778
101
0.656546
[ "MIT" ]
sphexator/DiscordHackWeek
DiscordHackWeek.Interactive/Paginator/PaginatedMessage.cs
529
C#
using System.Collections.Generic; using Microsoft.AspNetCore.SignalR; namespace Monito.Web.Services.Interface { public interface IUpdatingClientsAccessor { ICollection<JobClient> Clients { get; set; } void RegisterClient(HubCallerContext context, IClientProxy client, int requestID, int lastLinkID); } }
34.444444
100
0.809677
[ "Apache-2.0" ]
Wufe/monito
Presentation/Monito.Web/Services/Interface/IUpdatingClientsAccessor.cs
310
C#
namespace P03_FootballBetting.Data { using Microsoft.EntityFrameworkCore; using Config; using Models; public class FootballBettingContext : DbContext { public FootballBettingContext() { } public FootballBettingContext(DbContextOptions options) : base(options) { } public DbSet<Team> Teams { get; set; } public DbSet<Color> Colors { get; set; } public DbSet<Town> Towns { get; set; } public DbSet<Country> Countries { get; set; } public DbSet<Player> Players { get; set; } public DbSet<Position> Positions { get; set; } public DbSet<PlayerStatistic> PlayerStatistics { get; set; } public DbSet<Bet> Bets { get; set; } public DbSet<Game> Games { get; set; } public DbSet<User> Users { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { base.OnConfiguring(optionsBuilder); if (!optionsBuilder.IsConfigured) { optionsBuilder.UseSqlServer(DbContextConfiguration.ConnectionString); } } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.ApplyConfiguration(new TeamConfig()); modelBuilder.ApplyConfiguration(new ColorConfig()); modelBuilder.ApplyConfiguration(new TownConfig()); modelBuilder.ApplyConfiguration(new CountryConfig()); modelBuilder.ApplyConfiguration(new PlayerConfig()); modelBuilder.ApplyConfiguration(new PositionConfig()); modelBuilder.ApplyConfiguration(new PlayerStatisticConfig()); modelBuilder.ApplyConfiguration(new GameConfig()); modelBuilder.ApplyConfiguration(new BetConfig()); modelBuilder.ApplyConfiguration(new UserConfig()); } } }
30.421875
85
0.628659
[ "MIT" ]
RAstardzhiev/SoftUni-C-
Databases Advanced - Entity Framework Core/Entity Relations/P03_FootballBetting.Data/FootballBettingContext.cs
1,949
C#
using System; using System.Collections.Generic; namespace WeddingInfo.Domain.DTOs { public class UserDto { public int Id { get; set; } public bool IsAdmin { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string MiddleName { get; set; } public string Address { get; set; } public string PhoneNumber { get; set; } public string Email { get; set; } public bool IsAttending { get; set; } public bool IsGuest { get; set; } public int Guests { get; set; } public string Icon { get; set; } public string Category { get; set; } public string Household { get; set; } public bool SentSaveTheDate { get; set; } public bool Rehearsal { get; set; } public string Dietary { get; set; } public string Gift { get; set; } public bool SentThankYou { get; set; } public string Title { get; set; } } }
32.033333
47
0.609781
[ "MIT" ]
jsonpj3wt/WeddingInfo
WeddingInfo.Domain/DTOs/UserDto.cs
963
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.AspNetCore.Mvc.Formatters.Xml; public class PersonWrapperProvider : IWrapperProvider { public object Wrap(object obj) { var person = obj as Person; if (person == null) { return obj; } return new PersonWrapper(person); } public Type WrappingType { get { return typeof(PersonWrapper); } } }
20.107143
71
0.605684
[ "MIT" ]
3ejki/aspnetcore
src/Mvc/Mvc.Formatters.Xml/test/PersonWrapperProvider.cs
563
C#
namespace HREngine.Bots { class Pen_EX1_244 : PenTemplate //totemicmight { // verleiht euren totems +2 leben. public override int getPlayPenalty(Playfield p, Minion m, Minion target, int choice, bool isLethal) { return 0; } } }
25.272727
107
0.622302
[ "MIT" ]
chi-rei-den/Silverfish
penalties/Pen_EX1_244.cs
278
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; //********************************** // Item class // Abstract // Change NOTHING in this file //********************************** namespace _105_FinalPracticalStarter { abstract class Item { // Fields protected String name; protected double weight; // Properties public String Name { get { return name; } } public double Weight { get { return weight; } } // Constructor public Item(String name, double weight) { this.name = name; this.weight = weight; } // Methods public abstract bool Use(); // Returns a string representation of the item public override string ToString() { return "This is an item named '" + name + "' and weighs " + weight + " pounds"; } } }
22.619048
91
0.544211
[ "MIT" ]
bmckenna75/GDAPS1
105_FinalPracticalStarter/105_FinalPracticalStarter/Item.cs
952
C#
using System; using System.Text.RegularExpressions; namespace GitHub.Unity { class LfsVersionOutputProcessor : BaseOutputProcessor<Version> { public static Regex GitLfsVersionRegex = new Regex(@"git-lfs/([\d]+)\.([\d]+)\.([\d]+)"); public override void LineReceived(string line) { if (String.IsNullOrEmpty(line)) return; var match = GitLfsVersionRegex.Match(line); if (match.Groups.Count > 0) { var major = Int32.Parse(match.Groups[1].Value); var minor = Int32.Parse(match.Groups[2].Value); var build = Int32.Parse(match.Groups[3].Value); var version = new Version(major, minor, build); RaiseOnEntry(version); } } } }
30.407407
97
0.55542
[ "MIT" ]
Frozenfire92/Unity
src/GitHub.Api/OutputProcessors/LfsVersionOutputProcessor.cs
821
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("a")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("a")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // 次の GUID は、このプロジェクトが COM に公開される場合の、typelib の ID です [assembly: Guid("fb04f16c-cfda-42d2-9250-dd3a2bd980e0")] // アセンブリのバージョン情報は、以下の 4 つの値で構成されています: // // Major Version // Minor Version // Build Number // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
29
57
0.739981
[ "MIT" ]
yu3mars/procon
atcoder/others/code_festival/2014/morning/middle/a/a/Properties/AssemblyInfo.cs
1,598
C#
using System; using System.Threading.Tasks; using Nimbus.Infrastructure; using Nimbus.Interceptors.Inbound; using Nimbus.PropertyInjection; using Nimbus.Tests.Common; using Nimbus.Tests.Common.TestUtilities; namespace Nimbus.IntegrationTests.Tests.InterceptorTests.Interceptors { public sealed class SomeMethodLevelInterceptorForFoo : InboundInterceptor, IRequireBusId { public override async Task OnCommandHandlerExecuting<TBusCommand>(TBusCommand busCommand, NimbusMessage nimbusMessage) { MethodCallCounter.ForInstance(BusId).RecordCall<SomeMethodLevelInterceptorForFoo>(h => h.OnCommandHandlerExecuting(busCommand, nimbusMessage)); } public override async Task OnCommandHandlerSuccess<TBusCommand>(TBusCommand busCommand, NimbusMessage nimbusMessage) { MethodCallCounter.ForInstance(BusId).RecordCall<SomeMethodLevelInterceptorForFoo>(h => h.OnCommandHandlerSuccess(busCommand, nimbusMessage)); } public override async Task OnCommandHandlerError<TBusCommand>(TBusCommand busCommand, NimbusMessage nimbusMessage, Exception exception) { MethodCallCounter.ForInstance(BusId).RecordCall<SomeMethodLevelInterceptorForFoo>(h => h.OnCommandHandlerError(busCommand, nimbusMessage, exception)); } public Guid BusId { get; set; } } }
45.333333
162
0.771324
[ "MIT" ]
dicko2/Nimbus
src/Tests/Nimbus.IntegrationTests/Tests/InterceptorTests/Interceptors/SomeMethodLevelInterceptorForFoo.cs
1,362
C#
// *********************************************************************** // Assembly : IronyModManager.Parser // Author : Mario // Created : 03-28-2020 // // Last Modified By : Mario // Last Modified On : 12-07-2020 // *********************************************************************** // <copyright file="WholeTextParser.cs" company="Mario"> // Mario // </copyright> // <summary></summary> // *********************************************************************** using System; using System.Collections.Generic; using System.IO; using System.Linq; using IronyModManager.Parser.Common.Args; using IronyModManager.Parser.Common.Parsers; using IronyModManager.Shared; using IronyModManager.Shared.Models; using ValueType = IronyModManager.Shared.Models.ValueType; namespace IronyModManager.Parser.Generic { /// <summary> /// Class WholeTextParser. /// Implements the <see cref="IronyModManager.Parser.Common.Parsers.BaseParser" /> /// Implements the <see cref="IronyModManager.Parser.Common.Parsers.IGenericParser" /> /// </summary> /// <seealso cref="IronyModManager.Parser.Common.Parsers.BaseParser" /> /// <seealso cref="IronyModManager.Parser.Common.Parsers.IGenericParser" /> public class WholeTextParser : BaseParser, IGenericParser { #region Fields /// <summary> /// The skip validation for types /// </summary> private static readonly string[] skipValidationForTypes = new string[] { Common.Constants.ShaderExtension, Common.Constants.FxhExtension }; /// <summary> /// The starts with checks /// </summary> private static readonly string[] startsWithChecks = new string[] { Common.Constants.OnActionsPath }; #endregion Fields #region Constructors /// <summary> /// Initializes a new instance of the <see cref="WholeTextParser" /> class. /// </summary> /// <param name="codeParser">The code parser.</param> /// <param name="logger">The logger.</param> public WholeTextParser(ICodeParser codeParser, ILogger logger) : base(codeParser, logger) { } #endregion Constructors #region Properties /// <summary> /// Gets the name of the parser. /// </summary> /// <value>The name of the parser.</value> public override string ParserName => "Generic" + nameof(WholeTextParser); /// <summary> /// Gets the priority. /// </summary> /// <value>The priority.</value> public virtual int Priority => 1; #endregion Properties #region Methods /// <summary> /// Determines whether this instance can parse the specified arguments. /// </summary> /// <param name="args">The arguments.</param> /// <returns><c>true</c> if this instance can parse the specified arguments; otherwise, <c>false</c>.</returns> public override bool CanParse(CanParseArgs args) { return IsValidType(args); } /// <summary> /// Parses the specified arguments. /// </summary> /// <param name="args">The arguments.</param> /// <returns>IEnumerable&lt;IDefinition&gt;.</returns> public override IEnumerable<IDefinition> Parse(ParserArgs args) { bool fileNameTag = false; // Doesn't seem to like fxh and or shader file extensions if (!skipValidationForTypes.Any(p => args.File.EndsWith(p))) { var errors = EvalForErrorsOnly(args); if (errors != null) { return errors; } } else { fileNameTag = true; } // This type is a bit different and only will conflict in filenames. var def = GetDefinitionInstance(); MapDefinitionFromArgs(ConstructArgs(args, def)); def.OriginalCode = def.Code = string.Join(Environment.NewLine, args.Lines.Where(p => !string.IsNullOrWhiteSpace(p))); def.Id = Path.GetFileName(args.File).ToLowerInvariant(); if (fileNameTag) { def.Tags.Add(def.Id.ToLowerInvariant()); } else { // Get tags only var definitions = ParseRoot(args); foreach (var item in definitions) { foreach (var tag in item.Tags) { var lower = tag.ToLowerInvariant(); if (!def.Tags.Contains(lower)) { def.Tags.Add(lower); } } } } def.ValueType = ValueType.WholeTextFile; return new List<IDefinition> { def }; } /// <summary> /// Determines whether this instance [can parse ends with] the specified arguments. /// </summary> /// <param name="args">The arguments.</param> /// <returns><c>true</c> if this instance [can parse ends with] the specified arguments; otherwise, <c>false</c>.</returns> protected virtual bool CanParseEndsWith(CanParseArgs args) { return skipValidationForTypes.Any(s => args.File.EndsWith(s, StringComparison.OrdinalIgnoreCase)); } /// <summary> /// Determines whether this instance [can parse root common file] the specified arguments. /// </summary> /// <param name="args">The arguments.</param> /// <returns><c>true</c> if this instance [can parse root common file] the specified arguments; otherwise, <c>false</c>.</returns> protected virtual bool CanParseRootCommonFile(CanParseArgs args) { return Path.GetDirectoryName(args.File).Equals(Common.Constants.CommonPath); } /// <summary> /// Determines whether this instance [can parse sound file] the specified arguments. /// </summary> /// <param name="args">The arguments.</param> /// <returns><c>true</c> if this instance [can parse sound file] the specified arguments; otherwise, <c>false</c>.</returns> protected virtual bool CanParseSoundFile(CanParseArgs args) { return args.File.StartsWith(Common.Constants.Stellaris.Sound, StringComparison.OrdinalIgnoreCase) && Constants.TextExtensions.Any(s => args.File.EndsWith(s, StringComparison.OrdinalIgnoreCase)); } /// <summary> /// Determines whether this instance [can parse starts with] the specified arguments. /// </summary> /// <param name="args">The arguments.</param> /// <returns><c>true</c> if this instance [can parse starts with] the specified arguments; otherwise, <c>false</c>.</returns> protected virtual bool CanParseStartsWith(CanParseArgs args) { return startsWithChecks.Any(s => args.File.StartsWith(s, StringComparison.OrdinalIgnoreCase)); } /// <summary> /// Determines whether [is valid type] [the specified arguments]. /// </summary> /// <param name="args">The arguments.</param> /// <returns><c>true</c> if [is valid type] [the specified arguments]; otherwise, <c>false</c>.</returns> protected virtual bool IsValidType(CanParseArgs args) { return CanParseStartsWith(args) || CanParseEndsWith(args) || CanParseSoundFile(args) || CanParseRootCommonFile(args); } #endregion Methods } }
38.79
206
0.568703
[ "MIT" ]
LunarTraveller/IronyModManager
src/IronyModManager.Parser/Generic/WholeTextParser.cs
7,760
C#
using System; using System.Xml; using System.Xml.Linq; using System.Xml.Schema; using System.Collections.Generic; namespace LWTSD { public class SubscriptionCancelled { public readonly string SubscriptionID; public SubscriptionCancelled(string SubscriptionID) { this.SubscriptionID = SubscriptionID; } public SubscriptionCancelled(XElement Element) { SubscriptionID = Element.Attribute("subscriptionid").Value; } } }
19.26087
62
0.772009
[ "Unlicense" ]
Clayster/samples
NET/LWTSD/SubscriptionCancelled.cs
445
C#
using Contoso.Events.ViewModels; using Contoso.Events.ViewModels.Dynamic; using Microsoft.Azure; using Microsoft.WindowsAzure.ServiceRuntime; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Table; using Newtonsoft.Json.Linq; using System; using System.Net; using System.Net.Http; using System.Web; using System.Web.Http; namespace Contoso.Events.Web.Controllers { public class RegisterController : ApiController { public dynamic Post(JToken registrationToken) { dynamic registration = DynamicEntity.GenerateDynamicItem(registrationToken); Guid registrationKey = StoreRegistration(registration); UpdateEventRegistrationCount(registrationToken); if (RoleEnvironment.IsAvailable) { var response = Request.CreateResponse(HttpStatusCode.Moved); var url = Url.Route("Default", new { controller = "Home", action = "Registered", id = registrationKey }); response.StatusCode = HttpStatusCode.Redirect; response.Headers.Location = new Uri(ToAbsoluteUrl(url), UriKind.Absolute); return response; } else { return RedirectToRoute("Default", new { controller = "Home", action = "Registered", id = registrationKey }); } } private Guid StoreRegistration(dynamic registration) { var storageAccount = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("Microsoft.WindowsAzure.Storage.ConnectionString")); var tableClient = storageAccount.CreateCloudTableClient(); var table = tableClient.GetTableReference("EventRegistrations"); var operation = TableOperation.Insert(registration); table.Execute(operation); return Guid.Parse(registration.RowKey); } private void UpdateEventRegistrationCount(JToken registrationToken) { int eventId = Int32.Parse(registrationToken["Event.Id"].ToString()); EventIncrementViewModel.IncrementEvent(eventId); } public string ToAbsoluteUrl(string relativeUrl) { if (string.IsNullOrEmpty(relativeUrl)) return relativeUrl; if (HttpContext.Current == null) return relativeUrl; if (relativeUrl.StartsWith("/")) relativeUrl = relativeUrl.Insert(0, "~"); if (!relativeUrl.StartsWith("~/")) relativeUrl = relativeUrl.Insert(0, "~/"); var url = HttpContext.Current.Request.Url; var port = url.Port != 80 ? (":" + (url.Port - 1)) : String.Empty; return String.Format("{0}://{1}{2}{3}", url.Scheme, url.Host, port, VirtualPathUtility.ToAbsolute(relativeUrl)); } } }
36.5375
179
0.635306
[ "MIT" ]
JaimePolo/20532-DevelopingMicrosoftAzureSolutions
Allfiles/dotnet/Mod07/Labfiles/Starter/Contoso.Events/Contoso.Events.Web/Controllers/RegisterController.cs
2,925
C#
using Microsoft.AspNetCore.Mvc; namespace Referrals.API.Controllers { [ApiController] [Route("api/[controller]")] public class BaseController : ControllerBase { } }
18.5
48
0.697297
[ "MIT" ]
StefanStrauberg/TelMed
src/Services/Referrals/API/Referrals.API/Controllers/BaseController.cs
185
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LR.Models { public class AttendeeModel { public Guid Id { get; set; } public string Name { get; set; } public string Email { get; set; } public DateTime Mealtime { get; set; } public FoodstoreModel Foodstore { get; set; } } }
18.636364
53
0.639024
[ "MIT" ]
harmoniemand/lunch-roulette
LR/LR/Models/AttendeeModel.cs
412
C#
using System; namespace MlkFileHasher.Hash { public interface IHashAlgorithm : IDisposable { void Process(byte[] buf, int count); void Done(); byte[] Hash { get; } } }
17.166667
49
0.592233
[ "MIT" ]
mkropat/MlkFileHasher
MlkFileHasher/Hash/IHashAlgorithm.cs
208
C#
using Newtonsoft.Json; namespace VaultSharp.V1.SystemBackend { /// <summary> /// Represents the Seal status of the Vault. /// </summary> public class SealStatus { /// <summary> /// Gets or sets a value indicating the type. /// </summary> [JsonProperty("type")] public string Type { get; set; } /// <summary> /// Gets or sets a value indicating thif initialized. /// </summary> [JsonProperty("initialized")] public bool Initialized { get; set; } /// <summary> /// Gets or sets a value indicating about the <see cref="SealStatus"/>. /// </summary> /// <value> /// <c>true</c> if sealed; otherwise, <c>false</c>. /// </value> [JsonProperty("sealed")] public bool Sealed { get; set; } /// <summary> /// Gets or sets the number of shares required to reconstruct the master key. /// </summary> /// <value> /// The secret threshold. /// </value> [JsonProperty("t")] public int SecretThreshold { get; set; } /// <summary> /// Gets or sets the number of shares to split the master key into. /// </summary> /// <value> /// The secret shares. /// </value> [JsonProperty("n")] public int SecretShares { get; set; } /// <summary> /// Gets or sets the number of shares that have been successfully applied to reconstruct the master key. /// When the value is about to reach <see cref="SecretThreshold"/>, the Vault will be unsealed and the value will become <value>0</value>. /// </summary> /// <value> /// The progress count. /// </value> [JsonProperty("progress")] public int Progress { get; set; } /// <summary> /// Gets or sets the nonce. /// </summary> /// <value> /// The nonce. /// </value> [JsonProperty("nonce")] public string Nonce { get; set; } /// <summary> /// Gets or sets the vault version. /// </summary> /// <value> /// The version. /// </value> [JsonProperty("version")] public string Version { get; set; } /// <summary> /// Gets or sets the migration. /// </summary> /// <value> /// The migration. /// </value> [JsonProperty("migration")] public bool Migration { get; set; } /// <summary> /// Gets or sets the recovery seal. /// </summary> /// <value> /// The recovery seal. /// </value> [JsonProperty("recovery_seal")] public bool RecoverySeal { get; set; } /// <summary> /// Gets or sets the name of the cluster. /// </summary> /// <value> /// The name of the cluster. /// </value> [JsonProperty("cluster_name")] public string ClusterName { get; set; } /// <summary> /// Gets or sets the cluster identifier. /// </summary> /// <value> /// The cluster identifier. /// </value> [JsonProperty("cluster_id")] public string ClusterId { get; set; } } }
29.371681
146
0.500151
[ "Apache-2.0" ]
devgig/VaultSharp
src/VaultSharp/V1/SystemBackend/SealStatus.cs
3,321
C#
// Copyright (c) Jeremy W. Kuhne. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Runtime.InteropServices; namespace WInterop.GdiPlus.EmfPlus { [StructLayout(LayoutKind.Sequential)] public readonly ref struct MetafilePlusObject { public const ushort ContinueObjectFlag = 0b1000_0000_0000_0000; public const ushort ObjectTypeMask = 0b0111_1111_0000_0000; public const ushort ObjectIdMask = 0b0000_0000_1111_1111; public readonly MetafilePlusRecord Record; private readonly byte _data; public uint TotalObjectSize => Continued ? Record.DataSize : 0; public unsafe uint DataSize { get { if (!Continued) { return Record.DataSize; } fixed (byte* b = &_data) { return *(uint*)b; } } } public MetafilePlusObjectType ObjectType => (MetafilePlusObjectType)((Record.Flags & ObjectTypeMask) >> 8); public int ObjectId => Record.Flags & ObjectIdMask; public bool Continued => (Record.Flags & ContinueObjectFlag) != 0; } }
32.073171
115
0.596958
[ "MIT" ]
JeremyKuhne/WInterop
src/WInterop.GdiPlus/EmfPlus/MetafilePlusObject.cs
1,317
C#
using MLlearning.BL.ExtractData; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using Accord.Controls; using Deedle; namespace MLlearning.BL.Emails { public class SpamAnalyzer { public static void Analyze() { var allEmailsFrame = EmailInfoHistoricalSource.GetEmailsAsCsv().IndexRows<int>("Id").SortRowsByKey(); var fileNameOfSubjectVectorOfAllEmails = "subject-of-all-email.csv"; var subjectVectorOfAllEmails = CreateWordVector(allEmailsFrame.GetColumn<string>("Subject")); if (File.Exists(fileNameOfSubjectVectorOfAllEmails) == false) { subjectVectorOfAllEmails.SaveCsv(fileNameOfSubjectVectorOfAllEmails); } Console.WriteLine($"* Subject Word Vec DF Shape (Rows count: {subjectVectorOfAllEmails.RowCount}, columns count: {subjectVectorOfAllEmails.ColumnCount})"); var hamEmailCount = allEmailsFrame.GetColumn<int>("IsNotSpam").NumSum(); var spamEmailCount = allEmailsFrame.RowCount - hamEmailCount; var tmp = allEmailsFrame.Where(row => row.Value.GetAs<bool>("IsSpam")).RowCount; subjectVectorOfAllEmails.AddColumn("IsNotSpam", allEmailsFrame.GetColumn<int>("IsNotSpam")); var hamTermFrequencies = subjectVectorOfAllEmails .Where(x => x.Value.GetAs<bool>("IsNotSpam")) .Sum() .Sort() .Reversed .Where(x => x.Key != "IsNotSpam"); var spamTermFrequencies = subjectVectorOfAllEmails .Where(x => x.Value.GetAs<bool>("IsNotSpam") == false) .Sum() .Sort() .Reversed; // Look at Top 10 terms that appear in Ham vs. Spam emails var topN = 10; var hamTermProportions = hamTermFrequencies / hamEmailCount; var topHamTerms = hamTermProportions.Keys.Take(topN); var topHamTermsProportions = hamTermProportions.Values.Take(topN); var spamTermProportions = spamTermFrequencies / spamEmailCount; var topSpamTerms = spamTermProportions.Keys.Take(topN); var topSpamTermsProportions = spamTermProportions.Values.Take(topN); var barChart = DataBarBox.Show( new string[] { "Ham", "Spam" }, new double[] { hamEmailCount, spamEmailCount } ); barChart.SetTitle("Ham vs. Spam in Sample Set"); } private static Frame<int, string> CreateWordVector(Series<int, string> rows) { var wordsThatSeriesContains = rows.GetAllValues().Select((row, rowIndex) => { var vector = new SeriesBuilder<string, int>(); var allWords = Regex.Matches(row.Value, "\\w+") .Cast<Match>() .Select(x => x.Value.ToLower()) .Where(x => x.Length > 1 && x != "a" && x != "the") .Distinct(); foreach (var word in allWords) { vector.Add(word, 1); } return KeyValue.Create(rowIndex, vector.Series); }); var wordVectorFrame = Frame.FromRows(wordsThatSeriesContains).FillMissing(0); return wordVectorFrame; } } }
38.063158
167
0.585177
[ "MIT" ]
pu1se/MLlearning
src/MLlearning.BL/Emails/SpamAnalyzer.cs
3,618
C#
using Denounces.Domain.Entities.Pos; namespace Mersy.Infraestructure.Extensions { internal static class OrderExtensions { public static Order AddOrderDetails(this Order order, params OrderDetail[] orderDetails) { foreach (var orderDetail in orderDetails) { order.OrderDetails.Add(orderDetail); } return order; } } }
23.277778
96
0.610979
[ "MIT" ]
132329/Denunciado
Core/Denounces.Infraestructure/Extensions/OrderExtensions.cs
421
C#
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Xml; using LibGit2Sharp; using Microsoft.Build.Construction; using Microsoft.Build.Evaluation; using Microsoft.Build.Execution; using Microsoft.Build.Framework; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Nerdbank.GitVersioning; using Validation; using Xunit; using Xunit.Abstractions; using Version = System.Version; public class BuildIntegrationTests : RepoTestBase, IClassFixture<MSBuildFixture> { private const string GitVersioningTargetsFileName = "NerdBank.GitVersioning.targets"; private const string UnitTestCloudBuildPrefix = "UnitTest: "; private static readonly string[] ToxicEnvironmentVariablePrefixes = new string[] { "APPVEYOR", "SYSTEM_", "BUILD_", }; private BuildManager buildManager; private ProjectCollection projectCollection; private string projectDirectory; private ProjectRootElement testProject; private Dictionary<string, string> globalProperties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { // Set global properties to neutralize environment variables // that might actually be defined by a CI that is building and running these tests. { "PublicRelease", string.Empty }, }; private Random random; public BuildIntegrationTests(ITestOutputHelper logger) : base(logger) { int seed = (int)DateTime.Now.Ticks; this.random = new Random(seed); this.Logger.WriteLine("Random seed: {0}", seed); this.buildManager = new BuildManager(); this.projectCollection = new ProjectCollection(); this.projectDirectory = Path.Combine(this.RepoPath, "projdir"); Directory.CreateDirectory(this.projectDirectory); this.LoadTargetsIntoProjectCollection(); this.testProject = this.CreateProjectRootElement(this.projectDirectory, "test.prj"); this.globalProperties.Add("NerdbankGitVersioningTasksPath", Environment.CurrentDirectory + "\\"); Environment.SetEnvironmentVariable("_NBGV_UnitTest", "true"); // Sterilize the test of any environment variables. foreach (System.Collections.DictionaryEntry variable in Environment.GetEnvironmentVariables()) { string name = (string)variable.Key; if (ToxicEnvironmentVariablePrefixes.Any(toxic => name.StartsWith(toxic, StringComparison.OrdinalIgnoreCase))) { this.globalProperties[name] = string.Empty; } } } private string CommitIdShort => this.Repo.Head.Commits.First().Id.Sha.Substring(0, VersionOptions.DefaultGitCommitIdShortFixedLength); protected override void Dispose(bool disposing) { Environment.SetEnvironmentVariable("_NBGV_UnitTest", string.Empty); base.Dispose(disposing); } [Fact] public async Task GetBuildVersion_Returns_BuildVersion_Property() { this.WriteVersionFile(); this.InitializeSourceControl(); var buildResult = await this.BuildAsync(); Assert.Equal( buildResult.BuildVersion, buildResult.BuildResult.ResultsByTarget[Targets.GetBuildVersion].Items.Single().ItemSpec); } [Fact] public async Task GetBuildVersion_Without_Git() { this.WriteVersionFile("3.4"); var buildResult = await this.BuildAsync(); Assert.Equal("3.4", buildResult.BuildVersion); Assert.Equal("3.4.0", buildResult.AssemblyInformationalVersion); } [Fact] public async Task GetBuildVersion_WithThreeVersionIntegers() { VersionOptions workingCopyVersion = new VersionOptions { Version = SemanticVersion.Parse("7.8.9-beta.3"), SemVer1NumericIdentifierPadding = 1, }; this.WriteVersionFile(workingCopyVersion); this.InitializeSourceControl(); var buildResult = await this.BuildAsync(); this.AssertStandardProperties(workingCopyVersion, buildResult); } [Fact] public async Task GetBuildVersion_Without_Git_HighPrecisionAssemblyVersion() { this.WriteVersionFile(new VersionOptions { Version = SemanticVersion.Parse("3.4"), AssemblyVersion = new VersionOptions.AssemblyVersionOptions { Precision = VersionOptions.VersionPrecision.Revision, }, }); var buildResult = await this.BuildAsync(); Assert.Equal("3.4", buildResult.BuildVersion); Assert.Equal("3.4.0", buildResult.AssemblyInformationalVersion); } [Fact] public async Task GetBuildVersion_OutsideGit_PointingToGit() { // Write a version file to the 'virtualized' repo. string version = "3.4"; this.WriteVersionFile(version); // Update the repo path so we create the 'normal' one elsewhere this.RepoPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); this.InitializeSourceControl(); // Write the same version file to the 'real' repo this.WriteVersionFile(version); // Point the project to the 'real' repo this.testProject.AddProperty("GitRepoRoot", this.RepoPath); var buildResult = await this.BuildAsync(); var workingCopyVersion = VersionOptions.FromVersion(new Version(version)); this.AssertStandardProperties(workingCopyVersion, buildResult); } [Fact] public async Task GetBuildVersion_In_Git_But_Without_Commits() { Repository.Init(this.RepoPath); var repo = new Repository(this.RepoPath); // do not assign Repo property to avoid commits being generated later this.WriteVersionFile("3.4"); Assumes.False(repo.Head.Commits.Any()); // verification that the test is doing what it claims var buildResult = await this.BuildAsync(); Assert.Equal("3.4.0.0", buildResult.BuildVersion); Assert.Equal("3.4.0", buildResult.AssemblyInformationalVersion); } [Fact] public async Task GetBuildVersion_In_Git_But_Head_Lacks_VersionFile() { Repository.Init(this.RepoPath); var repo = new Repository(this.RepoPath); // do not assign Repo property to avoid commits being generated later repo.Commit("empty", this.Signer, this.Signer, new CommitOptions { AllowEmptyCommit = true }); this.WriteVersionFile("3.4"); Assumes.True(repo.Index[VersionFile.JsonFileName] == null); var buildResult = await this.BuildAsync(); Assert.Equal("3.4.0." + repo.Head.Commits.First().GetIdAsVersion().Revision, buildResult.BuildVersion); Assert.Equal("3.4.0+" + repo.Head.Commits.First().Id.Sha.Substring(0, VersionOptions.DefaultGitCommitIdShortFixedLength), buildResult.AssemblyInformationalVersion); } [Fact] public async Task GetBuildVersion_In_Git_But_WorkingCopy_Has_Changes() { const string majorMinorVersion = "5.8"; const string prerelease = ""; this.WriteVersionFile(majorMinorVersion, prerelease); this.InitializeSourceControl(); var workingCopyVersion = VersionOptions.FromVersion(new Version("6.0")); VersionFile.SetVersion(this.RepoPath, workingCopyVersion); var buildResult = await this.BuildAsync(); this.AssertStandardProperties(workingCopyVersion, buildResult); } [Fact] public async Task GetBuildVersion_In_Git_No_VersionFile_At_All() { Repository.Init(this.RepoPath); var repo = new Repository(this.RepoPath); // do not assign Repo property to avoid commits being generated later repo.Commit("empty", this.Signer, this.Signer, new CommitOptions { AllowEmptyCommit = true }); var buildResult = await this.BuildAsync(); Assert.Equal("0.0.0." + repo.Head.Commits.First().GetIdAsVersion().Revision, buildResult.BuildVersion); Assert.Equal("0.0.0+" + repo.Head.Commits.First().Id.Sha.Substring(0, VersionOptions.DefaultGitCommitIdShortFixedLength), buildResult.AssemblyInformationalVersion); } [Fact] public async Task GetBuildVersion_In_Git_With_Version_File_In_Subdirectory_Works() { const string majorMinorVersion = "5.8"; const string prerelease = ""; const string subdirectory = "projdir"; this.WriteVersionFile(majorMinorVersion, prerelease, subdirectory); this.InitializeSourceControl(); this.AddCommits(this.random.Next(15)); var buildResult = await this.BuildAsync(); this.AssertStandardProperties(VersionOptions.FromVersion(new Version(majorMinorVersion)), buildResult, subdirectory); } [Fact] public async Task GetBuildVersion_In_Git_With_Version_File_In_Root_And_Subdirectory_Works() { var rootVersionSpec = new VersionOptions { Version = SemanticVersion.Parse("14.1"), AssemblyVersion = new VersionOptions.AssemblyVersionOptions(new Version(14, 0)), }; var subdirVersionSpec = new VersionOptions { Version = SemanticVersion.Parse("11.0") }; const string subdirectory = "projdir"; this.WriteVersionFile(rootVersionSpec); this.WriteVersionFile(subdirVersionSpec, subdirectory); this.InitializeSourceControl(); this.AddCommits(this.random.Next(15)); var buildResult = await this.BuildAsync(); this.AssertStandardProperties(subdirVersionSpec, buildResult, subdirectory); } [Fact] public async Task GetBuildVersion_In_Git_With_Version_File_In_Root_And_Project_In_Root_Works() { var rootVersionSpec = new VersionOptions { Version = SemanticVersion.Parse("14.1"), AssemblyVersion = new VersionOptions.AssemblyVersionOptions(new Version(14, 0)), }; this.WriteVersionFile(rootVersionSpec); this.InitializeSourceControl(); this.AddCommits(this.random.Next(15)); this.testProject = this.CreateProjectRootElement(this.RepoPath, "root.proj"); var buildResult = await this.BuildAsync(); this.AssertStandardProperties(rootVersionSpec, buildResult); } [Fact] public async Task GetBuildVersion_StablePreRelease() { const string majorMinorVersion = "5.8"; const string prerelease = ""; this.WriteVersionFile(majorMinorVersion, prerelease); this.InitializeSourceControl(); this.AddCommits(this.random.Next(15)); var buildResult = await this.BuildAsync(); this.AssertStandardProperties(VersionOptions.FromVersion(new Version(majorMinorVersion)), buildResult); } [Fact] public async Task GetBuildVersion_StableRelease() { const string majorMinorVersion = "5.8"; const string prerelease = ""; this.WriteVersionFile(majorMinorVersion, prerelease); this.InitializeSourceControl(); this.AddCommits(this.random.Next(15)); this.globalProperties["PublicRelease"] = "true"; var buildResult = await this.BuildAsync(); this.AssertStandardProperties(VersionOptions.FromVersion(new Version(majorMinorVersion)), buildResult); Version version = this.Repo.Head.Commits.First().GetIdAsVersion(); Assert.Equal($"{version.Major}.{version.Minor}.{buildResult.GitVersionHeight}", buildResult.NuGetPackageVersion); } [Fact] public async Task GetBuildVersion_UnstablePreRelease() { const string majorMinorVersion = "5.8"; const string prerelease = "-beta"; this.WriteVersionFile(majorMinorVersion, prerelease); this.InitializeSourceControl(); this.AddCommits(this.random.Next(15)); var buildResult = await this.BuildAsync(); this.AssertStandardProperties(VersionOptions.FromVersion(new Version(majorMinorVersion), prerelease), buildResult); } [Fact] public async Task GetBuildVersion_UnstableRelease() { const string majorMinorVersion = "5.8"; const string prerelease = "-beta"; this.WriteVersionFile(majorMinorVersion, prerelease); this.InitializeSourceControl(); this.AddCommits(this.random.Next(15)); this.globalProperties["PublicRelease"] = "true"; var buildResult = await this.BuildAsync(); this.AssertStandardProperties(VersionOptions.FromVersion(new Version(majorMinorVersion), prerelease), buildResult); } [Fact] public async Task GetBuildVersion_CustomAssemblyVersion() { this.WriteVersionFile("14.0"); this.InitializeSourceControl(); var versionOptions = new VersionOptions { Version = new SemanticVersion(new Version(14, 1)), AssemblyVersion = new VersionOptions.AssemblyVersionOptions(new Version(14, 0)), }; this.WriteVersionFile(versionOptions); var buildResult = await this.BuildAsync(); this.AssertStandardProperties(versionOptions, buildResult); } [Theory] [InlineData(VersionOptions.VersionPrecision.Major)] [InlineData(VersionOptions.VersionPrecision.Build)] [InlineData(VersionOptions.VersionPrecision.Revision)] public async Task GetBuildVersion_CustomAssemblyVersionWithPrecision(VersionOptions.VersionPrecision precision) { var versionOptions = new VersionOptions { Version = new SemanticVersion("14.1"), AssemblyVersion = new VersionOptions.AssemblyVersionOptions { Version = new Version("15.2"), Precision = precision, }, }; this.WriteVersionFile(versionOptions); this.InitializeSourceControl(); var buildResult = await this.BuildAsync(); this.AssertStandardProperties(versionOptions, buildResult); } [Theory] [InlineData(VersionOptions.VersionPrecision.Major)] [InlineData(VersionOptions.VersionPrecision.Build)] [InlineData(VersionOptions.VersionPrecision.Revision)] public async Task GetBuildVersion_CustomAssemblyVersionPrecision(VersionOptions.VersionPrecision precision) { var versionOptions = new VersionOptions { Version = new SemanticVersion("14.1"), AssemblyVersion = new VersionOptions.AssemblyVersionOptions { Precision = precision, }, }; this.WriteVersionFile(versionOptions); this.InitializeSourceControl(); var buildResult = await this.BuildAsync(); this.AssertStandardProperties(versionOptions, buildResult); } [Fact] public async Task GetBuildVersion_CustomBuildNumberOffset() { this.WriteVersionFile("14.0"); this.InitializeSourceControl(); var versionOptions = new VersionOptions { Version = new SemanticVersion(new Version(14, 1)), VersionHeightOffset = 5, }; this.WriteVersionFile(versionOptions); var buildResult = await this.BuildAsync(); this.AssertStandardProperties(versionOptions, buildResult); } [Fact] public async Task GetBuildVersion_OverrideBuildNumberOffset() { this.WriteVersionFile("14.0"); this.InitializeSourceControl(); var versionOptions = new VersionOptions { Version = new SemanticVersion(new Version(14, 1)) }; this.WriteVersionFile(versionOptions); this.testProject.AddProperty("OverrideBuildNumberOffset", "10"); var buildResult = await this.BuildAsync(); Assert.StartsWith("14.1.11.", buildResult.AssemblyFileVersion); } [Fact] public async Task GetBuildVersion_Minus1BuildOffset_NotYetCommitted() { this.WriteVersionFile("14.0"); this.InitializeSourceControl(); var versionOptions = new VersionOptions { Version = new SemanticVersion(new Version(14, 1)), VersionHeightOffset = -1, }; VersionFile.SetVersion(this.RepoPath, versionOptions); var buildResult = await this.BuildAsync(); this.AssertStandardProperties(versionOptions, buildResult); } [Theory] [InlineData(0)] [InlineData(21)] public async Task GetBuildVersion_BuildNumberSpecifiedInVersionJson(int buildNumber) { var versionOptions = new VersionOptions { Version = SemanticVersion.Parse("14.0." + buildNumber), }; this.WriteVersionFile(versionOptions); this.InitializeSourceControl(); var buildResult = await this.BuildAsync(); this.AssertStandardProperties(versionOptions, buildResult); } [Fact] public async Task PublicRelease_RegEx_Unsatisfied() { var versionOptions = new VersionOptions { Version = SemanticVersion.Parse("1.0"), PublicReleaseRefSpec = new string[] { "^refs/heads/release$" }, }; this.WriteVersionFile(versionOptions); this.InitializeSourceControl(); // Just build "master", which doesn't conform to the regex. var buildResult = await this.BuildAsync(); Assert.False(buildResult.PublicRelease); this.AssertStandardProperties(versionOptions, buildResult); } public static IEnumerable<object[]> CloudBuildOfBranch(string branchName) { return new object[][] { new object[] { CloudBuild.AppVeyor.SetItem("APPVEYOR_REPO_BRANCH", branchName) }, new object[] { CloudBuild.VSTS.SetItem("BUILD_SOURCEBRANCH", $"refs/heads/{branchName}") }, new object[] { CloudBuild.Teamcity.SetItem("BUILD_GIT_BRANCH", $"refs/heads/{branchName}") }, }; } [Theory] [MemberData(nameof(CloudBuildOfBranch), "release")] public async Task PublicRelease_RegEx_SatisfiedByCI(IReadOnlyDictionary<string, string> serverProperties) { var versionOptions = new VersionOptions { Version = SemanticVersion.Parse("1.0"), PublicReleaseRefSpec = new string[] { "^refs/heads/release$" }, }; this.WriteVersionFile(versionOptions); this.InitializeSourceControl(); // Don't actually switch the checked out branch in git. CI environment variables // should take precedence over actual git configuration. (Why? because these variables may // retain information about which tag was checked out on a detached head). using (ApplyEnvironmentVariables(serverProperties)) { var buildResult = await this.BuildAsync(); Assert.True(buildResult.PublicRelease); this.AssertStandardProperties(versionOptions, buildResult); } } public static object[][] CloudBuildVariablesData { get { return new object[][] { new object[] { CloudBuild.VSTS, "##vso[task.setvariable variable={NAME};]{VALUE}", false }, new object[] { CloudBuild.VSTS, "##vso[task.setvariable variable={NAME};]{VALUE}", true }, }; } } [Theory] [Trait("TestCategory", "FailsOnAzurePipelines")] [MemberData(nameof(CloudBuildVariablesData))] public async Task CloudBuildVariables_SetInCI(IReadOnlyDictionary<string, string> properties, string expectedMessage, bool setAllVariables) { using (ApplyEnvironmentVariables(properties)) { string keyName = "n1"; string value = "v1"; this.testProject.AddItem("CloudBuildVersionVars", keyName, new Dictionary<string, string> { { "Value", value } }); string alwaysExpectedMessage = UnitTestCloudBuildPrefix + expectedMessage .Replace("{NAME}", keyName) .Replace("{VALUE}", value); var versionOptions = new VersionOptions { Version = SemanticVersion.Parse("1.0"), CloudBuild = new VersionOptions.CloudBuildOptions { SetAllVariables = setAllVariables, SetVersionVariables = true }, }; this.WriteVersionFile(versionOptions); this.InitializeSourceControl(); var buildResult = await this.BuildAsync(); this.AssertStandardProperties(versionOptions, buildResult); // Assert GitBuildVersion was set string conditionallyExpectedMessage = UnitTestCloudBuildPrefix + expectedMessage .Replace("{NAME}", "GitBuildVersion") .Replace("{VALUE}", buildResult.BuildVersion); Assert.Contains(alwaysExpectedMessage, buildResult.LoggedEvents.Select(e => e.Message.TrimEnd())); Assert.Contains(conditionallyExpectedMessage, buildResult.LoggedEvents.Select(e => e.Message.TrimEnd())); // Assert GitBuildVersionSimple was set conditionallyExpectedMessage = UnitTestCloudBuildPrefix + expectedMessage .Replace("{NAME}", "GitBuildVersionSimple") .Replace("{VALUE}", buildResult.BuildVersionSimple); Assert.Contains(alwaysExpectedMessage, buildResult.LoggedEvents.Select(e => e.Message.TrimEnd())); Assert.Contains(conditionallyExpectedMessage, buildResult.LoggedEvents.Select(e => e.Message.TrimEnd())); // Assert that project properties are also set. Assert.Equal(buildResult.BuildVersion, buildResult.GitBuildVersion); Assert.Equal(buildResult.BuildVersionSimple, buildResult.GitBuildVersionSimple); Assert.Equal(buildResult.AssemblyInformationalVersion, buildResult.GitAssemblyInformationalVersion); if (setAllVariables) { // Assert that some project properties were set as build properties prefaced with "NBGV_". Assert.Equal(buildResult.GitCommitIdShort, buildResult.NBGV_GitCommitIdShort); Assert.Equal(buildResult.NuGetPackageVersion, buildResult.NBGV_NuGetPackageVersion); } else { // Assert that the NBGV_ prefixed properties are *not* set. Assert.Equal(string.Empty, buildResult.NBGV_GitCommitIdShort); Assert.Equal(string.Empty, buildResult.NBGV_NuGetPackageVersion); } // Assert that env variables were also set in context of the build. Assert.Contains(buildResult.LoggedEvents, e => string.Equals(e.Message, $"n1=v1", StringComparison.OrdinalIgnoreCase)); versionOptions.CloudBuild.SetVersionVariables = false; this.WriteVersionFile(versionOptions); buildResult = await this.BuildAsync(); this.AssertStandardProperties(versionOptions, buildResult); // Assert GitBuildVersion was not set conditionallyExpectedMessage = UnitTestCloudBuildPrefix + expectedMessage .Replace("{NAME}", "GitBuildVersion") .Replace("{VALUE}", buildResult.BuildVersion); Assert.Contains(alwaysExpectedMessage, buildResult.LoggedEvents.Select(e => e.Message.TrimEnd())); Assert.DoesNotContain(conditionallyExpectedMessage, buildResult.LoggedEvents.Select(e => e.Message.TrimEnd())); Assert.NotEqual(buildResult.BuildVersion, buildResult.BuildResult.ProjectStateAfterBuild.GetPropertyValue("GitBuildVersion")); // Assert GitBuildVersionSimple was not set conditionallyExpectedMessage = UnitTestCloudBuildPrefix + expectedMessage .Replace("{NAME}", "GitBuildVersionSimple") .Replace("{VALUE}", buildResult.BuildVersionSimple); Assert.Contains(alwaysExpectedMessage, buildResult.LoggedEvents.Select(e => e.Message.TrimEnd())); Assert.DoesNotContain(conditionallyExpectedMessage, buildResult.LoggedEvents.Select(e => e.Message.TrimEnd())); Assert.NotEqual(buildResult.BuildVersionSimple, buildResult.BuildResult.ProjectStateAfterBuild.GetPropertyValue("GitBuildVersionSimple")); } } private static VersionOptions BuildNumberVersionOptionsBasis { get { return new VersionOptions { Version = SemanticVersion.Parse("1.0"), CloudBuild = new VersionOptions.CloudBuildOptions { BuildNumber = new VersionOptions.CloudBuildNumberOptions { Enabled = true, IncludeCommitId = new VersionOptions.CloudBuildNumberCommitIdOptions(), } }, }; } } public static object[][] BuildNumberData { get { return new object[][] { new object[] { BuildNumberVersionOptionsBasis, CloudBuild.VSTS, "##vso[build.updatebuildnumber]{CLOUDBUILDNUMBER}" }, }; } } [Theory] [MemberData(nameof(BuildNumberData))] public async Task BuildNumber_SetInCI(VersionOptions versionOptions, IReadOnlyDictionary<string, string> properties, string expectedBuildNumberMessage) { this.WriteVersionFile(versionOptions); this.InitializeSourceControl(); using (ApplyEnvironmentVariables(properties)) { var buildResult = await this.BuildAsync(); this.AssertStandardProperties(versionOptions, buildResult); expectedBuildNumberMessage = expectedBuildNumberMessage.Replace("{CLOUDBUILDNUMBER}", buildResult.CloudBuildNumber); Assert.Contains(UnitTestCloudBuildPrefix + expectedBuildNumberMessage, buildResult.LoggedEvents.Select(e => e.Message.TrimEnd())); } versionOptions.CloudBuild.BuildNumber.Enabled = false; this.WriteVersionFile(versionOptions); using (ApplyEnvironmentVariables(properties)) { var buildResult = await this.BuildAsync(); this.AssertStandardProperties(versionOptions, buildResult); expectedBuildNumberMessage = expectedBuildNumberMessage.Replace("{CLOUDBUILDNUMBER}", buildResult.CloudBuildNumber); Assert.DoesNotContain(UnitTestCloudBuildPrefix + expectedBuildNumberMessage, buildResult.LoggedEvents.Select(e => e.Message.TrimEnd())); } } [Theory] [PairwiseData] public async Task BuildNumber_VariousOptions(bool isPublic, VersionOptions.CloudBuildNumberCommitWhere where, VersionOptions.CloudBuildNumberCommitWhen when, [CombinatorialValues(0, 1, 2)] int extraBuildMetadataCount, [CombinatorialValues(1, 2)] int semVer) { var versionOptions = BuildNumberVersionOptionsBasis; versionOptions.CloudBuild.BuildNumber.IncludeCommitId.Where = where; versionOptions.CloudBuild.BuildNumber.IncludeCommitId.When = when; versionOptions.NuGetPackageVersion = new VersionOptions.NuGetPackageVersionOptions { SemVer = semVer, }; this.WriteVersionFile(versionOptions); this.InitializeSourceControl(); this.globalProperties["PublicRelease"] = isPublic.ToString(); for (int i = 0; i < extraBuildMetadataCount; i++) { this.testProject.AddItem("BuildMetadata", $"A{i}"); } var buildResult = await this.BuildAsync(); this.AssertStandardProperties(versionOptions, buildResult); } [Fact] public async Task PublicRelease_RegEx_SatisfiedByCheckedOutBranch() { var versionOptions = new VersionOptions { Version = SemanticVersion.Parse("1.0"), PublicReleaseRefSpec = new string[] { "^refs/heads/release$" }, }; this.WriteVersionFile(versionOptions); this.InitializeSourceControl(); using (ApplyEnvironmentVariables(CloudBuild.SuppressEnvironment)) { // Check out a branch that conforms. var releaseBranch = this.Repo.CreateBranch("release"); Commands.Checkout(this.Repo, releaseBranch); var buildResult = await this.BuildAsync(); Assert.True(buildResult.PublicRelease); this.AssertStandardProperties(versionOptions, buildResult); } } [Theory] [PairwiseData] public async Task AssemblyInfo(bool isVB, bool includeNonVersionAttributes, bool gitRepo) { this.WriteVersionFile(); if (gitRepo) { this.InitializeSourceControl(); } if (isVB) { this.MakeItAVBProject(); } if (includeNonVersionAttributes) { this.testProject.AddProperty("NBGV_EmitNonVersionCustomAttributes", "true"); } var result = await this.BuildAsync("Build", logVerbosity: LoggerVerbosity.Minimal); string assemblyPath = result.BuildResult.ProjectStateAfterBuild.GetPropertyValue("TargetPath"); string versionFileContent = File.ReadAllText(Path.Combine(this.projectDirectory, result.BuildResult.ProjectStateAfterBuild.GetPropertyValue("VersionSourceFile"))); this.Logger.WriteLine(versionFileContent); var assembly = Assembly.LoadFile(assemblyPath); var assemblyFileVersion = assembly.GetCustomAttribute<AssemblyFileVersionAttribute>(); var assemblyInformationalVersion = assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>(); var assemblyTitle = assembly.GetCustomAttribute<AssemblyTitleAttribute>(); var assemblyProduct = assembly.GetCustomAttribute<AssemblyProductAttribute>(); var assemblyCompany = assembly.GetCustomAttribute<AssemblyCompanyAttribute>(); var assemblyCopyright = assembly.GetCustomAttribute<AssemblyCopyrightAttribute>(); var thisAssemblyClass = assembly.GetType("ThisAssembly") ?? assembly.GetType("TestNamespace.ThisAssembly"); Assert.NotNull(thisAssemblyClass); Assert.Equal(new Version(result.AssemblyVersion), assembly.GetName().Version); Assert.Equal(result.AssemblyFileVersion, assemblyFileVersion.Version); Assert.Equal(result.AssemblyInformationalVersion, assemblyInformationalVersion.InformationalVersion); if (includeNonVersionAttributes) { Assert.Equal(result.AssemblyTitle, assemblyTitle.Title); Assert.Equal(result.AssemblyProduct, assemblyProduct.Product); Assert.Equal(result.AssemblyCompany, assemblyCompany.Company); Assert.Equal(result.AssemblyCopyright, assemblyCopyright.Copyright); } else { Assert.Null(assemblyTitle); Assert.Null(assemblyProduct); Assert.Null(assemblyCompany); Assert.Null(assemblyCopyright); } const BindingFlags fieldFlags = BindingFlags.Static | BindingFlags.NonPublic; Assert.Equal(result.AssemblyVersion, thisAssemblyClass.GetField("AssemblyVersion", fieldFlags).GetValue(null)); Assert.Equal(result.AssemblyFileVersion, thisAssemblyClass.GetField("AssemblyFileVersion", fieldFlags).GetValue(null)); Assert.Equal(result.AssemblyInformationalVersion, thisAssemblyClass.GetField("AssemblyInformationalVersion", fieldFlags).GetValue(null)); Assert.Equal(result.AssemblyName, thisAssemblyClass.GetField("AssemblyName", fieldFlags).GetValue(null)); Assert.Equal(result.RootNamespace, thisAssemblyClass.GetField("RootNamespace", fieldFlags).GetValue(null)); Assert.Equal(result.AssemblyConfiguration, thisAssemblyClass.GetField("AssemblyConfiguration", fieldFlags).GetValue(null)); Assert.Equal(result.AssemblyTitle, thisAssemblyClass.GetField("AssemblyTitle", fieldFlags)?.GetValue(null)); Assert.Equal(result.AssemblyProduct, thisAssemblyClass.GetField("AssemblyProduct", fieldFlags)?.GetValue(null)); Assert.Equal(result.AssemblyCompany, thisAssemblyClass.GetField("AssemblyCompany", fieldFlags)?.GetValue(null)); Assert.Equal(result.AssemblyCopyright, thisAssemblyClass.GetField("AssemblyCopyright", fieldFlags)?.GetValue(null)); Assert.Equal(result.GitCommitId, thisAssemblyClass.GetField("GitCommitId", fieldFlags)?.GetValue(null) ?? string.Empty); if (gitRepo) { Assert.True(long.TryParse(result.GitCommitDateTicks, out _), $"Invalid value for GitCommitDateTicks: '{result.GitCommitDateTicks}'"); DateTimeOffset gitCommitDate = new DateTimeOffset(long.Parse(result.GitCommitDateTicks), TimeSpan.Zero); Assert.Equal(gitCommitDate, thisAssemblyClass.GetProperty("GitCommitDate", fieldFlags)?.GetValue(null) ?? thisAssemblyClass.GetField("GitCommitDate", fieldFlags)?.GetValue(null) ?? string.Empty); } else { Assert.Empty(result.GitCommitDateTicks); Assert.Null(thisAssemblyClass.GetProperty("GitCommitDate", fieldFlags)); } // Verify that it doesn't have key fields Assert.Null(thisAssemblyClass.GetField("PublicKey", fieldFlags)); Assert.Null(thisAssemblyClass.GetField("PublicKeyToken", fieldFlags)); } // TODO: add key container test. [Theory] [InlineData("keypair.snk", false)] [InlineData("public.snk", true)] [InlineData("protectedPair.pfx", true)] public async Task AssemblyInfo_HasKeyData(string keyFile, bool delaySigned) { TestUtilities.ExtractEmbeddedResource($@"Keys\{keyFile}", Path.Combine(this.projectDirectory, keyFile)); this.testProject.AddProperty("SignAssembly", "true"); this.testProject.AddProperty("AssemblyOriginatorKeyFile", keyFile); this.testProject.AddProperty("DelaySign", delaySigned.ToString()); this.WriteVersionFile(); var result = await this.BuildAsync(Targets.GenerateAssemblyVersionInfo, logVerbosity: LoggerVerbosity.Minimal); string versionCsContent = File.ReadAllText(Path.Combine(this.projectDirectory, result.BuildResult.ProjectStateAfterBuild.GetPropertyValue("VersionSourceFile"))); this.Logger.WriteLine(versionCsContent); var sourceFile = CSharpSyntaxTree.ParseText(versionCsContent); var syntaxTree = await sourceFile.GetRootAsync(); var fields = syntaxTree.DescendantNodes().OfType<VariableDeclaratorSyntax>(); var publicKeyField = (LiteralExpressionSyntax)fields.SingleOrDefault(f => f.Identifier.ValueText == "PublicKey")?.Initializer.Value; var publicKeyTokenField = (LiteralExpressionSyntax)fields.SingleOrDefault(f => f.Identifier.ValueText == "PublicKeyToken")?.Initializer.Value; if (Path.GetExtension(keyFile) == ".pfx") { // No support for PFX (yet anyway), since they're encrypted. // Note for future: I think by this point, the user has typically already decrypted // the PFX and stored the key pair in a key container. If we knew how to find which one, // we could perhaps divert to that. Assert.Null(publicKeyField); Assert.Null(publicKeyTokenField); } else { Assert.Equal( "002400000480000094000000060200000024000052534131000400000100010067cea773679e0ecc114b7e1d442466a90bf77c755811a0d3962a546ed716525b6508abf9f78df132ffd3fb75fe604b3961e39c52d5dfc0e6c1fb233cb4fb56b1a9e3141513b23bea2cd156cb2ef7744e59ba6b663d1f5b2f9449550352248068e85b61c68681a6103cad91b3bf7a4b50d2fabf97e1d97ac34db65b25b58cd0dc", publicKeyField?.Token.ValueText); Assert.Equal("ca2d1515679318f5", publicKeyTokenField?.Token.ValueText); } } [Fact] [Trait("TestCategory", "FailsOnAzurePipelines")] public async Task AssemblyInfo_IncrementalBuild() { this.WriteVersionFile(prerelease: "-beta"); await this.BuildAsync("Build", logVerbosity: LoggerVerbosity.Minimal); this.WriteVersionFile(prerelease: "-rc"); // two characters SHORTER, to test file truncation. await this.BuildAsync("Build", logVerbosity: LoggerVerbosity.Minimal); } /// <summary> /// Emulate a project with an unsupported language, and verify that /// one warning is emitted because the assembly info file couldn't be generated. /// </summary> [Fact] public async Task AssemblyInfo_NotProducedWithoutCodeDomProvider() { var propertyGroup = this.testProject.CreatePropertyGroupElement(); this.testProject.AppendChild(propertyGroup); propertyGroup.AddProperty("Language", "NoCodeDOMProviderForThisLanguage"); this.WriteVersionFile(); var result = await this.BuildAsync(Targets.GenerateAssemblyVersionInfo, logVerbosity: LoggerVerbosity.Minimal, assertSuccessfulBuild: false); Assert.Equal(BuildResultCode.Failure, result.BuildResult.OverallResult); string versionCsFilePath = Path.Combine(this.projectDirectory, result.BuildResult.ProjectStateAfterBuild.GetPropertyValue("VersionSourceFile")); Assert.False(File.Exists(versionCsFilePath)); Assert.Single(result.LoggedEvents.OfType<BuildErrorEventArgs>()); } /// <summary> /// Emulate a project with an unsupported language, and verify that /// no errors are emitted because the target is skipped. /// </summary> [Fact] public async Task AssemblyInfo_Suppressed() { var propertyGroup = this.testProject.CreatePropertyGroupElement(); this.testProject.AppendChild(propertyGroup); propertyGroup.AddProperty("Language", "NoCodeDOMProviderForThisLanguage"); propertyGroup.AddProperty(Targets.GenerateAssemblyVersionInfo, "false"); this.WriteVersionFile(); var result = await this.BuildAsync(Targets.GenerateAssemblyVersionInfo, logVerbosity: LoggerVerbosity.Minimal); string versionCsFilePath = Path.Combine(this.projectDirectory, result.BuildResult.ProjectStateAfterBuild.GetPropertyValue("VersionSourceFile")); Assert.False(File.Exists(versionCsFilePath)); Assert.Empty(result.LoggedEvents.OfType<BuildErrorEventArgs>()); Assert.Empty(result.LoggedEvents.OfType<BuildWarningEventArgs>()); } /// <summary> /// Emulate a project with an unsupported language, and verify that /// no errors are emitted because the target is skipped. /// </summary> [Fact] public async Task AssemblyInfo_SuppressedImplicitlyByTargetExt() { var propertyGroup = this.testProject.CreatePropertyGroupElement(); this.testProject.InsertAfterChild(propertyGroup, this.testProject.Imports.First()); // insert just after the Common.Targets import. propertyGroup.AddProperty("Language", "NoCodeDOMProviderForThisLanguage"); propertyGroup.AddProperty("TargetExt", ".notdll"); this.WriteVersionFile(); var result = await this.BuildAsync(Targets.GenerateAssemblyVersionInfo, logVerbosity: LoggerVerbosity.Minimal); string versionCsFilePath = Path.Combine(this.projectDirectory, result.BuildResult.ProjectStateAfterBuild.GetPropertyValue("VersionSourceFile")); Assert.False(File.Exists(versionCsFilePath)); Assert.Empty(result.LoggedEvents.OfType<BuildErrorEventArgs>()); Assert.Empty(result.LoggedEvents.OfType<BuildWarningEventArgs>()); } /// <summary> /// Create a native resource .dll and verify that its version /// information is set correctly. /// </summary> [Fact] public async Task NativeVersionInfo_CreateNativeResourceDll() { this.testProject = this.CreateNativeProjectRootElement(this.projectDirectory, "test.vcxproj"); this.WriteVersionFile(); var result = await this.BuildAsync(Targets.Build, logVerbosity: LoggerVerbosity.Minimal); Assert.Empty(result.LoggedEvents.OfType<BuildErrorEventArgs>()); string targetFile = Path.Combine(this.projectDirectory, result.BuildResult.ProjectStateAfterBuild.GetPropertyValue("TargetPath")); Assert.True(File.Exists(targetFile)); var fileInfo = FileVersionInfo.GetVersionInfo(targetFile); Assert.Equal("1.2", fileInfo.FileVersion); Assert.Equal("1.2.0", fileInfo.ProductVersion); Assert.Equal("test", fileInfo.InternalName); Assert.Equal("NerdBank", fileInfo.CompanyName); Assert.Equal($"Copyright (c) {DateTime.Now.Year}. All rights reserved.", fileInfo.LegalCopyright); } private static Version GetExpectedAssemblyVersion(VersionOptions versionOptions, Version version) { // Function should be very similar to VersionOracle.GetAssemblyVersion() var assemblyVersion = (versionOptions?.AssemblyVersion?.Version ?? versionOptions.Version.Version).EnsureNonNegativeComponents(); var precision = versionOptions?.AssemblyVersion?.Precision ?? VersionOptions.DefaultVersionPrecision; assemblyVersion = new System.Version( assemblyVersion.Major, precision >= VersionOptions.VersionPrecision.Minor ? assemblyVersion.Minor : 0, precision >= VersionOptions.VersionPrecision.Build ? version.Build : 0, precision >= VersionOptions.VersionPrecision.Revision ? version.Revision : 0); return assemblyVersion; } private static RestoreEnvironmentVariables ApplyEnvironmentVariables(IReadOnlyDictionary<string, string> variables) { Requires.NotNull(variables, nameof(variables)); var oldValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); foreach (var variable in variables) { oldValues[variable.Key] = Environment.GetEnvironmentVariable(variable.Key); Environment.SetEnvironmentVariable(variable.Key, variable.Value); } return new RestoreEnvironmentVariables(oldValues); } private void AssertStandardProperties(VersionOptions versionOptions, BuildResults buildResult, string relativeProjectDirectory = null) { int versionHeight = this.Repo.GetVersionHeight(relativeProjectDirectory); Version idAsVersion = this.Repo.GetIdAsVersion(relativeProjectDirectory); string commitIdShort = this.CommitIdShort; Version version = this.Repo.GetIdAsVersion(relativeProjectDirectory); Version assemblyVersion = GetExpectedAssemblyVersion(versionOptions, version); var additionalBuildMetadata = from item in buildResult.BuildResult.ProjectStateAfterBuild.GetItems("BuildMetadata") select item.EvaluatedInclude; var expectedBuildMetadata = $"+{commitIdShort}"; if (additionalBuildMetadata.Any()) { expectedBuildMetadata += "." + string.Join(".", additionalBuildMetadata); } string expectedBuildMetadataWithoutCommitId = additionalBuildMetadata.Any() ? $"+{string.Join(".", additionalBuildMetadata)}" : string.Empty; Assert.Equal($"{version}", buildResult.AssemblyFileVersion); Assert.Equal($"{idAsVersion.Major}.{idAsVersion.Minor}.{idAsVersion.Build}{versionOptions.Version.Prerelease}{expectedBuildMetadata}", buildResult.AssemblyInformationalVersion); // The assembly version property should always have four integer components to it, // per bug https://github.com/AArnott/Nerdbank.GitVersioning/issues/26 Assert.Equal($"{assemblyVersion.Major}.{assemblyVersion.Minor}.{assemblyVersion.Build}.{assemblyVersion.Revision}", buildResult.AssemblyVersion); Assert.Equal(idAsVersion.Build.ToString(), buildResult.BuildNumber); Assert.Equal($"{version}", buildResult.BuildVersion); Assert.Equal($"{idAsVersion.Major}.{idAsVersion.Minor}.{idAsVersion.Build}", buildResult.BuildVersion3Components); Assert.Equal(idAsVersion.Build.ToString(), buildResult.BuildVersionNumberComponent); Assert.Equal($"{idAsVersion.Major}.{idAsVersion.Minor}.{idAsVersion.Build}", buildResult.BuildVersionSimple); Assert.Equal(this.Repo.Head.Commits.First().Id.Sha, buildResult.GitCommitId); Assert.Equal(this.Repo.Head.Commits.First().Author.When.UtcTicks.ToString(CultureInfo.InvariantCulture), buildResult.GitCommitDateTicks); Assert.Equal(commitIdShort, buildResult.GitCommitIdShort); Assert.Equal(versionHeight.ToString(), buildResult.GitVersionHeight); Assert.Equal($"{version.Major}.{version.Minor}", buildResult.MajorMinorVersion); Assert.Equal(versionOptions.Version.Prerelease, buildResult.PrereleaseVersion); Assert.Equal(expectedBuildMetadata, buildResult.SemVerBuildSuffix); string GetPkgVersionSuffix(bool useSemVer2) { string semVer1CommitPrefix = useSemVer2 ? string.Empty : "g"; string pkgVersionSuffix = buildResult.PublicRelease ? string.Empty : $"-{semVer1CommitPrefix}{commitIdShort}"; if (useSemVer2) { pkgVersionSuffix += expectedBuildMetadataWithoutCommitId; } return pkgVersionSuffix; } // NuGet is now SemVer 2.0 and will pass additional build metadata if provided string nugetPkgVersionSuffix = GetPkgVersionSuffix(useSemVer2: versionOptions?.NuGetPackageVersionOrDefault.SemVer == 2); Assert.Equal($"{idAsVersion.Major}.{idAsVersion.Minor}.{idAsVersion.Build}{GetSemVerAppropriatePrereleaseTag(versionOptions)}{nugetPkgVersionSuffix}", buildResult.NuGetPackageVersion); // Chocolatey only supports SemVer 1.0 string chocolateyPkgVersionSuffix = GetPkgVersionSuffix(useSemVer2: false); Assert.Equal($"{idAsVersion.Major}.{idAsVersion.Minor}.{idAsVersion.Build}{GetSemVerAppropriatePrereleaseTag(versionOptions)}{chocolateyPkgVersionSuffix}", buildResult.ChocolateyPackageVersion); var buildNumberOptions = versionOptions.CloudBuildOrDefault.BuildNumberOrDefault; if (buildNumberOptions.EnabledOrDefault) { var commitIdOptions = buildNumberOptions.IncludeCommitIdOrDefault; var buildNumberSemVer = SemanticVersion.Parse(buildResult.CloudBuildNumber); bool hasCommitData = commitIdOptions.WhenOrDefault == VersionOptions.CloudBuildNumberCommitWhen.Always || (commitIdOptions.WhenOrDefault == VersionOptions.CloudBuildNumberCommitWhen.NonPublicReleaseOnly && !buildResult.PublicRelease); Version expectedVersion = hasCommitData && commitIdOptions.WhereOrDefault == VersionOptions.CloudBuildNumberCommitWhere.FourthVersionComponent ? idAsVersion : new Version(version.Major, version.Minor, version.Build); Assert.Equal(expectedVersion, buildNumberSemVer.Version); Assert.Equal(buildResult.PrereleaseVersion, buildNumberSemVer.Prerelease); string expectedBuildNumberMetadata = hasCommitData && commitIdOptions.WhereOrDefault == VersionOptions.CloudBuildNumberCommitWhere.BuildMetadata ? $"+{commitIdShort}" : string.Empty; if (additionalBuildMetadata.Any()) { expectedBuildNumberMetadata = expectedBuildNumberMetadata.Length == 0 ? "+" + string.Join(".", additionalBuildMetadata) : expectedBuildNumberMetadata + "." + string.Join(".", additionalBuildMetadata); } Assert.Equal(expectedBuildNumberMetadata, buildNumberSemVer.BuildMetadata); } else { Assert.Equal(string.Empty, buildResult.CloudBuildNumber); } } private static string GetSemVerAppropriatePrereleaseTag(VersionOptions versionOptions) { return versionOptions.NuGetPackageVersionOrDefault.SemVer == 1 ? versionOptions.Version.Prerelease?.Replace('.', '-') : versionOptions.Version.Prerelease; } private async Task<BuildResults> BuildAsync(string target = Targets.GetBuildVersion, LoggerVerbosity logVerbosity = LoggerVerbosity.Detailed, bool assertSuccessfulBuild = true) { var eventLogger = new MSBuildLogger { Verbosity = LoggerVerbosity.Minimal }; var loggers = new ILogger[] { eventLogger }; this.testProject.Save(); // persist generated project on disk for analysis var buildResult = await this.buildManager.BuildAsync( this.Logger, this.projectCollection, this.testProject, target, this.globalProperties, logVerbosity, loggers); var result = new BuildResults(buildResult, eventLogger.LoggedEvents); this.Logger.WriteLine(result.ToString()); if (assertSuccessfulBuild) { Assert.Equal(BuildResultCode.Success, buildResult.OverallResult); } return result; } private void LoadTargetsIntoProjectCollection() { string prefix = $"{ThisAssembly.RootNamespace}.Targets."; var streamNames = from name in Assembly.GetExecutingAssembly().GetManifestResourceNames() where name.StartsWith(prefix, StringComparison.Ordinal) select name; foreach (string name in streamNames) { using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(name)) { var targetsFile = ProjectRootElement.Create(XmlReader.Create(stream), this.projectCollection); targetsFile.FullPath = Path.Combine(this.RepoPath, name.Substring(prefix.Length)); targetsFile.Save(); // persist files on disk } } } private ProjectRootElement CreateNativeProjectRootElement(string projectDirectory, string projectName) { using (var reader = XmlReader.Create(Assembly.GetExecutingAssembly().GetManifestResourceStream($"{ThisAssembly.RootNamespace}.test.vcprj"))) { var pre = ProjectRootElement.Create(reader, this.projectCollection); pre.FullPath = Path.Combine(projectDirectory, projectName); pre.AddImport(Path.Combine(this.RepoPath, GitVersioningTargetsFileName)); return pre; } } private ProjectRootElement CreateProjectRootElement(string projectDirectory, string projectName) { using (var reader = XmlReader.Create(Assembly.GetExecutingAssembly().GetManifestResourceStream($"{ThisAssembly.RootNamespace}.test.prj"))) { var pre = ProjectRootElement.Create(reader, this.projectCollection); pre.FullPath = Path.Combine(projectDirectory, projectName); pre.AddImport(Path.Combine(this.RepoPath, GitVersioningTargetsFileName)); return pre; } } private void MakeItAVBProject() { var csharpImport = this.testProject.Imports.Single(i => i.Project.Contains("CSharp")); csharpImport.Project = @"$(MSBuildToolsPath)\Microsoft.VisualBasic.targets"; var isVbProperty = this.testProject.Properties.Single(p => p.Name == "IsVB"); isVbProperty.Value = "true"; } private struct RestoreEnvironmentVariables : IDisposable { private readonly IReadOnlyDictionary<string, string> applyVariables; internal RestoreEnvironmentVariables(IReadOnlyDictionary<string, string> applyVariables) { this.applyVariables = applyVariables; } public void Dispose() { ApplyEnvironmentVariables(this.applyVariables); } } private static class CloudBuild { public static readonly ImmutableDictionary<string, string> SuppressEnvironment = ImmutableDictionary<string, string>.Empty // AppVeyor .Add("APPVEYOR", string.Empty) .Add("APPVEYOR_REPO_TAG", string.Empty) .Add("APPVEYOR_REPO_TAG_NAME", string.Empty) .Add("APPVEYOR_PULL_REQUEST_NUMBER", string.Empty) // VSTS .Add("SYSTEM_TEAMPROJECTID", string.Empty) .Add("BUILD_SOURCEBRANCH", string.Empty) // Teamcity .Add("BUILD_VCS_NUMBER", string.Empty) .Add("BUILD_GIT_BRANCH", string.Empty); public static readonly ImmutableDictionary<string, string> VSTS = SuppressEnvironment .SetItem("SYSTEM_TEAMPROJECTID", "1"); public static readonly ImmutableDictionary<string, string> AppVeyor = SuppressEnvironment .SetItem("APPVEYOR", "True"); public static readonly ImmutableDictionary<string, string> Teamcity = SuppressEnvironment .SetItem("BUILD_VCS_NUMBER", "1"); } private static class Targets { internal const string Build = "Build"; internal const string GetBuildVersion = "GetBuildVersion"; internal const string GetNuGetPackageVersion = "GetNuGetPackageVersion"; internal const string GenerateAssemblyVersionInfo = "GenerateAssemblyVersionInfo"; internal const string GenerateNativeVersionInfo = "GenerateNativeVersionInfo"; } private class BuildResults { internal BuildResults(BuildResult buildResult, IReadOnlyList<BuildEventArgs> loggedEvents) { Requires.NotNull(buildResult, nameof(buildResult)); this.BuildResult = buildResult; this.LoggedEvents = loggedEvents; } public BuildResult BuildResult { get; private set; } public IReadOnlyList<BuildEventArgs> LoggedEvents { get; private set; } public bool PublicRelease => string.Equals("true", this.BuildResult.ProjectStateAfterBuild.GetPropertyValue("PublicRelease"), StringComparison.OrdinalIgnoreCase); public string BuildNumber => this.BuildResult.ProjectStateAfterBuild.GetPropertyValue("BuildNumber"); public string GitCommitId => this.BuildResult.ProjectStateAfterBuild.GetPropertyValue("GitCommitId"); public string BuildVersion => this.BuildResult.ProjectStateAfterBuild.GetPropertyValue("BuildVersion"); public string BuildVersionSimple => this.BuildResult.ProjectStateAfterBuild.GetPropertyValue("BuildVersionSimple"); public string PrereleaseVersion => this.BuildResult.ProjectStateAfterBuild.GetPropertyValue("PrereleaseVersion"); public string MajorMinorVersion => this.BuildResult.ProjectStateAfterBuild.GetPropertyValue("MajorMinorVersion"); public string BuildVersionNumberComponent => this.BuildResult.ProjectStateAfterBuild.GetPropertyValue("BuildVersionNumberComponent"); public string GitCommitIdShort => this.BuildResult.ProjectStateAfterBuild.GetPropertyValue("GitCommitIdShort"); public string GitCommitDateTicks => this.BuildResult.ProjectStateAfterBuild.GetPropertyValue("GitCommitDateTicks"); public string GitVersionHeight => this.BuildResult.ProjectStateAfterBuild.GetPropertyValue("GitVersionHeight"); public string SemVerBuildSuffix => this.BuildResult.ProjectStateAfterBuild.GetPropertyValue("SemVerBuildSuffix"); public string BuildVersion3Components => this.BuildResult.ProjectStateAfterBuild.GetPropertyValue("BuildVersion3Components"); public string AssemblyInformationalVersion => this.BuildResult.ProjectStateAfterBuild.GetPropertyValue("AssemblyInformationalVersion"); public string AssemblyFileVersion => this.BuildResult.ProjectStateAfterBuild.GetPropertyValue("AssemblyFileVersion"); public string AssemblyVersion => this.BuildResult.ProjectStateAfterBuild.GetPropertyValue("AssemblyVersion"); public string NuGetPackageVersion => this.BuildResult.ProjectStateAfterBuild.GetPropertyValue("NuGetPackageVersion"); public string ChocolateyPackageVersion => this.BuildResult.ProjectStateAfterBuild.GetPropertyValue("ChocolateyPackageVersion"); public string CloudBuildNumber => this.BuildResult.ProjectStateAfterBuild.GetPropertyValue("CloudBuildNumber"); public string AssemblyName => this.BuildResult.ProjectStateAfterBuild.GetPropertyValue("AssemblyName"); public string AssemblyTitle => this.BuildResult.ProjectStateAfterBuild.GetPropertyValue("AssemblyTitle"); public string AssemblyProduct => this.BuildResult.ProjectStateAfterBuild.GetPropertyValue("AssemblyProduct"); public string AssemblyCompany => this.BuildResult.ProjectStateAfterBuild.GetPropertyValue("AssemblyCompany"); public string AssemblyCopyright => this.BuildResult.ProjectStateAfterBuild.GetPropertyValue("AssemblyCopyright"); public string AssemblyConfiguration => this.BuildResult.ProjectStateAfterBuild.GetPropertyValue("Configuration"); public string RootNamespace => this.BuildResult.ProjectStateAfterBuild.GetPropertyValue("RootNamespace"); public string GitBuildVersion => this.BuildResult.ProjectStateAfterBuild.GetPropertyValue("GitBuildVersion"); public string GitBuildVersionSimple => this.BuildResult.ProjectStateAfterBuild.GetPropertyValue("GitBuildVersionSimple"); public string GitAssemblyInformationalVersion => this.BuildResult.ProjectStateAfterBuild.GetPropertyValue("GitAssemblyInformationalVersion"); // Just a sampling of other properties optionally set in cloud build. public string NBGV_GitCommitIdShort => this.BuildResult.ProjectStateAfterBuild.GetPropertyValue("NBGV_GitCommitIdShort"); public string NBGV_NuGetPackageVersion => this.BuildResult.ProjectStateAfterBuild.GetPropertyValue("NBGV_NuGetPackageVersion"); public override string ToString() { var sb = new StringBuilder(); foreach (var property in this.GetType().GetRuntimeProperties().OrderBy(p => p.Name, StringComparer.OrdinalIgnoreCase)) { if (property.DeclaringType == this.GetType() && property.Name != nameof(this.BuildResult)) { sb.AppendLine($"{property.Name} = {property.GetValue(this)}"); } } return sb.ToString(); } } private class MSBuildLogger : ILogger { public string Parameters { get; set; } public LoggerVerbosity Verbosity { get; set; } public List<BuildEventArgs> LoggedEvents { get; } = new List<BuildEventArgs>(); public void Initialize(IEventSource eventSource) { eventSource.AnyEventRaised += this.EventSource_AnyEventRaised; } public void Shutdown() { } private void EventSource_AnyEventRaised(object sender, BuildEventArgs e) { this.LoggedEvents.Add(e); } } }
48.134537
339
0.695497
[ "MIT" ]
r-bennett/Nerdbank.GitVersioning
src/NerdBank.GitVersioning.Tests/BuildIntegrationTests.cs
58,678
C#
namespace PS2Disassembler.Core.Instructions.Register.C790 { public class PSUBUB : RegisterBase { public PSUBUB(uint rs, uint rt, uint rd, uint sa) : base("PSUBUB", rs, rt, rd, sa) { } } }
21.636364
58
0.567227
[ "MIT" ]
HankiDesign/EmotionEngineDisassembler
PS2Disassembler.Core/Instructions/Register/C790/PSUBUB.cs
240
C#
// <copyright file="IVideoRecorder.cs" company="Automate The Planet Ltd."> // Copyright 2021 Automate The Planet Ltd. // Licensed under the Apache License, Version 2.0 (the "License"); // You may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // <author>Anton Angelov</author> // <site>https://bellatrix.solutions/</site> using System; namespace Bellatrix.Plugins.Video.Contracts { public interface IVideoRecorder : IDisposable { string Record(string filePath, string fileName); void Stop(); } }
39.958333
85
0.737226
[ "Apache-2.0" ]
48x16/BELLATRIX
src/Bellatrix.Plugins.Video/contracts/IVideoRecorder.cs
961
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the chime-2018-05-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Chime.Model { /// <summary> /// Container for the parameters to the InviteUsers operation. /// Sends email to a maximum of 50 users, inviting them to the specified Amazon Chime /// <code>Team</code> account. Only <code>Team</code> account types are currently supported /// for this action. /// </summary> public partial class InviteUsersRequest : AmazonChimeRequest { private string _accountId; private List<string> _userEmailList = new List<string>(); /// <summary> /// Gets and sets the property AccountId. /// <para> /// The Amazon Chime account ID. /// </para> /// </summary> [AWSProperty(Required=true)] public string AccountId { get { return this._accountId; } set { this._accountId = value; } } // Check to see if AccountId property is set internal bool IsSetAccountId() { return this._accountId != null; } /// <summary> /// Gets and sets the property UserEmailList. /// <para> /// The user email addresses to which to send the email invitation. /// </para> /// </summary> [AWSProperty(Required=true, Max=50)] public List<string> UserEmailList { get { return this._userEmailList; } set { this._userEmailList = value; } } // Check to see if UserEmailList property is set internal bool IsSetUserEmailList() { return this._userEmailList != null && this._userEmailList.Count > 0; } } }
31.65
103
0.629147
[ "Apache-2.0" ]
damianh/aws-sdk-net
sdk/src/Services/Chime/Generated/Model/InviteUsersRequest.cs
2,532
C#
using Prism.Common; using Prism.Maui.Tests.Mocks; using Prism.Maui.Tests.Navigation.Mocks.ViewModels; using Microsoft.Maui.Controls; namespace Prism.Maui.Tests.Navigation.Mocks.Views { public class NavigationPathPageMock : ContentPage { public NavigationPathPageMockViewModel ViewModel { get; } public NavigationPathPageMock() { var navService = new PageNavigationServiceMock(null, new ApplicationMock(), null); ((IPageAware)navService).Page = this; BindingContext = ViewModel = new NavigationPathPageMockViewModel(navService); } } public class NavigationPathPageMock2 : NavigationPathPageMock { public NavigationPathPageMock2() { } } public class NavigationPathPageMock3 : NavigationPathPageMock { public NavigationPathPageMock3() { } } public class NavigationPathPageMock4 : NavigationPathPageMock { public NavigationPathPageMock4() { } } public class NavigationPathTabbedPageMock : TabbedPage { public NavigationPathPageMockViewModel ViewModel { get; } public NavigationPathTabbedPageMock() { var navService = new PageNavigationServiceMock(null, new ApplicationMock(), null); ((IPageAware)navService).Page = this; BindingContext = ViewModel = new NavigationPathPageMockViewModel(navService); Children.Add(new NavigationPathPageMock()); Children.Add(new NavigationPathPageMock2()); Children.Add(new NavigationPathPageMock3()); } } }
27.081967
94
0.662833
[ "MIT" ]
GTX-ABEL/Prism.Maui
tests/Prism.Maui.Tests/Mocks/Views/NavigationPagePathPageMock.cs
1,654
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; using System.Collections.Generic; namespace System.Management.Automation { /// <summary> /// Class HelpProviderWithCache provides a pseudo implementation of HelpProvider /// at which results are cached in a hashtable so that later retrieval can be /// faster. /// </summary> internal abstract class HelpProviderWithCache : HelpProvider { /// <summary> /// Constructor for HelpProviderWithCache. /// </summary> internal HelpProviderWithCache(HelpSystem helpSystem) : base(helpSystem) { } #region Help Provider Interface /// <summary> /// _helpCache is a hashtable to stores helpInfo. /// </summary> /// <remarks> /// This hashtable is made case-insensitive so that helpInfo can be retrieved case insensitively. /// </remarks> private readonly Hashtable _helpCache = new Hashtable(StringComparer.OrdinalIgnoreCase); /// <summary> /// Exact match help for a target. /// </summary> /// <param name="helpRequest">Help request object.</param> /// <returns>The HelpInfo found. Null if nothing is found.</returns> internal override IEnumerable<HelpInfo> ExactMatchHelp(HelpRequest helpRequest) { string target = helpRequest.Target; if (!this.HasCustomMatch) { if (_helpCache.Contains(target)) { yield return (HelpInfo)_helpCache[target]; } } else { foreach (string key in _helpCache.Keys) { if (CustomMatch(target, key)) { yield return (HelpInfo)_helpCache[key]; } } } if (!this.CacheFullyLoaded) { DoExactMatchHelp(helpRequest); if (_helpCache.Contains(target)) { yield return (HelpInfo)_helpCache[target]; } } } /// <summary> /// This is for child class to indicate that it has implemented /// a custom way of match. /// </summary> /// <value></value> protected bool HasCustomMatch { get; set; } = false; /// <summary> /// This is for implementing custom match algorithm. /// </summary> /// <param name="target">Target to search.</param> /// <param name="key">Key used in cache table.</param> /// <returns></returns> protected virtual bool CustomMatch(string target, string key) { return target == key; } /// <summary> /// Do exact match help for a target. /// </summary> /// <remarks> /// Derived class can choose to either override ExactMatchHelp method to DoExactMatchHelp method. /// If ExactMatchHelp is overridden, initial cache checking will be disabled by default. /// If DoExactMatchHelp is overridden, cache check will be done first in ExactMatchHelp before the /// logic in DoExactMatchHelp is in place. /// </remarks> /// <param name="helpRequest">Help request object.</param> internal virtual void DoExactMatchHelp(HelpRequest helpRequest) { } /// <summary> /// Search help for a target. /// </summary> /// <param name="helpRequest">Help request object.</param> /// <param name="searchOnlyContent"> /// If true, searches for pattern in the help content. Individual /// provider can decide which content to search in. /// /// If false, searches for pattern in the command names. /// </param> /// <returns>A collection of help info objects.</returns> internal override IEnumerable<HelpInfo> SearchHelp(HelpRequest helpRequest, bool searchOnlyContent) { string target = helpRequest.Target; string wildcardpattern = GetWildCardPattern(target); HelpRequest searchHelpRequest = helpRequest.Clone(); searchHelpRequest.Target = wildcardpattern; if (!this.CacheFullyLoaded) { IEnumerable<HelpInfo> result = DoSearchHelp(searchHelpRequest); if (result != null) { foreach (HelpInfo helpInfoToReturn in result) { yield return helpInfoToReturn; } } } else { int countOfHelpInfoObjectsFound = 0; WildcardPattern helpMatcher = WildcardPattern.Get(wildcardpattern, WildcardOptions.IgnoreCase); foreach (string key in _helpCache.Keys) { if ((!searchOnlyContent && helpMatcher.IsMatch(key)) || (searchOnlyContent && ((HelpInfo)_helpCache[key]).MatchPatternInContent(helpMatcher))) { countOfHelpInfoObjectsFound++; yield return (HelpInfo)_helpCache[key]; if (helpRequest.MaxResults > 0 && countOfHelpInfoObjectsFound >= helpRequest.MaxResults) { yield break; } } } } } /// <summary> /// Create a wildcard pattern based on a target. /// /// Here we provide the default implementation of this, covering following /// two cases /// a. if target has wildcard pattern, return as it is. /// b. if target doesn't have wildcard pattern, postfix it with * /// /// Child class of this one may choose to override this function. /// </summary> /// <param name="target">Target string.</param> /// <returns>Wild card pattern created.</returns> internal virtual string GetWildCardPattern(string target) { if (WildcardPattern.ContainsWildcardCharacters(target)) return target; return "*" + target + "*"; } /// <summary> /// Do search help. This is for child class to override. /// </summary> /// <remarks> /// Child class can choose to override SearchHelp of DoSearchHelp depending on /// whether it want to reuse the logic in SearchHelp for this class. /// </remarks> /// <param name="helpRequest">Help request object.</param> /// <returns>A collection of help info objects.</returns> internal virtual IEnumerable<HelpInfo> DoSearchHelp(HelpRequest helpRequest) { yield break; } /// <summary> /// Add an help entry to cache. /// </summary> /// <param name="target">The key of the help entry.</param> /// <param name="helpInfo">HelpInfo object as the value of the help entry.</param> internal void AddCache(string target, HelpInfo helpInfo) { _helpCache[target] = helpInfo; } /// <summary> /// Get help entry from cache. /// </summary> /// <param name="target">The key for the help entry to retrieve.</param> /// <returns>The HelpInfo in cache corresponding the key specified.</returns> internal HelpInfo GetCache(string target) { return (HelpInfo)_helpCache[target]; } /// <summary> /// Is cached fully loaded? /// /// If cache is fully loaded, search/exactmatch Help can short cut the logic /// in various help providers to get help directly from cache. /// /// This indicator is usually set by help providers derived from this class. /// </summary> /// <value></value> protected internal bool CacheFullyLoaded { get; set; } = false; /// <summary> /// This will reset the help cache. Normally this corresponds to a /// help culture change. /// </summary> internal override void Reset() { base.Reset(); _helpCache.Clear(); CacheFullyLoaded = false; } #endregion } }
36.681034
112
0.549824
[ "MIT" ]
10088/PowerShell
src/System.Management.Automation/help/HelpProviderWithCache.cs
8,510
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的一般信息由以下 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("JPush")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("JPush")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] //将 ComVisible 设置为 false 将使此程序集中的类型 //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, //请将此类型的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("6fea766c-0074-43f5-9c4f-7e459b70441d")] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
25.162162
56
0.709989
[ "MIT" ]
qq283335746/Qdhtyy
src/TygaSoft/JPush/Properties/AssemblyInfo.cs
1,282
C#
using System; using System.Collections.Generic; using System.Diagnostics; namespace Lucene.Net.Util { /* * 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 DataInput = Lucene.Net.Store.DataInput; using DataOutput = Lucene.Net.Store.DataOutput; using IndexInput = Lucene.Net.Store.IndexInput; /// <summary> /// Represents a logical <see cref="T:byte[]"/> as a series of pages. You /// can write-once into the logical <see cref="T:byte[]"/> (append only), /// using copy, and then retrieve slices (<see cref="BytesRef"/>) into it /// using fill. /// <para/> /// @lucene.internal /// </summary> // TODO: refactor this, byteblockpool, fst.bytestore, and any // other "shift/mask big arrays". there are too many of these classes! public sealed class PagedBytes { private readonly IList<byte[]> blocks = new List<byte[]>(); // TODO: these are unused? private readonly IList<int> blockEnd = new List<int>(); private readonly int blockSize; private readonly int blockBits; private readonly int blockMask; private bool didSkipBytes; private bool frozen; private int upto; private byte[] currentBlock; private readonly long bytesUsedPerBlock; private static readonly byte[] EMPTY_BYTES = #if FEATURE_ARRAYEMPTY Array.Empty<byte>(); #else new byte[0]; #endif /// <summary> /// Provides methods to read <see cref="BytesRef"/>s from a frozen /// <see cref="PagedBytes"/>. /// </summary> /// <seealso cref="Freeze(bool)"/> public sealed class Reader { private readonly byte[][] blocks; private readonly int[] blockEnds; private readonly int blockBits; private readonly int blockMask; private readonly int blockSize; internal Reader(PagedBytes pagedBytes) { blocks = new byte[pagedBytes.blocks.Count][]; for (var i = 0; i < blocks.Length; i++) { blocks[i] = pagedBytes.blocks[i]; } blockEnds = new int[blocks.Length]; for (int i = 0; i < blockEnds.Length; i++) { blockEnds[i] = pagedBytes.blockEnd[i]; } blockBits = pagedBytes.blockBits; blockMask = pagedBytes.blockMask; blockSize = pagedBytes.blockSize; } /// <summary> /// Gets a slice out of <see cref="PagedBytes"/> starting at <paramref name="start"/> with a /// given length. If the slice spans across a block border this method will /// allocate sufficient resources and copy the paged data. /// <para> /// Slices spanning more than two blocks are not supported. /// </para> /// @lucene.internal /// </summary> public void FillSlice(BytesRef b, long start, int length) { Debug.Assert(length >= 0, "length=" + length); Debug.Assert(length <= blockSize + 1, "length=" + length); b.Length = length; if (length == 0) { return; } var index = (int)(start >> blockBits); var offset = (int)(start & blockMask); if (blockSize - offset >= length) { // Within block b.Bytes = blocks[index]; b.Offset = offset; } else { // Split b.Bytes = new byte[length]; b.Offset = 0; Array.Copy(blocks[index], offset, b.Bytes, 0, blockSize - offset); Array.Copy(blocks[1 + index], 0, b.Bytes, blockSize - offset, length - (blockSize - offset)); } } /// <summary> /// Reads length as 1 or 2 byte vInt prefix, starting at <paramref name="start"/>. /// <para> /// <b>Note:</b> this method does not support slices spanning across block /// borders. /// </para> /// @lucene.internal /// </summary> // TODO: this really needs to be refactored into fieldcacheimpl public void Fill(BytesRef b, long start) { var index = (int)(start >> blockBits); var offset = (int)(start & blockMask); var block = b.Bytes = blocks[index]; if ((block[offset] & 128) == 0) { b.Length = block[offset]; b.Offset = offset + 1; } else { b.Length = ((block[offset] & 0x7f) << 8) | (block[1 + offset] & 0xff); b.Offset = offset + 2; Debug.Assert(b.Length > 0); } } /// <summary> /// Returns approximate RAM bytes used. </summary> public long RamBytesUsed() { return ((blocks != null) ? (blockSize * blocks.Length) : 0); } } /// <summary> /// 1&lt;&lt;blockBits must be bigger than biggest single /// <see cref="BytesRef"/> slice that will be pulled. /// </summary> public PagedBytes(int blockBits) { Debug.Assert(blockBits > 0 && blockBits <= 31, blockBits.ToString()); this.blockSize = 1 << blockBits; this.blockBits = blockBits; blockMask = blockSize - 1; upto = blockSize; bytesUsedPerBlock = blockSize + RamUsageEstimator.NUM_BYTES_ARRAY_HEADER + RamUsageEstimator.NUM_BYTES_OBJECT_REF; } /// <summary> /// Read this many bytes from <paramref name="in"/>. </summary> public void Copy(IndexInput @in, long byteCount) { while (byteCount > 0) { int left = blockSize - upto; if (left == 0) { if (currentBlock != null) { blocks.Add(currentBlock); blockEnd.Add(upto); } currentBlock = new byte[blockSize]; upto = 0; left = blockSize; } if (left < byteCount) { @in.ReadBytes(currentBlock, upto, left, false); upto = blockSize; byteCount -= left; } else { @in.ReadBytes(currentBlock, upto, (int)byteCount, false); upto += (int)byteCount; break; } } } /// <summary> /// Copy <see cref="BytesRef"/> in, setting <see cref="BytesRef"/> out to the result. /// Do not use this if you will use <c>Freeze(true)</c>. /// This only supports <c>bytes.Length &lt;= blockSize</c>/ /// </summary> public void Copy(BytesRef bytes, BytesRef @out) { int left = blockSize - upto; if (bytes.Length > left || currentBlock == null) { if (currentBlock != null) { blocks.Add(currentBlock); blockEnd.Add(upto); didSkipBytes = true; } currentBlock = new byte[blockSize]; upto = 0; left = blockSize; Debug.Assert(bytes.Length <= blockSize); // TODO: we could also support variable block sizes } @out.Bytes = currentBlock; @out.Offset = upto; @out.Length = bytes.Length; Array.Copy(bytes.Bytes, bytes.Offset, currentBlock, upto, bytes.Length); upto += bytes.Length; } /// <summary> /// Commits final <see cref="T:byte[]"/>, trimming it if necessary and if <paramref name="trim"/>=true. </summary> public Reader Freeze(bool trim) { if (frozen) { throw new InvalidOperationException("already frozen"); } if (didSkipBytes) { throw new InvalidOperationException("cannot freeze when copy(BytesRef, BytesRef) was used"); } if (trim && upto < blockSize) { var newBlock = new byte[upto]; Array.Copy(currentBlock, 0, newBlock, 0, upto); currentBlock = newBlock; } if (currentBlock == null) { currentBlock = EMPTY_BYTES; } blocks.Add(currentBlock); blockEnd.Add(upto); frozen = true; currentBlock = null; return new PagedBytes.Reader(this); } public long GetPointer() { if (currentBlock == null) { return 0; } else { return (blocks.Count * ((long)blockSize)) + upto; } } /// <summary> /// Return approx RAM usage in bytes. </summary> public long RamBytesUsed() { return (blocks.Count + (currentBlock != null ? 1 : 0)) * bytesUsedPerBlock; } /// <summary> /// Copy bytes in, writing the length as a 1 or 2 byte /// vInt prefix. /// </summary> // TODO: this really needs to be refactored into fieldcacheimpl public long CopyUsingLengthPrefix(BytesRef bytes) { if (bytes.Length >= 32768) { throw new ArgumentException("max length is 32767 (got " + bytes.Length + ")"); } if (upto + bytes.Length + 2 > blockSize) { if (bytes.Length + 2 > blockSize) { throw new ArgumentException("block size " + blockSize + " is too small to store length " + bytes.Length + " bytes"); } if (currentBlock != null) { blocks.Add(currentBlock); blockEnd.Add(upto); } currentBlock = new byte[blockSize]; upto = 0; } long pointer = GetPointer(); if (bytes.Length < 128) { currentBlock[upto++] = (byte)bytes.Length; } else { currentBlock[upto++] = unchecked((byte)(0x80 | (bytes.Length >> 8))); currentBlock[upto++] = unchecked((byte)(bytes.Length & 0xff)); } Array.Copy(bytes.Bytes, bytes.Offset, currentBlock, upto, bytes.Length); upto += bytes.Length; return pointer; } public sealed class PagedBytesDataInput : DataInput { private readonly PagedBytes outerInstance; private int currentBlockIndex; private int currentBlockUpto; private byte[] currentBlock; internal PagedBytesDataInput(PagedBytes outerInstance) { this.outerInstance = outerInstance; currentBlock = outerInstance.blocks[0]; } public override object Clone() { PagedBytesDataInput clone = outerInstance.GetDataInput(); clone.SetPosition(GetPosition()); return clone; } /// <summary> /// Returns the current byte position. </summary> public long GetPosition() { return (long)currentBlockIndex * outerInstance.blockSize + currentBlockUpto; } /// <summary> /// Seek to a position previously obtained from <see cref="GetPosition()"/>. /// </summary> /// <param name="position"></param> public void SetPosition(long position) { currentBlockIndex = (int)(position >> outerInstance.blockBits); currentBlock = outerInstance.blocks[currentBlockIndex]; currentBlockUpto = (int)(position & outerInstance.blockMask); } public override byte ReadByte() { if (currentBlockUpto == outerInstance.blockSize) { NextBlock(); } return (byte)currentBlock[currentBlockUpto++]; } public override void ReadBytes(byte[] b, int offset, int len) { Debug.Assert(b.Length >= offset + len); int offsetEnd = offset + len; while (true) { int blockLeft = outerInstance.blockSize - currentBlockUpto; int left = offsetEnd - offset; if (blockLeft < left) { System.Buffer.BlockCopy(currentBlock, currentBlockUpto, b, offset, blockLeft); NextBlock(); offset += blockLeft; } else { // Last block System.Buffer.BlockCopy(currentBlock, currentBlockUpto, b, offset, left); currentBlockUpto += left; break; } } } private void NextBlock() { currentBlockIndex++; currentBlockUpto = 0; currentBlock = outerInstance.blocks[currentBlockIndex]; } } public sealed class PagedBytesDataOutput : DataOutput { private readonly PagedBytes outerInstance; public PagedBytesDataOutput(PagedBytes outerInstance) { this.outerInstance = outerInstance; } public override void WriteByte(byte b) { if (outerInstance.upto == outerInstance.blockSize) { if (outerInstance.currentBlock != null) { outerInstance.blocks.Add(outerInstance.currentBlock); outerInstance.blockEnd.Add(outerInstance.upto); } outerInstance.currentBlock = new byte[outerInstance.blockSize]; outerInstance.upto = 0; } outerInstance.currentBlock[outerInstance.upto++] = (byte)b; } public override void WriteBytes(byte[] b, int offset, int length) { Debug.Assert(b.Length >= offset + length); if (length == 0) { return; } if (outerInstance.upto == outerInstance.blockSize) { if (outerInstance.currentBlock != null) { outerInstance.blocks.Add(outerInstance.currentBlock); outerInstance.blockEnd.Add(outerInstance.upto); } outerInstance.currentBlock = new byte[outerInstance.blockSize]; outerInstance.upto = 0; } int offsetEnd = offset + length; while (true) { int left = offsetEnd - offset; int blockLeft = outerInstance.blockSize - outerInstance.upto; if (blockLeft < left) { System.Buffer.BlockCopy(b, offset, outerInstance.currentBlock, outerInstance.upto, blockLeft); outerInstance.blocks.Add(outerInstance.currentBlock); outerInstance.blockEnd.Add(outerInstance.blockSize); outerInstance.currentBlock = new byte[outerInstance.blockSize]; outerInstance.upto = 0; offset += blockLeft; } else { // Last block System.Buffer.BlockCopy(b, offset, outerInstance.currentBlock, outerInstance.upto, left); outerInstance.upto += left; break; } } } /// <summary> /// Return the current byte position. </summary> public long GetPosition() { return outerInstance.GetPointer(); } } /// <summary> /// Returns a <see cref="DataInput"/> to read values from this /// <see cref="PagedBytes"/> instance. /// </summary> public PagedBytesDataInput GetDataInput() { if (!frozen) { throw new InvalidOperationException("must call Freeze() before GetDataInput()"); } return new PagedBytesDataInput(this); } /// <summary> /// Returns a <see cref="DataOutput"/> that you may use to write into /// this <see cref="PagedBytes"/> instance. If you do this, you should /// not call the other writing methods (eg, copy); /// results are undefined. /// </summary> public PagedBytesDataOutput GetDataOutput() { if (frozen) { throw new InvalidOperationException("cannot get DataOutput after Freeze()"); } return new PagedBytesDataOutput(this); } } }
36.635659
136
0.485876
[ "Apache-2.0" ]
Ref12/lucenenet
src/Lucene.Net/Util/PagedBytes.cs
18,904
C#
#if !NETSTANDARD13 /* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the cloud9-2017-09-23.normal.json service model. */ using Amazon.Runtime; namespace Amazon.Cloud9.Model { /// <summary> /// Paginator for the DescribeEnvironmentMemberships operation ///</summary> public interface IDescribeEnvironmentMembershipsPaginator { /// <summary> /// Enumerable containing all full responses for the operation /// </summary> IPaginatedEnumerable<DescribeEnvironmentMembershipsResponse> Responses { get; } } } #endif
33.257143
104
0.714777
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/Cloud9/Generated/Model/_bcl45+netstandard/IDescribeEnvironmentMembershipsPaginator.cs
1,164
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Security; using System.Text; using System.Threading.Tasks; namespace RazorEngine.Templating { /// <summary> /// An memory leaking invalidating caching provider (See <see cref="ICachingProvider"/>). /// This implementation does a very simple in-memory caching and allows you to release templates /// by trading with memory. /// WARNING: /// Use this caching provider only on AppDomains you recycle regulary, or to /// improve the debugging experience. /// Never use this in production without any recycle strategy. /// </summary> public class InvalidatingCachingProvider : ICachingProvider { private readonly ConcurrentDictionary<string, ConcurrentDictionary<Type, ICompiledTemplate>> _cache = new ConcurrentDictionary<string, ConcurrentDictionary<Type, ICompiledTemplate>>(); private readonly TypeLoader _loader; private readonly Action<string> _registerForCleanup; private readonly ConcurrentBag<Assembly> _assemblies = new ConcurrentBag<Assembly>(); /// <summary> /// Initializes a new instance of the <see cref="DefaultCachingProvider"/> class. /// </summary> public InvalidatingCachingProvider() : this(null) { } /// <summary> /// Initializes a new instance of the <see cref="DefaultCachingProvider"/> class. /// </summary> /// <param name="registerForCleanup">callback for files which need to be cleaned up.</param> public InvalidatingCachingProvider(Action<string> registerForCleanup) { _registerForCleanup = registerForCleanup ?? (item => RazorEngine.Compilation.CrossAppDomainCleanUp.RegisterCleanup(item, false)); _loader = new TypeLoader(AppDomain.CurrentDomain, _assemblies); } /// <summary> /// The manages <see cref="TypeLoader"/>. See <see cref="ICachingProvider.TypeLoader"/> /// </summary> public TypeLoader TypeLoader { get { return _loader; } } /// <summary> /// Get the key used within a dictionary for a modelType. /// </summary> public static Type GetModelTypeKey(Type modelType) { if (modelType == null || typeof(System.Dynamic.IDynamicMetaObjectProvider).IsAssignableFrom(modelType)) { return typeof(System.Dynamic.DynamicObject); } return modelType; } private void CacheTemplateHelper(ICompiledTemplate template, ITemplateKey templateKey, Type modelTypeKey) { var uniqueKey = templateKey.GetUniqueKeyString(); _cache.AddOrUpdate(uniqueKey, key => { // new item added _assemblies.Add(template.TemplateAssembly); var dict = new ConcurrentDictionary<Type, ICompiledTemplate>(); dict.AddOrUpdate(modelTypeKey, template, (t, old) => { throw new Exception("Expected the dictionary to be empty."); }); return dict; }, (key, dict) => { dict.AddOrUpdate(modelTypeKey, t => { // new item added (template was not compiled with the given type). _assemblies.Add(template.TemplateAssembly); return template; }, (t, old) => { // item was already added before return template; }); return dict; }); } /// <summary> /// Caches a template. See <see cref="ICachingProvider.CacheTemplate"/>. /// </summary> /// <param name="template"></param> /// <param name="templateKey"></param> public void CacheTemplate(ICompiledTemplate template, ITemplateKey templateKey) { var modelTypeKey = GetModelTypeKey(template.ModelType); _registerForCleanup(template.CompilationData.TmpFolder); CacheTemplateHelper(template, templateKey, modelTypeKey); var typeArgs = template.TemplateType.BaseType.GetGenericArguments(); if (typeArgs.Length > 0) { var alternativeKey = GetModelTypeKey(typeArgs[0]); if (alternativeKey != modelTypeKey) { // could be a template with an @model directive. CacheTemplateHelper(template, templateKey, typeArgs[0]); } } } /// <summary> /// Invalidates the compilation of the given template with the given model-type. /// WARNING: leads to memory leaks /// </summary> /// <param name="templateKey"></param> /// <param name="modelType"></param> public void InvalidateCacheOfType(ITemplateKey templateKey, Type modelType) { var uniqueKey = templateKey.GetUniqueKeyString(); var modelTypeKey = GetModelTypeKey(modelType); ConcurrentDictionary<Type, ICompiledTemplate> dict; if (!_cache.TryGetValue(uniqueKey, out dict)) { // not cached return; } ICompiledTemplate c; dict.TryRemove(modelTypeKey, out c); } /// <summary> /// Invalidates all compilations of the given template. /// WARNING: leads to memory leaks /// </summary> /// <param name="templateKey"></param> public void InvalidateCache(ITemplateKey templateKey) { var uniqueKey = templateKey.GetUniqueKeyString(); ConcurrentDictionary<Type, ICompiledTemplate> dict; _cache.TryRemove(uniqueKey, out dict); } /// <summary> /// Invalidates all compilations. /// WARNING: leads to memory leaks /// </summary> public void InvalidateAll() { _cache.Clear(); } /// <summary> /// Try to retrieve a template from the cache. See <see cref="ICachingProvider.TryRetrieveTemplate"/>. /// </summary> /// <param name="templateKey"></param> /// <param name="modelType"></param> /// <param name="compiledTemplate"></param> /// <returns></returns> public bool TryRetrieveTemplate(ITemplateKey templateKey, Type modelType, out ICompiledTemplate compiledTemplate) { compiledTemplate = null; var uniqueKey = templateKey.GetUniqueKeyString(); var modelTypeKey = GetModelTypeKey(modelType); ConcurrentDictionary<Type, ICompiledTemplate> dict; if (!_cache.TryGetValue(uniqueKey, out dict)) { return false; } return dict.TryGetValue(modelTypeKey, out compiledTemplate); } /// <summary> /// Dispose the instance. /// </summary> public void Dispose() { _loader.Dispose(); } } }
38.140625
121
0.579407
[ "Apache-2.0" ]
HongJunRen/RazorEngine
src/source/RazorEngine.Core/Templating/InvalidatingCachingProvider.cs
7,325
C#
using System.Collections.Generic; using System.Text.Json.Serialization; namespace Essensoft.Paylink.Alipay.Domain { /// <summary> /// AlipayPcreditHuabeiBenefitOrderCreateModel Data Structure. /// </summary> public class AlipayPcreditHuabeiBenefitOrderCreateModel : AlipayObject { /// <summary> /// 支付宝业务单据号,在scene=BLUE_ARROW时候,必填,且值为先享协议号 /// </summary> [JsonPropertyName("alipay_biz_no")] public string AlipayBizNo { get; set; } /// <summary> /// 支付宝用户id /// </summary> [JsonPropertyName("alipay_user_id")] public string AlipayUserId { get; set; } /// <summary> /// 业务自定义参数,例如权益账务相关数据通过该字段传递 [ { "key1": "value1" }, { "key2": "value2" } ] /// </summary> [JsonPropertyName("biz_param")] public List<KeyValuePair> BizParam { get; set; } /// <summary> /// 商户端业务发生时间(yyyy-MM-dd HH:mm:ss) /// </summary> [JsonPropertyName("biz_time")] public string BizTime { get; set; } /// <summary> /// 是否需要多次触发。权益打包和多次触发场景会有为true,默认为false /// </summary> [JsonPropertyName("need_repeat")] public bool NeedRepeat { get; set; } /// <summary> /// 权益商品id /// </summary> [JsonPropertyName("out_goods_id")] public string OutGoodsId { get; set; } /// <summary> /// 商户本次操作的请求流水号,用于标示请求流水的唯一性,不能包含除中文、英文、数字以外的字符,需要保证在商户端不重复。支付宝侧用来做请求的幂等 /// </summary> [JsonPropertyName("out_request_no")] public string OutRequestNo { get; set; } /// <summary> /// 权益商品sku_id,如果此项为空,会发放out_goods_id里面对应的所有sku /// </summary> [JsonPropertyName("out_sku_id")] public string OutSkuId { get; set; } /// <summary> /// 商户请求场景 /// </summary> [JsonPropertyName("scene")] public string Scene { get; set; } /// <summary> /// 是否立即触发发放。默认为false。蓝箭项目里面需要将此项设置为true /// </summary> [JsonPropertyName("trigger_send")] public bool TriggerSend { get; set; } } }
30.180556
122
0.558675
[ "MIT" ]
Frunck8206/payment
src/Essensoft.Paylink.Alipay/Domain/AlipayPcreditHuabeiBenefitOrderCreateModel.cs
2,611
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.Web.V20181101 { /// <summary> /// AzureStorageInfo dictionary resource. /// </summary> [AzureNextGenResourceType("azure-nextgen:web/v20181101:WebAppAzureStorageAccounts")] public partial class WebAppAzureStorageAccounts : Pulumi.CustomResource { /// <summary> /// Kind of resource. /// </summary> [Output("kind")] public Output<string?> Kind { get; private set; } = null!; /// <summary> /// Resource Name. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// Azure storage accounts. /// </summary> [Output("properties")] public Output<ImmutableDictionary<string, Outputs.AzureStorageInfoValueResponse>> Properties { get; private set; } = null!; /// <summary> /// Resource type. /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Create a WebAppAzureStorageAccounts 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 WebAppAzureStorageAccounts(string name, WebAppAzureStorageAccountsArgs args, CustomResourceOptions? options = null) : base("azure-nextgen:web/v20181101:WebAppAzureStorageAccounts", name, args ?? new WebAppAzureStorageAccountsArgs(), MakeResourceOptions(options, "")) { } private WebAppAzureStorageAccounts(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-nextgen:web/v20181101:WebAppAzureStorageAccounts", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:web:WebAppAzureStorageAccounts"}, new Pulumi.Alias { Type = "azure-nextgen:web/latest:WebAppAzureStorageAccounts"}, new Pulumi.Alias { Type = "azure-nextgen:web/v20180201:WebAppAzureStorageAccounts"}, new Pulumi.Alias { Type = "azure-nextgen:web/v20190801:WebAppAzureStorageAccounts"}, new Pulumi.Alias { Type = "azure-nextgen:web/v20200601:WebAppAzureStorageAccounts"}, new Pulumi.Alias { Type = "azure-nextgen:web/v20200901:WebAppAzureStorageAccounts"}, new Pulumi.Alias { Type = "azure-nextgen:web/v20201001:WebAppAzureStorageAccounts"}, }, }; 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 WebAppAzureStorageAccounts 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="options">A bag of options that control this resource's behavior</param> public static WebAppAzureStorageAccounts Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new WebAppAzureStorageAccounts(name, id, options); } } public sealed class WebAppAzureStorageAccountsArgs : Pulumi.ResourceArgs { /// <summary> /// Kind of resource. /// </summary> [Input("kind")] public Input<string>? Kind { get; set; } /// <summary> /// Name of the app. /// </summary> [Input("name", required: true)] public Input<string> Name { get; set; } = null!; [Input("properties")] private InputMap<Inputs.AzureStorageInfoValueArgs>? _properties; /// <summary> /// Azure storage accounts. /// </summary> public InputMap<Inputs.AzureStorageInfoValueArgs> Properties { get => _properties ?? (_properties = new InputMap<Inputs.AzureStorageInfoValueArgs>()); set => _properties = value; } /// <summary> /// Name of the resource group to which the resource belongs. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; public WebAppAzureStorageAccountsArgs() { } } }
41.537879
162
0.614262
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Web/V20181101/WebAppAzureStorageAccounts.cs
5,483
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VertexCodeMakerDomain.Interfaces { public interface IReadException { List<string> ExceptionsCollection { get; set; } } }
19.214286
55
0.743494
[ "MIT" ]
AliMusaev/VertexCode
VertexCodeMakerDomain/Interfaces/IReadException.cs
271
C#
using System; using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Controls; using System.ComponentModel; using System.Threading; using Form.TakiService; using Form.Dialogs; namespace Form { /// <summary> /// Inter_action logic for GamePage.xaml /// </summary> public partial class GamePage { private bool _myTurn; private PlayerList PlayersList { get; set; } = new PlayerList(); private Player Table { get; set; } private Player CurrentPlayer { get; set; } private User CurrentUser { get; set; } = MainWindow.CurrentUser; private Game CurrentGame { get; set; } public bool MyTurn { get => _myTurn; set { _myTurn = value; if (MyTurn) { uctable.CanTakeCardFromDeck(); } else uctable.CannotTakeCardFromDeck(); } } public bool Active { get; set; } public bool ClockWiseRotation { get; set; } public int Turn { get; set; } public int CurrentPlayerIndex { get; set; } public int PlayersCount { get; set; } public int PlusValue { get; set; } public Card OpenTaki { get; set; } public List<Card> Deck { get; set; } public MessageList LocalMessageList { get; set; } public BackgroundWorker BackgroundProgress { get; set; } public GamePage(Game game) { InitializeComponent(); MainWindow.CurrentGamePage = this; CurrentGame = game; SetBackgroundWorker(); ClockWiseRotation = true; uc1.SetAsNonActive(); OpenTaki = null; MyTurn = false; Active = true; PlusValue = 0; int firstPlayerUserId = CurrentGame.Players[0].UserId; ReorderPlayerList(); //the first player is the one to request changes saving in the database every x seconds if (CurrentUser.Id == firstPlayerUserId) { InitialTurn();// broadcast that self is the first player in the game's players list } uctable.TakeCardFromDeckButtonClicked += TakeCardFromDeck; uctable.PassCardToStackButtonClicked += PassCardToDeck; Deck = PlayersList[PlayersList.Count - 1].Hand.ToList(); DataContext = PlayersList; uc1.SetCurrentPlayer(CurrentPlayer); switch (CurrentGame.Players.Count) { case 3: uc2.Visibility = Visibility.Hidden; uc3.SetCurrentPlayer(PlayersList[1]); uc4.Visibility = Visibility.Hidden; uctable.SetCurrentPlayer(Table); break; case 4: uc2.SetCurrentPlayer(PlayersList[1]); uc3.SetCurrentPlayer(PlayersList[2]); uc4.Visibility = Visibility.Hidden; uctable.SetCurrentPlayer(Table); break; case 5: uc2.SetCurrentPlayer(PlayersList[1]); uc3.SetCurrentPlayer(PlayersList[2]); uc4.SetCurrentPlayer(PlayersList[3]); uctable.SetCurrentPlayer(Table); break; } } private void SetBackgroundWorker() { BackgroundProgress = new BackgroundWorker(); BackgroundProgress.DoWork += FetchChanges; BackgroundProgress.RunWorkerCompleted += BackgroundProcess_RunWorkerCompleted; BackgroundProgress.RunWorkerAsync(); } private void FetchChanges(object sender, DoWorkEventArgs e) { Thread.Sleep(100); LocalMessageList = MainWindow.Service.DoAction(CurrentGame.Id, CurrentPlayer.Id); } private void BackgroundProcess_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (Active) { // Update local variables if (LocalMessageList != null && LocalMessageList.Count != 0) { foreach (Message m in LocalMessageList) { switch (m.Action) { case TakiService.Action.Add: PlayersList.Find(p => p.Id == m.Target.Id).Hand.Add(m.Card); break; case TakiService.Action.Remove: Player tempPlayer = PlayersList.Find(p => p.Id == m.Target.Id); // the target player Card tempCard = tempPlayer.Hand.Find(c => c.Id == m.Card.Id); // the target card tempPlayer.Hand.Remove(tempCard); // remove the target card from the target player's hand break; case TakiService.Action.Win: Player winningPlayer = PlayersList.Find(p => p.Id == m.Target.Id); // the winning player if (CurrentPlayer.Id == m.Target.Id) { PlayerWin(); PlayerQuit(); MainWindow.BigFrame.Navigate(new MainMenu()); } else { PlayerWin pw = new PlayerWin(winningPlayer.Username); pw.ShowDialog(); if (PlayersList.Count == 3) { PlayerLoss(); MainWindow.Service.AddAction(new Message() { Action = TakiService.Action.Loss, Target = CurrentPlayer, Reciever = CurrentPlayer.Id, GameId = CurrentGame.Id }); } } break; case TakiService.Action.SwitchHand: CardList l1 = PlayersList.Find(p => p.Id == m.Target.Id).Hand; PlayersList.Find(p => p.Id == m.Target.Id).Hand = PlayersList.Find(p => p.Id == m.Card.Id).Hand; PlayersList.Find(p => p.Id == m.Card.Id).Hand = l1; break; case TakiService.Action.PlusTwo: PlusValue = m.Card.Id; if (CurrentPlayer.Id == m.Target.Id && PlusValue != 0) { if (CurrentPlayer.Hand.Find(c => c.Value == Value.PlusTwo) == null) { TakeMultipleCardsFromDeck(PlusValue); } } break; case TakiService.Action.NextTurn: Turn = PlayersList.FindIndex(p => p.Id == m.Target.Id); MyTurn = (m.Target.Id == CurrentPlayer.Id); Win(); DeclareTurn(); break; case TakiService.Action.SwitchRotation: if (ClockWiseRotation) ClockWiseRotation = false; else ClockWiseRotation = true; break; case TakiService.Action.PlayerQuit: int prevChangesSaverId = PlayersList[0].UserId; Player quitter = PlayersList.Find(p => p.Id == m.Target.Id); PlayersList.Remove(quitter); // remove the quitting player from the local players list PlayersList.TrimExcess(); CurrentGame.Players.TrimExcess(); if (CurrentUser.Id == PlayersList[0].UserId) { InitialTurn(); // broadcast that self is the first player in the game's players list uc1.SetAsActive(); } else { MyTurn = false; } DeclareTurn(); break; } } UpdateUi(); } // Run again BackgroundProgress.RunWorkerAsync(); // This will make the BgWorker run again, and never runs before it is completed. } } public void PrintCards() { string cards = "\n \n --------------------------------------"; foreach (Player p in PlayersList) { cards += "\n \n Player " + p.Username + ":"; foreach (Card c in p.Hand) { cards += "\n value:" + c.Value + ", color:" + c.Color; } } Console.Write(cards); } // this function re-arranges the player in a particular way, to make sure that: // - list[First] is the current player // - all the players after him are arranged in order // - list[Last] is the table private void ReorderPlayerList() { PlayersCount = CurrentGame.Players.Count; CurrentPlayerIndex = CurrentGame.Players.FindIndex(p => p.UserId == CurrentUser.Id); for (int i = 0; i < PlayersCount - 1; i++) { if (CurrentPlayerIndex >= PlayersCount - 1) { PlayersList.Add(CurrentGame.Players[CurrentPlayerIndex % (PlayersCount - 1)]); } else { PlayersList.Add(CurrentGame.Players[CurrentPlayerIndex]); } CurrentPlayerIndex++; } PlayersList.Add(CurrentGame.Players.Find(q => q.Username == "table")); CurrentPlayer = PlayersList[0]; Table = PlayersList[PlayersCount - 1]; } private void ExitGameButton_Click(object sender, RoutedEventArgs e) { ExitDialog dialog = new ExitDialog { Owner = Application.Current.MainWindow }; if (dialog.ShowDialog() == true) { PlayerQuit(); MainWindow.BigFrame.Navigate(new MainMenu()); } } private void UpdateUi() { uc1.UpdateUi(PlayersList[0]); switch (PlayersList.Count) { case 2: uc2.Visibility = Visibility.Hidden; uc3.Visibility = Visibility.Hidden; uc4.Visibility = Visibility.Hidden; uctable.UpdateUi(PlayersList[1]); ForceQuit dialog = new ForceQuit { Owner = Application.Current.MainWindow }; if (dialog.ShowDialog() == true) { PlayerQuit(); MainWindow.BigFrame.Navigate(new MainMenu()); } break; case 3: uc2.Visibility = Visibility.Hidden; uc3.UpdateUi(PlayersList[1]); uc4.Visibility = Visibility.Hidden; uctable.UpdateUi(PlayersList[2]); break; case 4: uc2.UpdateUi(PlayersList[1]); uc3.UpdateUi(PlayersList[2]); uc4.Visibility = Visibility.Hidden; uctable.UpdateUi(PlayersList[3]); break; case 5: uc2.UpdateUi(PlayersList[1]); uc3.UpdateUi(PlayersList[2]); uc4.UpdateUi(PlayersList[3]); uctable.UpdateUi(PlayersList[4]); break; } } private void PassCardToDeck(object sender, EventArgs e) { Player currentPlayer = PlayersList.First(); Player table = PlayersList.Last(); MessageList temp = new MessageList(); Card givenCard = uc1.SelectedCard(); if (givenCard != null) { if (givenCard.Value == Value.TakiAll || givenCard.Value == Value.Taki) { OpenTaki = givenCard; } if (CheckPlay(givenCard, table.Hand[table.Hand.Count - 1])) { for (int i = 0; i < PlayersList.Count; i++) //add for each player, not including the table { if (givenCard.Value != Value.SwitchHandAll) // don't add "SwitchHandsAll" card to table { temp.Add(new Message() // add the top card of the table to the current player { Action = TakiService.Action.Add, Target = table, // the person who's hand is modified Reciever = PlayersList[i].Id, // the peron who this message is for Card = givenCard, // the card modified GameId = CurrentGame.Id // the game modified }); temp.Add(new Message() // add the top card of the table to the current player { Action = TakiService.Action.Remove, Target = CurrentPlayer, // the person who's hand is modified Reciever = PlayersList[i].Id, // the peron who this message is for Card = givenCard, // the card modified GameId = CurrentGame.Id // the game modified }); } } MainWindow.Service.AddActions(temp); Switch(givenCard); } } } private void TakeCardFromDeck(object sender, EventArgs e) { if (PlusValue != 0) { TakeMultipleCardsFromDeck(PlusValue); } else { Player currentPlayer = PlayersList.First(); MessageList temp = new MessageList(); Card takenCard = uctable.GetCardFromStack(); // get a random card for (int i = 0; i < PlayersList.Count; i++) //add for each player, not including the table { temp.Add(new Message()// add the top card of the table to the current player { Action = TakiService.Action.Add, Target = CurrentPlayer, // the person who's hand is modified Reciever = PlayersList[i].Id, // the peron who this message is for Card = takenCard, // the card modified GameId = CurrentGame.Id // the game modified }); temp.Add(new Message()// add the top card of the table to the current player { Action = TakiService.Action.Remove, Target = Table, // the person who's hand is modified Reciever = PlayersList[i].Id, // the peron who this message is for Card = takenCard, // the card modified GameId = CurrentGame.Id // the game modified }); } MainWindow.Service.AddActions(temp); TurnFinished(Value.Nine); // give turn to next player } } private void TakeMultipleCardsFromDeck(int num) { Player currentPlayer = PlayersList.First(); MessageList temp = new MessageList(); for (int i = 0; i < num; i++) { for (int j = 0; j < PlayersList.Count; j++) //add for each player, not including the table { temp.Add(new Message()// add the top card of the table to the current player { Action = TakiService.Action.Add, Target = CurrentPlayer, // the person who's hand is modified Reciever = PlayersList[j].Id, // the peron who this message is for Card = uctable.GetCardFromStack(), // the card modified GameId = CurrentGame.Id // the game modified }); } } MainWindow.Service.AddActions(temp); PlusTwoMessage(0); // finished taking cards TurnFinished(Value.Nine); // give turn to next player } private int GetUserControlOfPlayer(int playerIndex) { if (uc1.CurrentPlayer != null && uc1.CurrentPlayer.Id == PlayersList[playerIndex].Id) return 1; if (uc2.CurrentPlayer != null && uc2.CurrentPlayer.Id == PlayersList[playerIndex].Id) return 2; if (uc3.CurrentPlayer != null && uc3.CurrentPlayer.Id == PlayersList[playerIndex].Id) return 3; return 4; } private void DeclareTurn() // declare the player with the turn as active { switch (GetUserControlOfPlayer(Turn)) { case 1: uc1.SetAsActive(); uc2.SetAsNonActive(); uc3.SetAsNonActive(); uc4.SetAsNonActive(); break; case 2: uc1.SetAsNonActive(); uc2.SetAsActive(); uc3.SetAsNonActive(); uc4.SetAsNonActive(); break; case 3: uc1.SetAsNonActive(); uc2.SetAsNonActive(); uc3.SetAsActive(); uc4.SetAsNonActive(); break; case 4: uc1.SetAsNonActive(); uc2.SetAsNonActive(); uc3.SetAsNonActive(); uc4.SetAsActive(); break; } } public void TurnFinished(Value value) { MessageList temp = new MessageList(); for (int i = 0; i < PlayersList.Count; i++) //add for each player, not including the table { temp.Add(new Message() { Action = TakiService.Action.NextTurn, // give next turn to Target = PlayersList.Find(p => p.Id == GetNextPlayerId(value)), Reciever = PlayersList[i].Id, GameId = CurrentGame.Id }); } MainWindow.Service.AddActions(temp); MyTurn = false; } private void InitialTurn() { uc1.SetAsActive(); MessageList temp = new MessageList(); for (int i = 0; i < PlayersList.Count; i++) //add for each player, not including the table { temp.Add(new Message() { Action = TakiService.Action.NextTurn, // give next turn to self Target = CurrentPlayer, Reciever = PlayersList[i].Id, GameId = CurrentGame.Id }); } MainWindow.Service.AddActions(temp); MyTurn = true; } public void PlayerQuit() { Console.WriteLine("Player" + CurrentPlayer.Username + " removed from the game in the gameList: " + MainWindow.Service.PlayerQuit(CurrentPlayer)); MessageList temp = new MessageList(); for (int i = 0; i < PlayersList.Count; i++) //add for each player, not including the table { temp.Add(new Message() { Action = TakiService.Action.PlayerQuit, Target = CurrentPlayer, Reciever = PlayersList[i].Id, GameId = CurrentGame.Id }); } MainWindow.Service.AddActions(temp); if (MyTurn) TurnFinished(Value.Nine); Active = false; } private bool CheckPlay(Card given, Card table) { if (PlusValue != 0) { if (given.Value == table.Value) return true; } // not Multi-color if (given.Color == Color.Multi || table.Value == Value.TakiAll || given.Color == table.Color || given.Value == table.Value) return true; return false; } private void Switch(Card givenCard) { if (OpenTaki != null) { int colorCount = CurrentPlayer.Hand.FindAll(c => c.Color == OpenTaki.Color || c.Value == Table.Hand[Table.Hand.Count-1].Value).Count - 1; if (givenCard.Value == Value.TakiAll) { colorCount = 2; } if (OpenTaki.Value == Value.TakiAll && givenCard.Value != Value.TakiAll) { switch (givenCard.Color) { case Color.Blue: OpenTaki = new Card() { Id = 61, Color = Color.Blue, Image = "../Resources/Cards/card0061.png", Special = true, Value = Value.Taki }; break; case Color.Green: OpenTaki = new Card() { Id = 13, Color = Color.Green, Image = "../Resources/Cards/card0013.png", Special = true, Value = Value.Taki }; break; case Color.Red: OpenTaki = new Card() { Id = 29, Color = Color.Red, Image = "../Resources/Cards/card0029.png", Special = true, Value = Value.Taki }; break; case Color.Yellow: OpenTaki = new Card() { Id = 45, Color = Color.Yellow, Image = "../Resources/Cards/card0045.png", Special = true, Value = Value.Taki }; break; } } if (colorCount == 0) { OpenTaki = null; TurnFinished(Value.Nine); } else { if (colorCount == 1) // if one playing options is left in open taki { OpenTaki = null; } TurnFinished(Value.Plus); } } else { switch (givenCard.Value) { case Value.SwitchColor: case Value.SwitchColorAll: SwitchColor dialog = new SwitchColor { Owner = Application.Current.MainWindow }; dialog.ShowDialog(); SwitchColorMessage(dialog.SelectedColor); break; case Value.PlusTwo: PlusTwoMessage(PlusValue + 2); break; case Value.SwitchDirection: ChangeRotationMessage(); break; case Value.SwitchHandAll: SwitchHandsMessage(); break; } TurnFinished(givenCard.Value); // GetNextPlayerId will handle this } } private void SwitchHandsMessage() { MessageList temp = new MessageList(); for (int i = 0; i < (PlayersList.Count - 1); i++) //add for each player, not including the table { temp.Add(new Message() // add the top card of the table to the current player { Action = TakiService.Action.Remove, Target = CurrentPlayer, // the person who's hand is modified Reciever = PlayersList[i].Id, // the peron who this message is for Card = new Card() {Id = 67}, // the card modified GameId = CurrentGame.Id // the game modified }); temp.Add(new Message() { Action = TakiService.Action.SwitchHand, Target = CurrentPlayer, Card = new Card() { Id = GetNextPlayerId(Value.Nine) }, // pass the other Player's ID through the card field. Reciever = PlayersList[i].Id, GameId = CurrentGame.Id }); } MainWindow.Service.AddActions(temp); } private void SwitchColorMessage(Card selectedColorCard) { MessageList temp = new MessageList(); for (int i = 0; i < PlayersList.Count; i++) //add for each player, not including the table { temp.Add(new Message() { Action = TakiService.Action.Add, Target = Table, Reciever = PlayersList[i].Id, GameId = CurrentGame.Id, Card = selectedColorCard }); } MainWindow.Service.AddActions(temp); } private void PlusTwoMessage(int num) { MessageList temp = new MessageList(); for (int i = 0; i < PlayersList.Count; i++) //add for each player, not including the table { temp.Add(new Message() { Action = TakiService.Action.PlusTwo, Target = PlayersList.Find(p => p.Id == GetNextPlayerId(Value.Nine)), // get the next player Reciever = PlayersList[i].Id, GameId = CurrentGame.Id, Card = new Card() { Id = num }// the card's id represents the PlusValue Build-up }); } MainWindow.Service.AddActions(temp); } private void ChangeRotationMessage() { MessageList temp = new MessageList(); for (int i = 0; i < PlayersList.Count; i++) //add for each player, not including the table { temp.Add(new Message() { Action = TakiService.Action.SwitchRotation, Target = CurrentPlayer, Reciever = PlayersList[i].Id, GameId = CurrentGame.Id }); } MainWindow.Service.AddActions(temp); } private int GetNextPlayerId(Value value) { // special card switch - case switch (value) { case Value.Stop: if (PlayersList.Count > 3) { if (ClockWiseRotation) return PlayersList[PlayersList.Count - 3].Id; return PlayersList[2].Id; } return CurrentPlayer.Id; case Value.Plus: case Value.Taki: case Value.TakiAll: return CurrentPlayer.Id; case Value.SwitchDirection: { if (!ClockWiseRotation) return PlayersList[PlayersList.Count - 2].Id; return PlayersList[1].Id; } } if (ClockWiseRotation) return PlayersList[PlayersList.Count - 2].Id; return PlayersList[1].Id; } private void Win() { if (CurrentPlayer.Hand.Count == 0) { MessageList temp = new MessageList(); for (int i = 0; i < PlayersList.Count; i++) //add for each player, not including the table { temp.Add(new Message() { Action = TakiService.Action.Win, Target = CurrentPlayer, Reciever = PlayersList[i].Id, GameId = CurrentGame.Id }); } MainWindow.Service.AddActions(temp); } } private void PlayerWin() { CurrentUser.Score += 500; CurrentUser.Wins += 1; CurrentUser.Level = (CurrentUser.Score - CurrentUser.Score % 1000) / 1000; } private void PlayerLoss() { CurrentUser.Score += 200; CurrentUser.Losses += 1; CurrentUser.Level = (CurrentUser.Score - CurrentUser.Score % 1000) / 1000; } } }
35.606407
157
0.433933
[ "MIT" ]
samuelarbibe/Taki
Client/Client/Form/GamePage.xaml.cs
31,122
C#
using System; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; namespace Orleans.Runtime.Messaging { internal class SiloConnectionMaintainer : ILifecycleParticipant<ISiloLifecycle>, ISiloStatusListener, ILifecycleObserver { private readonly ConnectionManager connectionManager; private readonly ISiloStatusOracle siloStatusOracle; private readonly ILogger<SiloConnectionMaintainer> log; public SiloConnectionMaintainer( ConnectionManager connectionManager, ISiloStatusOracle siloStatusOracle, ILogger<SiloConnectionMaintainer> log) { this.connectionManager = connectionManager; this.siloStatusOracle = siloStatusOracle; this.log = log; } public Task OnStart(CancellationToken ct) { this.siloStatusOracle.SubscribeToSiloStatusEvents(this); return Task.CompletedTask; } public Task OnStop(CancellationToken ct) { this.siloStatusOracle.UnSubscribeFromSiloStatusEvents(this); return Task.CompletedTask; } public void Participate(ISiloLifecycle lifecycle) { lifecycle.Subscribe(nameof(SiloConnectionMaintainer), ServiceLifecycleStage.RuntimeInitialize, this); } public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus status) { if (status == SiloStatus.Dead && updatedSilo != siloStatusOracle.SiloAddress) { _ = Task.Run(() => this.CloseConnectionAsync(updatedSilo)); } } private async Task CloseConnectionAsync(SiloAddress silo) { try { // Allow a short grace period to complete sending pending messages (eg, gossip responses) await Task.Delay(TimeSpan.FromSeconds(10)); this.log.LogInformation("Closing connections to defunct silo {SiloAddress}", silo); this.connectionManager.Close(silo); } catch (Exception exception) { this.log.LogInformation("Exception while closing connections to defunct silo {SiloAddress}: {Exception}", silo, exception); } } } }
35.938462
139
0.643836
[ "MIT" ]
ElderJames/orleans
src/Orleans.Runtime/Networking/SiloConnectionMaintainer.cs
2,336
C#
using System.Net; namespace Modbus.Device { using System; using System.Collections.Concurrent; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Net.Sockets; using System.Diagnostics; using System.IO; using System.Timers; using IO; /// <summary> /// Modbus TCP slave device. /// </summary> public class ModbusTcpSlave : ModbusSlave { private readonly object _serverLock = new object(); private readonly ConcurrentDictionary<string, ModbusMasterTcpConnection> _masters = new ConcurrentDictionary<string, ModbusMasterTcpConnection>(); private TcpListener _server; private Timer _timer; private const int TimeWaitResponse = 1000; private ModbusTcpSlave(byte unitId, TcpListener tcpListener) : base(unitId, new EmptyTransport()) { if (tcpListener == null) throw new ArgumentNullException("tcpListener"); _server = tcpListener; } private ModbusTcpSlave(byte unitId, TcpListener tcpListener, double timeInterval) : base(unitId, new EmptyTransport()) { if (tcpListener == null) throw new ArgumentNullException("tcpListener"); _server = tcpListener; _timer = new Timer(timeInterval); _timer.Elapsed += OnTimer; _timer.Enabled = true; } /// <summary> /// Gets the Modbus TCP Masters connected to this Modbus TCP Slave. /// </summary> public ReadOnlyCollection<TcpClient> Masters { get { return new ReadOnlyCollection<TcpClient>(_masters.Values.Select(mc => mc.TcpClient).ToList()); } } /// <summary> /// Gets the server. /// </summary> /// <value>The server.</value> /// <remarks> /// This property is not thread safe, it should only be consumed within a lock. /// </remarks> private TcpListener Server { get { if (_server == null) throw new ObjectDisposedException("Server"); return _server; } } /// <summary> /// Modbus TCP slave factory method. /// </summary> public static ModbusTcpSlave CreateTcp(byte unitId, TcpListener tcpListener) { return new ModbusTcpSlave(unitId, tcpListener); } /// <summary> /// Creates ModbusTcpSlave with timer which polls connected clients every <paramref name="pollInterval"/> /// milliseconds on that they are connected. /// </summary> public static ModbusTcpSlave CreateTcp(byte unitId, TcpListener tcpListener, double pollInterval) { return new ModbusTcpSlave(unitId, tcpListener, pollInterval); } private static bool IsSocketConnected(Socket socket) { bool poll = socket.Poll(TimeWaitResponse, SelectMode.SelectRead); bool available = (socket.Available == 0); return poll && available; } /// <summary> /// Start slave listening for requests. /// </summary> public override void Listen() { Trace.WriteLine(string.Format("Start Modbus Tcp Server.")); lock (_serverLock) { try { Server.Start(); // use Socket async API for compact framework compat Server.Server.BeginAccept(state => AcceptCompleted(state), this); } catch (ObjectDisposedException) { // this happens when the server stops } } } private void OnTimer(object sender, ElapsedEventArgs e) { foreach (var master in _masters.ToList()) { try { if (IsSocketConnected(master.Value.TcpClient.Client) == false) { var endpoint = (IPEndPoint) master.Value.TcpClient.Client.RemoteEndPoint; Trace.WriteLine( $"PollInterval dropping connection to {endpoint.Address}:{endpoint.Port}"); master.Value.CloseConnection(); master.Value.Dispose(); _masters.TryRemove(master.Key, out _); } } catch (Exception ex) { if (!(ex is ObjectDisposedException)) { Trace.TraceError("OnTimer: {0}", ex.Message); } } } } private void OnMasterConnectionClosedHandler(object sender, TcpConnectionEventArgs e) { ModbusMasterTcpConnection connection; if (!_masters.TryRemove(e.EndPoint, out connection)) { var msg = string.Format( CultureInfo.InvariantCulture, "EndPoint {0} cannot be removed, it does not exist.", e.EndPoint); throw new ArgumentException(msg); } Trace.WriteLine(string.Format("Removed Master {0}", e.EndPoint)); } private static void AcceptCompleted(IAsyncResult ar) { ModbusTcpSlave slave = (ModbusTcpSlave)ar.AsyncState; try { try { // use Socket async API for compact framework compat Socket socket = null; lock (slave._serverLock) { if (slave._server == null) // Checks for disposal to an otherwise unnecessary exception (which is slow and hinders debugging). return; try { socket = slave.Server.Server.EndAccept(ar); } catch (Exception) { } } TcpClient client = new TcpClient {Client = socket}; var masterConnection = new ModbusMasterTcpConnection(client, slave); masterConnection.ModbusMasterTcpConnectionClosed += slave.OnMasterConnectionClosedHandler; slave._masters.TryAdd(client.Client.RemoteEndPoint.ToString(), masterConnection); Trace.WriteLine(string.Format("Accept completed.")); } catch (IOException ex) { // Abandon the connection attempt and continue to accepting the next connection. Trace.WriteLine(string.Format("Accept failed: " + ex.Message)); } // Accept another client // use Socket async API for compact framework compat lock (slave._serverLock) { slave.Server.Server.BeginAccept(state => AcceptCompleted(state), slave); } } catch (ObjectDisposedException) { // this happens when the server stops } } /// <summary> /// Releases unmanaged and - optionally - managed resources /// </summary> /// <param name="disposing"> /// <c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only /// unmanaged resources. /// </param> /// <remarks>Dispose is thread-safe.</remarks> protected override void Dispose(bool disposing) { if (disposing) { // double-check locking if (_server != null) { lock (_serverLock) { if (_server != null) { _server.Stop(); _server = null; if (_timer != null) { _timer.Dispose(); _timer = null; } foreach (var key in _masters.Keys) { ModbusMasterTcpConnection connection; if (_masters.TryRemove(key, out connection)) { connection.ModbusMasterTcpConnectionClosed -= OnMasterConnectionClosedHandler; connection.Dispose(); } } } } } } } } }
35.732824
151
0.47351
[ "MIT" ]
spitfire05/NModbusS
NModbusS/Device/ModbusTcpSlave.cs
9,362
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace CoreCSharpPrograming.chap8.ienumerableandienumerator { class IEnumerableAndIEnumeratorInterfaceUsageExec : AChap8ExecObject { public override void Exec() { try { IEnumeratorUsedManaually(); IEnumeratorWithForeach(); BuildIteratorMethodWithYieldKeyword(); LocalFunctionUsage(); // LocalFunctionWithException(); NamedIteratorUsage(); } catch (Exception e) { Console.WriteLine("Exception occurs in IEnumerableAndIEnumeratorInterfaceUsage.cs: {0}\n{1}", e.Message, e.StackTrace); } } /// <summary> /// Manually work with IEnumerator /// </summary> private void IEnumeratorUsedManaually() { Console.WriteLine("=> Manually work with IEnumerator: "); Garage carLot = new Garage(); IEnumerator ienum = carLot.GetEnumerator(); ienum.MoveNext(); Car myCar = (Car)ienum.Current; Console.WriteLine("{0} is going {1} MPH", myCar.PetName, myCar.CurrentSpeed); Console.WriteLine(); } /// <summary> /// IEnumerator work with Foreach Statement /// </summary> private void IEnumeratorWithForeach() { Console.WriteLine("=> IEnumerator work with Foreach Statement: "); SecondGarage carLot = new SecondGarage(); foreach (Car car in carLot) { Console.WriteLine("{0} is going {1} MPH", car.PetName, car.CurrentSpeed); } Console.WriteLine(); } /// <summary> /// Building Iterator Method with yield keyword /// </summary> private void BuildIteratorMethodWithYieldKeyword() { Console.WriteLine("=> Building Iterator Method with yield keyword: "); GarageForIterator carLot = new GarageForIterator(); foreach (Car car in carLot) { Console.WriteLine("{0} is going {1} MPH", car.PetName, car.CurrentSpeed); } Console.WriteLine(); } /// <summary> /// Local Function Usage /// </summary> private void LocalFunctionUsage() { Console.WriteLine("=> Local Function Usage: "); GarageForIteratorForLocalFunction carLot = new GarageForIteratorForLocalFunction(); foreach (Car c in carLot) { Console.WriteLine("{0} is going {1} MPH", c.PetName, c.CurrentSpeed); } Console.WriteLine(); } /// <summary> /// Local Function With Exception /// </summary> private void LocalFunctionWithException() { Console.WriteLine("=> Local Function With Exception: "); GarageForIteratorForLocalFunctionSecond carLot = new GarageForIteratorForLocalFunctionSecond(); IEnumerator carEnumerator = carLot.GetEnumerator(); Console.WriteLine(); } /// <summary> /// Named Iterator Usage /// </summary> private void NamedIteratorUsage() { Console.WriteLine("=> Named Iterator Usage: "); GarageForIteratorForNamedIterator carLot = new GarageForIteratorForNamedIterator(); // Get Items using GetEnumerator() Console.WriteLine("-> Get Items using GetEnumerator()"); foreach (Car c in carLot) { Console.WriteLine("{0} is going {1} MPH", c.PetName, c.CurrentSpeed); } Console.WriteLine(); Console.WriteLine("-> Get Items using custom GetTheCars()"); foreach(Car c in carLot.GetTheCars(true)) { Console.WriteLine("{0} is going {1} MPH", c.PetName, c.CurrentSpeed); } Console.WriteLine(); } } }
29.478873
109
0.550167
[ "MIT" ]
arishu/cn.org.aris
csharp/study/ProCSharp/CSharpConstructsPartOne/chap8/ienumerableandienumerator/IEnumerableAndIEnumeratorInterfaceUsageExec.cs
4,188
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; using Azure.ResourceManager.Core; using Azure.ResourceManager.Network.Models; namespace Azure.ResourceManager.Network { internal partial class ExpressRouteConnectionsRestOperations { private string subscriptionId; private Uri endpoint; private string apiVersion; private ClientDiagnostics _clientDiagnostics; private HttpPipeline _pipeline; private readonly string _userAgent; /// <summary> Initializes a new instance of ExpressRouteConnectionsRestOperations. </summary> /// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param> /// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param> /// <param name="options"> The client options used to construct the current client. </param> /// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="endpoint"> server parameter. </param> /// <param name="apiVersion"> Api Version. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> or <paramref name="apiVersion"/> is null. </exception> public ExpressRouteConnectionsRestOperations(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, ClientOptions options, string subscriptionId, Uri endpoint = null, string apiVersion = "2021-02-01") { this.subscriptionId = subscriptionId ?? throw new ArgumentNullException(nameof(subscriptionId)); this.endpoint = endpoint ?? new Uri("https://management.azure.com"); this.apiVersion = apiVersion ?? throw new ArgumentNullException(nameof(apiVersion)); _clientDiagnostics = clientDiagnostics; _pipeline = pipeline; _userAgent = HttpMessageUtilities.GetUserAgentName(this, options); } internal HttpMessage CreateCreateOrUpdateRequest(string resourceGroupName, string expressRouteGatewayName, string connectionName, ExpressRouteConnectionData putExpressRouteConnectionParameters) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Put; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Network/expressRouteGateways/", false); uri.AppendPath(expressRouteGatewayName, true); uri.AppendPath("/expressRouteConnections/", false); uri.AppendPath(connectionName, true); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(putExpressRouteConnectionParameters); request.Content = content; message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Creates a connection between an ExpressRoute gateway and an ExpressRoute circuit. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="expressRouteGatewayName"> The name of the ExpressRoute gateway. </param> /// <param name="connectionName"> The name of the connection subresource. </param> /// <param name="putExpressRouteConnectionParameters"> Parameters required in an ExpressRouteConnection PUT operation. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="expressRouteGatewayName"/>, <paramref name="connectionName"/>, or <paramref name="putExpressRouteConnectionParameters"/> is null. </exception> public async Task<Response> CreateOrUpdateAsync(string resourceGroupName, string expressRouteGatewayName, string connectionName, ExpressRouteConnectionData putExpressRouteConnectionParameters, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (expressRouteGatewayName == null) { throw new ArgumentNullException(nameof(expressRouteGatewayName)); } if (connectionName == null) { throw new ArgumentNullException(nameof(connectionName)); } if (putExpressRouteConnectionParameters == null) { throw new ArgumentNullException(nameof(putExpressRouteConnectionParameters)); } using var message = CreateCreateOrUpdateRequest(resourceGroupName, expressRouteGatewayName, connectionName, putExpressRouteConnectionParameters); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 201: return message.Response; default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Creates a connection between an ExpressRoute gateway and an ExpressRoute circuit. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="expressRouteGatewayName"> The name of the ExpressRoute gateway. </param> /// <param name="connectionName"> The name of the connection subresource. </param> /// <param name="putExpressRouteConnectionParameters"> Parameters required in an ExpressRouteConnection PUT operation. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="expressRouteGatewayName"/>, <paramref name="connectionName"/>, or <paramref name="putExpressRouteConnectionParameters"/> is null. </exception> public Response CreateOrUpdate(string resourceGroupName, string expressRouteGatewayName, string connectionName, ExpressRouteConnectionData putExpressRouteConnectionParameters, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (expressRouteGatewayName == null) { throw new ArgumentNullException(nameof(expressRouteGatewayName)); } if (connectionName == null) { throw new ArgumentNullException(nameof(connectionName)); } if (putExpressRouteConnectionParameters == null) { throw new ArgumentNullException(nameof(putExpressRouteConnectionParameters)); } using var message = CreateCreateOrUpdateRequest(resourceGroupName, expressRouteGatewayName, connectionName, putExpressRouteConnectionParameters); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 201: return message.Response; default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateGetRequest(string resourceGroupName, string expressRouteGatewayName, string connectionName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Network/expressRouteGateways/", false); uri.AppendPath(expressRouteGatewayName, true); uri.AppendPath("/expressRouteConnections/", false); uri.AppendPath(connectionName, true); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Gets the specified ExpressRouteConnection. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="expressRouteGatewayName"> The name of the ExpressRoute gateway. </param> /// <param name="connectionName"> The name of the ExpressRoute connection. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="expressRouteGatewayName"/>, or <paramref name="connectionName"/> is null. </exception> public async Task<Response<ExpressRouteConnectionData>> GetAsync(string resourceGroupName, string expressRouteGatewayName, string connectionName, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (expressRouteGatewayName == null) { throw new ArgumentNullException(nameof(expressRouteGatewayName)); } if (connectionName == null) { throw new ArgumentNullException(nameof(connectionName)); } using var message = CreateGetRequest(resourceGroupName, expressRouteGatewayName, connectionName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { ExpressRouteConnectionData value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = ExpressRouteConnectionData.DeserializeExpressRouteConnectionData(document.RootElement); return Response.FromValue(value, message.Response); } case 404: return Response.FromValue((ExpressRouteConnectionData)null, message.Response); default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Gets the specified ExpressRouteConnection. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="expressRouteGatewayName"> The name of the ExpressRoute gateway. </param> /// <param name="connectionName"> The name of the ExpressRoute connection. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="expressRouteGatewayName"/>, or <paramref name="connectionName"/> is null. </exception> public Response<ExpressRouteConnectionData> Get(string resourceGroupName, string expressRouteGatewayName, string connectionName, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (expressRouteGatewayName == null) { throw new ArgumentNullException(nameof(expressRouteGatewayName)); } if (connectionName == null) { throw new ArgumentNullException(nameof(connectionName)); } using var message = CreateGetRequest(resourceGroupName, expressRouteGatewayName, connectionName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { ExpressRouteConnectionData value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = ExpressRouteConnectionData.DeserializeExpressRouteConnectionData(document.RootElement); return Response.FromValue(value, message.Response); } case 404: return Response.FromValue((ExpressRouteConnectionData)null, message.Response); default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateDeleteRequest(string resourceGroupName, string expressRouteGatewayName, string connectionName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Delete; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Network/expressRouteGateways/", false); uri.AppendPath(expressRouteGatewayName, true); uri.AppendPath("/expressRouteConnections/", false); uri.AppendPath(connectionName, true); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Deletes a connection to a ExpressRoute circuit. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="expressRouteGatewayName"> The name of the ExpressRoute gateway. </param> /// <param name="connectionName"> The name of the connection subresource. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="expressRouteGatewayName"/>, or <paramref name="connectionName"/> is null. </exception> public async Task<Response> DeleteAsync(string resourceGroupName, string expressRouteGatewayName, string connectionName, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (expressRouteGatewayName == null) { throw new ArgumentNullException(nameof(expressRouteGatewayName)); } if (connectionName == null) { throw new ArgumentNullException(nameof(connectionName)); } using var message = CreateDeleteRequest(resourceGroupName, expressRouteGatewayName, connectionName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 202: case 204: return message.Response; default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Deletes a connection to a ExpressRoute circuit. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="expressRouteGatewayName"> The name of the ExpressRoute gateway. </param> /// <param name="connectionName"> The name of the connection subresource. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="expressRouteGatewayName"/>, or <paramref name="connectionName"/> is null. </exception> public Response Delete(string resourceGroupName, string expressRouteGatewayName, string connectionName, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (expressRouteGatewayName == null) { throw new ArgumentNullException(nameof(expressRouteGatewayName)); } if (connectionName == null) { throw new ArgumentNullException(nameof(connectionName)); } using var message = CreateDeleteRequest(resourceGroupName, expressRouteGatewayName, connectionName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 202: case 204: return message.Response; default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateListRequest(string resourceGroupName, string expressRouteGatewayName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Network/expressRouteGateways/", false); uri.AppendPath(expressRouteGatewayName, true); uri.AppendPath("/expressRouteConnections", false); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Lists ExpressRouteConnections. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="expressRouteGatewayName"> The name of the ExpressRoute gateway. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/> or <paramref name="expressRouteGatewayName"/> is null. </exception> public async Task<Response<ExpressRouteConnectionList>> ListAsync(string resourceGroupName, string expressRouteGatewayName, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (expressRouteGatewayName == null) { throw new ArgumentNullException(nameof(expressRouteGatewayName)); } using var message = CreateListRequest(resourceGroupName, expressRouteGatewayName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { ExpressRouteConnectionList value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = ExpressRouteConnectionList.DeserializeExpressRouteConnectionList(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Lists ExpressRouteConnections. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="expressRouteGatewayName"> The name of the ExpressRoute gateway. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/> or <paramref name="expressRouteGatewayName"/> is null. </exception> public Response<ExpressRouteConnectionList> List(string resourceGroupName, string expressRouteGatewayName, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (expressRouteGatewayName == null) { throw new ArgumentNullException(nameof(expressRouteGatewayName)); } using var message = CreateListRequest(resourceGroupName, expressRouteGatewayName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { ExpressRouteConnectionList value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = ExpressRouteConnectionList.DeserializeExpressRouteConnectionList(document.RootElement); return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } } }
54.84
249
0.640838
[ "MIT" ]
DiskRP-Swagger/azure-sdk-for-net
sdk/network/Azure.ResourceManager.Network/src/Generated/RestOperations/ExpressRouteConnectionsRestOperations.cs
23,307
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: Templates\CSharp\Requests\EntityCollectionResponse.cs.tt namespace Microsoft.Graph { using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; /// <summary> /// The type EducationClassAssignmentCategoriesCollectionResponse. /// </summary> [JsonObject(MemberSerialization = MemberSerialization.OptIn)] public class EducationClassAssignmentCategoriesCollectionResponse { /// <summary> /// Gets or sets the <see cref="IEducationClassAssignmentCategoriesCollectionPage"/> value. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName ="value", Required = Newtonsoft.Json.Required.Default)] public IEducationClassAssignmentCategoriesCollectionPage Value { get; set; } /// <summary> /// Gets or sets additional data. /// </summary> [JsonExtensionData(ReadData = true)] public IDictionary<string, object> AdditionalData { get; set; } } }
42.911765
153
0.634681
[ "MIT" ]
OfficeGlobal/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/EducationClassAssignmentCategoriesCollectionResponse.cs
1,459
C#
using System; using System.Linq.Expressions; using Laraue.EfCoreTriggers.Tests.Infrastructure; using Xunit; namespace Laraue.EfCoreTriggers.Tests.Tests.Base { /// <summary> /// Tests of translating <see cref="string"/> functions to SQL code. /// </summary> public abstract class BaseStringFunctionsTests { /// <summary> /// StringField = OLD.StringField + "abc" /// </summary> protected Expression<Func<SourceEntity, DestinationEntity>> ConcatStringExpression = sourceEntity => new DestinationEntity { StringField = sourceEntity.StringField + "abc" }; [Fact] protected abstract void StringConcatSql(); /// <summary> /// StringField = OLD.StringField.ToLower() /// </summary> protected Expression<Func<SourceEntity, DestinationEntity>> StringToLowerExpression = sourceEntity => new DestinationEntity { StringField = sourceEntity.StringField.ToLower() }; [Fact] protected abstract void StringLowerSql(); /// <summary> /// StringField = OLD.StringField.ToUpper() /// </summary> protected Expression<Func<SourceEntity, DestinationEntity>> StringToUpperExpression = sourceEntity => new DestinationEntity { StringField = sourceEntity.StringField.ToUpper() }; [Fact] protected abstract void StringUpperSql(); /// <summary> /// StringField = OLD.StringField.Trim() /// </summary> protected Expression<Func<SourceEntity, DestinationEntity>> TrimStringValueExpression = sourceEntity => new DestinationEntity { StringField = sourceEntity.StringField.Trim() }; [Fact] protected abstract void StringTrimSql(); /// <summary> /// BooleanValue = OLD.StringField.Contains("abc") /// </summary> protected Expression<Func<SourceEntity, DestinationEntity>> ContainsStringValueExpression = sourceEntity => new DestinationEntity { BooleanValue = sourceEntity.StringField.Contains("abc") }; [Fact] protected abstract void StringContainsSql(); /// <summary> /// BooleanValue = OLD.StringField.EndsWith("abc") /// </summary> protected Expression<Func<SourceEntity, DestinationEntity>> EndsWithStringValueExpression = sourceEntity => new DestinationEntity { BooleanValue = sourceEntity.StringField.EndsWith("abc") }; [Fact] protected abstract void StringEndsWithSql(); /// <summary> /// BooleanValue = string.IsNullOrEmpty(OLD.StringField) /// </summary> protected Expression<Func<SourceEntity, DestinationEntity>> IsNullOrEmptyStringValueExpression = sourceEntity => new DestinationEntity { BooleanValue = string.IsNullOrEmpty(sourceEntity.StringField) }; [Fact] protected abstract void StringIsNullOrEmptySql(); } }
34.022222
142
0.633899
[ "MIT" ]
Ali-YousefiTelori/Laraue.EfCoreTriggers
tests/Laraue.EfCoreTriggers.Tests/Tests/Base/BaseStringFunctionsTests.cs
3,064
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 RedisViewer.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.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; } } } }
34.387097
151
0.581614
[ "MIT" ]
jaklithn/RedisViewer
RedisViewer/Properties/Settings.Designer.cs
1,068
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Draws.RandomStocks.Models; using Fizzler.Systems.HtmlAgilityPack; using HtmlAgilityPack; namespace Draws.RandomStocks.Services { public class HtmlParserService { private HtmlDocument _document; private string _url; public HtmlParserService(string url) { _url = url; } public async Task Initialise() { _document = await new HtmlWeb().LoadFromWebAsync(_url); } public IEnumerable<Ticker> GetAllTickers() { List<Ticker> _tickers = new List<Ticker>(); var htmlNode = _document.DocumentNode; int tickerAmount = Convert.ToInt32(Math.Round((double)htmlNode.QuerySelectorAll("tr").Count() / 3)); for(int i = 0; i < tickerAmount; i++) { var rows = htmlNode.QuerySelectorAll($"#{i}"); foreach (var row in rows) { _tickers.Add(new Ticker() { Name = row.InnerText }); } } return _tickers; } } }
28.948718
112
0.597874
[ "MIT" ]
Drawserqzez/random-ticker-finder
src/Services/HtmlParserService.cs
1,129
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WeaverSmokeTestCS { public partial class Form1 : Form { public Form1() { InitializeComponent(); } } }
18.857143
38
0.65404
[ "MIT" ]
mkaring/Substitute.Fody
WeaverSmokeTestCS/Form1.cs
398
C#
namespace S2Library.Connection { public delegate void ConnectionEventHandler(ConnectionEventArgs args); public delegate void ConnectionResultHandler(ConnectionResultArgs args); public delegate void ConnectionReceiveHandler(ConnectionReceiveArgs args); public class ConnectionEventArgs { public Connection Conn { get; } internal ConnectionEventArgs(Connection conn) { Conn = conn; } } public class ConnectionResultArgs : ConnectionEventArgs { public ConnectionResult Result { get; internal set; } internal ConnectionResultArgs(Connection conn, ConnectionResult result) : base(conn) { Result = result; } } public class ConnectionReceiveArgs : ConnectionEventArgs { public byte[] Data { get; internal set; } internal ConnectionReceiveArgs(Connection conn, byte[] data) : base(conn) { Data = data; } } }
23.6875
80
0.569041
[ "Unlicense" ]
zocker-160/sacred2-lobby-emulator
S2Library/Connection/ConnectionEvents.cs
1,137
C#