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 SFA.DAS.FindEmploymentSchemes.Contentful.Services.Roots.Base; using Xunit; namespace SFA.DAS.FindEmploymentSchemes.UnitTests.Contentful.Services.Roots.Base { public class ContentRootServiceTests { [Theory] [InlineData("\"", "“")] [InlineData("\"", "”")] [InlineData("\"\"", "“”")] [InlineData("\r\n", "\r")] [InlineData("\r\n", "\r\n")] [InlineData("\r\n\r\n", "\r\r\n")] [InlineData("\r\nn", "\rn")] [InlineData("<br>", "<br>")] public void ToNormalisedHtmlString_Tests(string expectedHtmlStringValue, string html) { var result = ContentRootService.ToNormalisedHtmlString(html); Assert.Equal(expectedHtmlStringValue, result.Value); } } }
31.2
93
0.588462
[ "MIT" ]
SkillsFundingAgency/das-employers-front-door
src/SFA.DAS.FindEmploymentSchemes.UnitTests/Contentful/Services/Roots/Base/ContentRootServiceTests.cs
790
C#
#if !NETSTANDARD13 /* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the quicksight-2018-04-01.normal.json service model. */ using Amazon.Runtime; namespace Amazon.QuickSight.Model { /// <summary> /// Paginator for the ListTemplates operation ///</summary> public interface IListTemplatesPaginator { /// <summary> /// Enumerable containing all full responses for the operation /// </summary> IPaginatedEnumerable<ListTemplatesResponse> Responses { get; } } } #endif
31.742857
108
0.70297
[ "Apache-2.0" ]
PureKrome/aws-sdk-net
sdk/src/Services/QuickSight/Generated/Model/_bcl45+netstandard/IListTemplatesPaginator.cs
1,111
C#
// Copyright (c) MudBlazor using System; // ReSharper disable once CheckNamespace internal static class TimeSpanExtensions { public static string ToIsoString(this TimeSpan self, bool seconds = false, bool ms = false) { if (!seconds) return $"{self.Hours:D2}:{self.Minutes:D2}"; if (!ms) return $"{self.Hours:D2}:{self.Minutes:D2}-{self.Seconds:D2}"; return $"{self.Hours:D2}:{self.Minutes:D2}-{self.Seconds:D2},{self.Milliseconds}"; } public static string ToIsoString(this TimeSpan? self, bool seconds = false, bool ms = false) { if (self == null) return null; return self.Value.ToIsoString(seconds, ms); } public static int ToAmPmHour(this TimeSpan time) { var h = time.Hours % 12; if (h == 0) h = 12; return h; } }
27.1875
96
0.591954
[ "MIT" ]
BananaRush/MudBlazor
src/MudBlazor/Extensions/TimeSpanExtensions.cs
872
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Utils.ObjectPooling { /// <summary> /// Class that manages generic object pooling. /// A pooler will expand when needed. /// </summary> public class Pooler : MonoBehaviour { private GameObject _prefab; private List<GameObject> _pooledObjects; public delegate void OnGetPooledObject(Pooler pooler,GameObject pooled); /// <summary> /// Event raise after getting an inactive pooled object /// </summary> public event OnGetPooledObject onGetPooledObject; private void RaiseOnGetPooledObject(Pooler pooler,GameObject pooled) { onGetPooledObject?.Invoke(pooler,pooled); } /// <summary> /// Initialize this pooler /// </summary> /// <param name="prefab">The object to pool</param> public void Init(GameObject prefab) { _prefab = prefab; _pooledObjects = new List<GameObject>(); GenerateObjects(); } private void GenerateObjects() { for (int i = 0; i < PoolersManager.Instance.StartingPooledObjects; i++) { GameObject pooled = Instantiate(_prefab, this.transform); _pooledObjects.Add(pooled); pooled.SetActive(false); } } public List<GameObject> GetPooledObjects() => _pooledObjects; /// <summary> /// Get an object in this pooler /// </summary> /// <param name="startsActive">Activate pooled object on get</param> /// <returns>The pooled object</returns> public GameObject GetPooledObject() { GameObject pooled = FindInactive(); if (pooled == null) { GenerateObjects(); pooled = FindInactive(); } RaiseOnGetPooledObject(this,pooled); pooled.SetActive(true); return pooled; } /// <summary> /// Get a pooled object and starts a coroutine that /// deactivate the pooled object after timeToLive seconds /// </summary> /// <param name="startsActive">Activate pooled object on get</param> /// <param name="timeToLive">Liftetime of the object</param> /// <returns>The pooled object</returns> public GameObject GetPooledObject(float timeToLive) { GameObject pooled = FindInactive(); if (pooled == null) { GenerateObjects(); pooled = FindInactive(); } RaiseOnGetPooledObject(this,pooled); StartCoroutine(PooledObjectLifetime(pooled, timeToLive)); pooled.SetActive(true); return pooled; } public void DeactivatePooledObject(GameObject pooled) { if(!_pooledObjects.Contains(pooled)) return; pooled.transform.position = Vector3.zero; pooled.transform.SetParent(transform); pooled.SetActive(false); } private GameObject FindInactive() { foreach (GameObject pooled in _pooledObjects) { if (!pooled.activeInHierarchy) return pooled; } return null; } private IEnumerator PooledObjectLifetime(GameObject pooled,float duration) { yield return new WaitForSeconds(duration); DeactivatePooledObject(pooled); } } }
28.766917
83
0.537376
[ "MIT" ]
Matteo-Moriani/HellForOne
project/Hell For One/Assets/Scripts/Utils/ObjectPooling/Pooler.cs
3,828
C#
using BuildLight.Common.Extensions; using BuildLight.Common.Models; namespace BuildLight.Common { public class SettingsService { public static Settings ReadSettings(string text) { return text.ConvertJsonTo<Settings>(); } } }
18.4
56
0.65942
[ "MIT" ]
andy-kohne/BuildLight
BuildLight.Common/SettingsService.cs
278
C#
using System; /* 4.1. Написать метод для формирования массива, целочисленные неотрицательные элементы которого вычисляются по следующему рекуррентному соотношению: ai+1 = ai%2==0 ? ai/2 :(3*ai+1). Процесс вычисления завершается, когда ai+1 станет равным 1. Параметр метода задает значение a0. Количество элементов массива заранее не известно, так как определяется значением a0. 4.2. Написать метод вывода элементов массива в виде [индекс] = значение, размещая в строке по 5 элементов. 4.3 В основной программе, вводя значения a0, формировать массив и выводить его элементы на экран. */ class Program { static void Main(string[] args) { uint a; do { Console.Write("Введите a: "); } while (!uint.TryParse(Console.ReadLine(), out a)); PrintArray(FormArray(a)); Console.ReadKey(); } public static uint[] FormArray(uint a) { uint[] arr = new uint[1]; arr[0] = a; int count = 0; // while last element in array is not equal to 1 while (arr[count] != 1) { // check if we need to double size of array if (arr.Length == count + 1) { ChangeArraySize(ref arr, arr.Length * 2, arr.Length); } arr[count + 1] = arr[count] % 2 == 0 ? arr[count] / 2 : 3 * arr[count] + 1; count++; } // check if we need to remove zeros from the tail of the array if (arr.Length > ++count) { Array.Resize(ref arr, count); } return arr; } public static void ChangeArraySize(ref uint[] array, int newArraySize, int numberOfElementsToCopy) { uint[] tempArr = new uint[newArraySize]; Array.Copy(array, tempArr, numberOfElementsToCopy); array = tempArr; } public static void PrintArray(uint[] arr) { for (int i = 0; i < arr.Length; i++) { Console.Write($"[{i}] = {arr[i]}\t"); // move to new line if ((i + 1) % 5 == 0) Console.WriteLine(); } } }
29.776316
106
0.533363
[ "MIT" ]
hse-programming-CSharp2020-2021/CSharp2020-2021
01 module/5seminar/Seminar1_05/Task04/Program.cs
2,696
C#
using System; using System.Collections.Generic; using System.Data; using System.Drawing; using System.Linq; using System.Windows.Forms; namespace HangMan { public partial class Form1 : Form { const int MAX_WRONG_GUESSES = 6; int incorrectGuesses = 0; // incorrect guess counter int letterNo = 0; // keeps track of the highest amount of letters in a word HashSet<char> guessedLetters; // all the letters the player has guessed WordList wl = new WordList(); // world list object public Form1() { InitializeComponent(); guessedLetters = new HashSet<char>(); // stores guessed letters InitializeGame(); // initialize game settings } private void buttonButton_Click(object sender, EventArgs e) { HandleGuess(); } public void WrongGuess() { if (incorrectGuesses < MAX_WRONG_GUESSES) { incorrectGuesses++; // increment wrong guess counter toolStripStatusLabel1.Text = string.Format($"wrong guess #{incorrectGuesses}"); // add hint to debug label statusMessages.Refresh(); // refresh status messages } ChangeHangmanImageTo(incorrectGuesses); // change image if (incorrectGuesses >= MAX_WRONG_GUESSES) { toolStripStatusLabel1.Text = string.Format("hint: {0}", wl.SecretWord); // add hint to debug label statusMessages.Refresh(); // refresh status messages MessageBox.Show($"Maximum number of {MAX_WRONG_GUESSES} guesses reached!", "You lose!", MessageBoxButtons.OK, MessageBoxIcon.Error); InitializeGame(); // start a new game } } public void ChangeHangmanImageTo(int i) { pbHangman.Image = (Image)Properties.Resources.ResourceManager.GetObject("image" + (i + 1)); pbHangman.Invalidate(); } public void InitializeGame() { wl.TestThis(); guessedLetters.Clear(); // clear previous guesses labelGuessed.Text = ""; // reset list of guessed letter guessBox.Text = ""; // reset guess box this.ActiveControl = guessBox; // make guess box the focused control incorrectGuesses = 0; // reset incorrect guess counter ChangeHangmanImageTo(0); // reset hangman image wl.ResetSecretWord(); // reset secret word //toolStripStatusLabel1.Text = string.Format("hint: {0}", wl.SecretWord); // add hint to debug label //statusMessages.Refresh(); // refresh status messages // ensure we have a textbox for each letter while (letterNo < wl.SecretWord.Length) { AddNewTextBox(); } // format each textbox as needed for (int l = 0; l < letterNo; l++) { TextBox tb = (TextBox)this.Controls.Find("added" + l.ToString(), true).FirstOrDefault(); if (l >= wl.SecretWord.Length) { tb.Visible = false; tb.Text = ""; } else { tb.Visible = true; tb.Text = "_"; } } } public TextBox AddNewTextBox() { TextBox txt = new TextBox(); this.Controls.Add(txt); txt.Top = 250; txt.Left = 20 + letterNo * 25; txt.Width = 20; txt.TextAlign = HorizontalAlignment.Center; txt.Name = "added" + letterNo.ToString(); txt.Font = new Font(txt.Font, FontStyle.Bold); txt.ReadOnly = true; txt.BackColor = Color.White; letterNo++; return txt; } bool CheckGuess(char ch) { bool found = false; for (int i = 0; i < wl.SecretWord.Length; i++) { //does char i in the word match char i in the word if (wl.SecretWord[i] == ch) { found = true; // match found! TextBox tb = (TextBox)this.Controls.Find("added" + i.ToString(), true).FirstOrDefault(); tb.Text = ch.ToString(); // show matched letter } } return found; } private bool PlayerWon() { //look at each char in the word and see if it has been guessed for (int i = 0; i < wl.SecretWord.Length; i++) { if (!guessedLetters.Contains(wl.SecretWord[i])) { return false; } //found a character that hasn't been guessed yet } return true; //if we reached here, all the characters must have been guessed } public void HandleGuess() { if (guessBox.Text.Length > 0) //make sure player entered something { char ch = guessBox.Text[0]; //get the 1st character in the text if (guessedLetters.Contains(ch)) { //see if the player has guessed the letter MessageBox.Show($"You've already guessed '{ch}'.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { //if it hasn't been guessed, see if it's in the word guessedLetters.Add(ch); //put the letter in the set of used letters labelGuessed.Text += ch; //append the character to the guessed letters text box if (CheckGuess(ch)) { //see if the that letter was in the secret word if (PlayerWon()) { MessageBox.Show("You win!", "Congrats!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } else { WrongGuess(); // call the wrong guess function } } guessBox.Text = ""; // clear the guess box } else { MessageBox.Show("Please enter a letter a-z", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; //bail out of this function } guessBox.Focus(); // focus on the guess box } private void restartToolStripMenuItem_Click(object sender, EventArgs e) { InitializeGame(); } private void guessBox_Enter(object sender, EventArgs e) { guessBox.Text = ""; } private void aboutToolStripMenuItem_Click(object sender, EventArgs e) { MessageBox.Show("No help for you!", "This is just a joke ;)", MessageBoxButtons.OK, MessageBoxIcon.Information); } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { Application.Exit(); } } }
39.572139
122
0.469198
[ "MIT" ]
StanTsky/HangMan
HangMan/Form1.cs
7,956
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Threading.Tasks; using NUnit.Framework; using Azure.ResourceManager.Resources; using Azure.Core.TestFramework; using Azure.ResourceManager.EventHubs.Models; using Azure.ResourceManager.EventHubs; using Azure.ResourceManager.EventHubs.Tests.Helpers; namespace Azure.ResourceManager.EventHubs.Tests { public class ConsumerGroupTests : EventHubTestBase { private ResourceGroupResource _resourceGroup; private EventHubResource _eventHub; private ConsumerGroupCollection _consumerGroupCollection; public ConsumerGroupTests(bool isAsync) : base(isAsync) { } [SetUp] public async Task CreateNamespaceAndGetEventhubCollection() { _resourceGroup = await CreateResourceGroupAsync(); string namespaceName = await CreateValidNamespaceName("testnamespacemgmt"); EventHubNamespaceCollection namespaceCollection = _resourceGroup.GetEventHubNamespaces(); EventHubNamespaceResource eHNamespace = (await namespaceCollection.CreateOrUpdateAsync(WaitUntil.Completed, namespaceName, new EventHubNamespaceData(DefaultLocation))).Value; EventHubCollection eventhubCollection = eHNamespace.GetEventHubs(); string eventhubName = Recording.GenerateAssetName("eventhub"); _eventHub = (await eventhubCollection.CreateOrUpdateAsync(WaitUntil.Completed, eventhubName, new EventHubData())).Value; _consumerGroupCollection = _eventHub.GetConsumerGroups(); } [TearDown] public async Task ClearNamespaces() { //remove all namespaces under current resource group if (_resourceGroup != null) { EventHubNamespaceCollection namespaceCollection = _resourceGroup.GetEventHubNamespaces(); List<EventHubNamespaceResource> namespaceList = await namespaceCollection.GetAllAsync().ToEnumerableAsync(); foreach (EventHubNamespaceResource eventHubNamespace in namespaceList) { await eventHubNamespace.DeleteAsync(WaitUntil.Completed); } _resourceGroup = null; } } [Test] [RecordedTest] public async Task CreateDeleteConsumerGroup() { //create consumer group string consumerGroupName = Recording.GenerateAssetName("testconsumergroup"); ConsumerGroupResource consumerGroup = (await _consumerGroupCollection.CreateOrUpdateAsync(WaitUntil.Completed, consumerGroupName, new ConsumerGroupData())).Value; Assert.NotNull(consumerGroup); Assert.AreEqual(consumerGroup.Id.Name, consumerGroupName); //validate if created successfully Assert.IsTrue(await _consumerGroupCollection.ExistsAsync(consumerGroupName)); consumerGroup = await _consumerGroupCollection.GetAsync(consumerGroupName); //delete consumer group await consumerGroup.DeleteAsync(WaitUntil.Completed); //validate var exception = Assert.ThrowsAsync<RequestFailedException>(async () => { await _consumerGroupCollection.GetAsync(consumerGroupName); }); Assert.AreEqual(404, exception.Status); Assert.IsFalse(await _consumerGroupCollection.ExistsAsync(consumerGroupName)); } [Test] [RecordedTest] public async Task GetAllConsumerGroups() { //create ten consumer groups for (int i = 0; i < 10; i++) { string consumerGroupName = Recording.GenerateAssetName("testconsumergroup" + i.ToString()); _ = (await _consumerGroupCollection.CreateOrUpdateAsync(WaitUntil.Completed, consumerGroupName, new ConsumerGroupData())).Value; } //validate List<ConsumerGroupResource> list = await _consumerGroupCollection.GetAllAsync().ToEnumerableAsync(); // the count should be 11 because there is a default consumergroup Assert.AreEqual(list.Count, 11); list = await _consumerGroupCollection.GetAllAsync(5, 5).ToEnumerableAsync(); Assert.AreEqual(list.Count, 6); } [Test] [RecordedTest] public async Task UpdateConsumerGroup() { //create consumer group string consumerGroupName = Recording.GenerateAssetName("testconsumergroup"); ConsumerGroupResource consumerGroup = (await _consumerGroupCollection.CreateOrUpdateAsync(WaitUntil.Completed, consumerGroupName, new ConsumerGroupData())).Value; Assert.NotNull(consumerGroup); Assert.AreEqual(consumerGroup.Id.Name, consumerGroupName); //update consumer group and validate consumerGroup.Data.UserMetadata = "update the user meta data"; consumerGroup = (await _consumerGroupCollection.CreateOrUpdateAsync(WaitUntil.Completed, consumerGroupName, consumerGroup.Data)).Value; Assert.AreEqual(consumerGroup.Data.UserMetadata, "update the user meta data"); } } }
48.486239
186
0.686471
[ "MIT" ]
ChenTanyi/azure-sdk-for-net
sdk/eventhub/Azure.ResourceManager.EventHubs/tests/Tests/ConsumerGroupTests.cs
5,287
C#
#region BSD Licence /* Copyright (c) 2013-2014, Doxense SAS All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Doxense nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #endregion namespace FoundationDB.Client.Tests { using FoundationDB.Client; using NUnit.Framework; using System; using System.Text; [TestFixture] public class SliceComparerFacts : FdbTest { #region SliceComparer... [Test] public void Test_SliceComparer_Equals() { var cmp = SliceComparer.Default; Assert.That(cmp, Is.Not.Null); Assert.That(SliceComparer.Default, Is.SameAs(cmp)); Assert.That(cmp.Equals(Slice.Nil, Slice.Nil), Is.True); Assert.That(cmp.Equals(Slice.Empty, Slice.Empty), Is.True); Assert.That(cmp.Equals(Slice.Nil, Slice.Empty), Is.False); Assert.That(cmp.Equals(Slice.Empty, Slice.Nil), Is.False); Assert.That(cmp.Equals(Slice.FromByte(42), Slice.FromByte(42)), Is.True); Assert.That(cmp.Equals(Slice.FromByte(42), Slice.Create(new byte[] { 42 })), Is.True); Assert.That(cmp.Equals(Slice.FromByte(42), Slice.FromByte(77)), Is.False); Assert.That(cmp.Equals(Slice.Create(new byte[] { 65, 66, 67 }), Slice.FromString("ABC")), Is.True); Assert.That(cmp.Equals(Slice.Create(new byte[] { 65, 66, 67, 68 }), Slice.FromString("ABC")), Is.False); var buf1 = Encoding.ASCII.GetBytes("ABBAABA"); var buf2 = Encoding.ASCII.GetBytes("ABBAABA"); Assert.That(cmp.Equals(Slice.Create(buf1, 0, 2), Slice.Create(buf1, 0, 2)), Is.True); Assert.That(cmp.Equals(Slice.Create(buf1, 0, 2), Slice.Create(buf1, 0, 3)), Is.False); Assert.That(cmp.Equals(Slice.Create(buf1, 0, 2), Slice.Create(buf1, 4, 2)), Is.True); Assert.That(cmp.Equals(Slice.Create(buf1, 0, 3), Slice.Create(buf1, 4, 3)), Is.False); Assert.That(cmp.Equals(Slice.Create(buf1, 0, 2), Slice.Create(buf2, 4, 2)), Is.True); Assert.That(cmp.Equals(Slice.Create(buf1, 0, 3), Slice.Create(buf2, 4, 3)), Is.False); } [Test] public void Test_SliceComparer_GetHashCode_Should_Return_Same_As_Slice() { var cmp = SliceComparer.Default; Assert.That(cmp, Is.Not.Null); Assert.That(cmp.GetHashCode(Slice.Nil), Is.EqualTo(Slice.Nil.GetHashCode())); Assert.That(cmp.GetHashCode(Slice.Empty), Is.EqualTo(Slice.Empty.GetHashCode())); Assert.That(cmp.GetHashCode(Slice.Nil), Is.Not.EqualTo(Slice.Empty)); var rnd = new Random(123456); for (int i = 0; i < 100; i++) { var s = Slice.Random(rnd, rnd.Next(1, 16)); Assert.That(cmp.GetHashCode(s), Is.EqualTo(s.GetHashCode())); } } [Test] public void Test_SliceComparer_Compare() { var cmp = SliceComparer.Default; Assert.That(cmp, Is.Not.Null); Assert.That(cmp.Compare(Slice.Nil, Slice.Nil), Is.EqualTo(0)); Assert.That(cmp.Compare(Slice.Empty, Slice.Empty), Is.EqualTo(0)); Assert.That(cmp.Compare(Slice.FromByte(42), Slice.FromByte(42)), Is.EqualTo(0)); //REVIEW: Inconsistency: compare(nil, empty) == 0, but Equals(nil, empty) == false Assert.That(cmp.Compare(Slice.Nil, Slice.Empty), Is.EqualTo(0), "Nil and Empty are considered similar regarding ordering"); Assert.That(cmp.Compare(Slice.Empty, Slice.Nil), Is.EqualTo(0), "Nil and Empty are considered similar regarding ordering"); Assert.That(cmp.Compare(Slice.FromByte(42), Slice.FromByte(77)), Is.LessThan(0)); Assert.That(cmp.Compare(Slice.FromByte(42), Slice.FromByte(21)), Is.GreaterThan(0)); Assert.That(cmp.Compare(Slice.FromByte(42), Slice.Empty), Is.GreaterThan(0)); Assert.That(cmp.Compare(Slice.FromByte(42), Slice.Nil), Is.GreaterThan(0)); Assert.That(cmp.Compare(Slice.FromString("hello"), Slice.FromString("world")), Is.LessThan(0)); Assert.That(cmp.Compare(Slice.FromString("world"), Slice.FromString("hello")), Is.GreaterThan(0)); Assert.That(cmp.Compare(Slice.FromString("hell"), Slice.FromString("hello")), Is.LessThan(0)); Assert.That(cmp.Compare(Slice.FromString("help"), Slice.FromString("hello")), Is.GreaterThan(0)); } #endregion } }
44.487395
126
0.727049
[ "BSD-3-Clause" ]
BedeGaming/foundationdb-dotnet-client
FoundationDB.Tests/Utils/SliceComparerFacts.cs
5,296
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Scf.V20180416.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class ListFunctionsRequest : AbstractModel { /// <summary> /// 以升序还是降序的方式返回结果,可选值 ASC 和 DESC /// </summary> [JsonProperty("Order")] public string Order{ get; set; } /// <summary> /// 根据哪个字段进行返回结果排序,支持以下字段:AddTime, ModTime, FunctionName /// </summary> [JsonProperty("Orderby")] public string Orderby{ get; set; } /// <summary> /// 数据偏移量,默认值为 0 /// </summary> [JsonProperty("Offset")] public long? Offset{ get; set; } /// <summary> /// 返回数据长度,默认值为 20 /// </summary> [JsonProperty("Limit")] public long? Limit{ get; set; } /// <summary> /// 支持FunctionName模糊匹配 /// </summary> [JsonProperty("SearchKey")] public string SearchKey{ get; set; } /// <summary> /// 函数描述,支持模糊搜索 /// </summary> [JsonProperty("Description")] public string Description{ get; set; } /// <summary> /// 过滤条件。 /// - tag:tag-key - String - 是否必填:否 - (过滤条件)按照标签键值对进行过滤。 tag-key使用具体的标签键进行替换。 /// /// 每次请求的Filters的上限为10,Filter.Values的上限为5。 /// </summary> [JsonProperty("Filters")] public Filter[] Filters{ get; set; } /// <summary> /// 内部实现,用户禁止调用 /// </summary> internal override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "Order", this.Order); this.SetParamSimple(map, prefix + "Orderby", this.Orderby); this.SetParamSimple(map, prefix + "Offset", this.Offset); this.SetParamSimple(map, prefix + "Limit", this.Limit); this.SetParamSimple(map, prefix + "SearchKey", this.SearchKey); this.SetParamSimple(map, prefix + "Description", this.Description); this.SetParamArrayObj(map, prefix + "Filters.", this.Filters); } } }
31.438202
85
0.590064
[ "Apache-2.0" ]
YuanXiaoLcx/tencentcloud-sdk-dotnet
TencentCloud/Scf/V20180416/Models/ListFunctionsRequest.cs
3,090
C#
using System.Collections.Generic; using IocPerformance.Benchmarks; namespace IocPerformance.Output { public class MultiOutput : IOutput { private readonly IEnumerable<IOutput> outputs; public MultiOutput(params IOutput[] outputs) { this.outputs = outputs; } public void Create(IEnumerable<IBenchmark> benchmarks, IEnumerable<BenchmarkResult> benchmarkResults) { foreach (var output in this.outputs) { output.Create(benchmarks, benchmarkResults); } } } }
24.583333
109
0.622034
[ "Apache-2.0" ]
BalintPogatsa/IocPerformance
IocPerformance/Output/MultiOutput.cs
592
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace BikBot.Model.DB { using System; using System.Collections.Generic; public partial class gorunum { public int id { get; set; } public string renk { get; set; } public string font { get; set; } } }
30.818182
85
0.4941
[ "MIT" ]
sisbas/BikUpload
BikBot/Model/DB/gorunum.cs
678
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using System.Collections.Generic; using System.Globalization; using System.Threading.Tasks; using Xunit; namespace System.Text.RegularExpressions.Tests { // Tests don't actually use reflection emit, but they do generate assembly via Roslyn in-memory at run time and expect it to be JIT'd. // The tests also use typeof(object).Assembly.Location, which returns an empty string on wasm. [ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported), nameof(PlatformDetection.IsNotMobile), nameof(PlatformDetection.IsNotBrowser))] public class RegexGeneratorParserTests { [Fact] public async Task Diagnostic_MultipleAttributes() { IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class C { [RegexGenerator(""ab"")] [RegexGenerator(""abc"")] private static partial Regex MultipleAttributes(); } "); Assert.Equal("SYSLIB1041", Assert.Single(diagnostics).Id); } public static IEnumerable<object[]> Diagnostic_MalformedCtor_MemberData() { const string Pre = "[RegexGenerator"; const string Post = "]"; const string Middle = "\"abc\", RegexOptions.None, -1, \"extra\""; foreach (bool withParens in new[] { false, true }) { string preParen = withParens ? "(" : ""; string postParen = withParens ? ")" : ""; for (int i = 0; i < Middle.Length; i++) { yield return new object[] { Pre + preParen + Middle.Substring(0, i) + postParen }; yield return new object[] { Pre + preParen + Middle.Substring(0, i) + postParen + Post }; } } } [Theory] [MemberData(nameof(Diagnostic_MalformedCtor_MemberData))] public async Task Diagnostic_MalformedCtor(string attribute) { // Validate the generator doesn't crash with an incomplete attribute IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator($@" using System.Text.RegularExpressions; partial class C {{ {attribute} private static partial Regex MultipleAttributes(); }} "); if (diagnostics.Count != 0) { Assert.Contains(Assert.Single(diagnostics).Id, new[] { "SYSLIB1040", "SYSLIB1042" }); } } [Theory] [InlineData("null")] [InlineData("\"ab[]\"")] public async Task Diagnostic_InvalidRegexPattern(string pattern) { IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator($@" using System.Text.RegularExpressions; partial class C {{ [RegexGenerator({pattern})] private static partial Regex InvalidPattern(); }} "); Assert.Equal("SYSLIB1042", Assert.Single(diagnostics).Id); } [Theory] [InlineData(0x800)] public async Task Diagnostic_InvalidRegexOptions(int options) { IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator(@$" using System.Text.RegularExpressions; partial class C {{ [RegexGenerator(""ab"", (RegexOptions){options})] private static partial Regex InvalidPattern(); }} "); Assert.Equal("SYSLIB1042", Assert.Single(diagnostics).Id); } [Theory] [InlineData(-2)] [InlineData(0)] public async Task Diagnostic_InvalidRegexTimeout(int matchTimeout) { IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator(@$" using System.Text.RegularExpressions; partial class C {{ [RegexGenerator(""ab"", RegexOptions.None, {matchTimeout.ToString(CultureInfo.InvariantCulture)})] private static partial Regex InvalidPattern(); }} "); Assert.Equal("SYSLIB1042", Assert.Single(diagnostics).Id); } [Fact] public async Task Diagnostic_MethodMustReturnRegex() { IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class C { [RegexGenerator(""ab"")] private static partial int MethodMustReturnRegex(); } "); Assert.Equal("SYSLIB1043", Assert.Single(diagnostics).Id); } [Fact] public async Task Diagnostic_MethodMustNotBeGeneric() { IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class C { [RegexGenerator(""ab"")] private static partial Regex MethodMustNotBeGeneric<T>(); } "); Assert.Equal("SYSLIB1043", Assert.Single(diagnostics).Id); } [Fact] public async Task Diagnostic_MethodMustBeParameterless() { IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class C { [RegexGenerator(""ab"")] private static partial Regex MethodMustBeParameterless(int i); } "); Assert.Equal("SYSLIB1043", Assert.Single(diagnostics).Id); } [Fact] public async Task Diagnostic_MethodMustBePartial() { IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class C { [RegexGenerator(""ab"")] private static Regex MethodMustBePartial() => null; } "); Assert.Equal("SYSLIB1043", Assert.Single(diagnostics).Id); } [Theory] [InlineData(LanguageVersion.CSharp9)] [InlineData(LanguageVersion.CSharp10)] public async Task Diagnostic_InvalidLangVersion(LanguageVersion version) { IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class C { [RegexGenerator(""ab"")] private static partial Regex InvalidLangVersion(); } ", langVersion: version); Assert.Equal("SYSLIB1044", Assert.Single(diagnostics).Id); } [Fact] public async Task Diagnostic_RightToLeft_LimitedSupport() { IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class C { [RegexGenerator(""ab"", RegexOptions.RightToLeft)] private static partial Regex RightToLeftNotSupported(); } "); Assert.Equal("SYSLIB1045", Assert.Single(diagnostics).Id); } [Fact] public async Task Diagnostic_NonBacktracking_LimitedSupport() { IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class C { [RegexGenerator(""ab"", RegexOptions.NonBacktracking)] private static partial Regex RightToLeftNotSupported(); } "); Assert.Equal("SYSLIB1045", Assert.Single(diagnostics).Id); } [Fact] public async Task Diagnostic_PositiveLookbehind_LimitedSupport() { IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class C { [RegexGenerator(""(?<=\b20)\d{2}\b"")] private static partial Regex PositiveLookbehindNotSupported(); } "); Assert.Equal("SYSLIB1045", Assert.Single(diagnostics).Id); } [Fact] public async Task Diagnostic_NegativeLookbehind_LimitedSupport() { IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class C { [RegexGenerator(""(?<!(Saturday|Sunday) )\b\w+ \d{1,2}, \d{4}\b"")] private static partial Regex NegativeLookbehindNotSupported(); } "); Assert.Equal("SYSLIB1045", Assert.Single(diagnostics).Id); } [Fact] public async Task Valid_ClassWithoutNamespace() { Assert.Empty(await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class C { [RegexGenerator(""ab"")] private static partial Regex Valid(); } ", compile: true)); } [Theory] [InlineData("RegexOptions.None")] [InlineData("RegexOptions.Compiled")] [InlineData("RegexOptions.IgnoreCase | RegexOptions.CultureInvariant")] public async Task Valid_PatternOptions(string options) { Assert.Empty(await RegexGeneratorHelper.RunGenerator($@" using System.Text.RegularExpressions; partial class C {{ [RegexGenerator(""ab"", {options})] private static partial Regex Valid(); }} ", compile: true)); } [Theory] [InlineData("-1")] [InlineData("1")] [InlineData("1_000")] public async Task Valid_PatternOptionsTimeout(string timeout) { Assert.Empty(await RegexGeneratorHelper.RunGenerator($@" using System.Text.RegularExpressions; partial class C {{ [RegexGenerator(""ab"", RegexOptions.None, {timeout})] private static partial Regex Valid(); }} ", compile: true)); } [Fact] public async Task Valid_NamedArguments() { Assert.Empty(await RegexGeneratorHelper.RunGenerator($@" using System.Text.RegularExpressions; partial class C {{ [RegexGenerator(pattern: ""ab"", options: RegexOptions.None, matchTimeoutMilliseconds: -1)] private static partial Regex Valid(); }} ", compile: true)); } [Fact] public async Task Valid_ReorderedNamedArguments() { Assert.Empty(await RegexGeneratorHelper.RunGenerator($@" using System.Text.RegularExpressions; partial class C {{ [RegexGenerator(options: RegexOptions.None, matchTimeoutMilliseconds: -1, pattern: ""ab"")] private static partial Regex Valid1(); [RegexGenerator(matchTimeoutMilliseconds: -1, pattern: ""ab"", options: RegexOptions.None)] private static partial Regex Valid2(); }} ", compile: true)); } [Theory] [InlineData(false)] [InlineData(true)] public async Task Valid_ClassWithNamespace(bool allowUnsafe) { Assert.Empty(await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; namespace A { partial class C { [RegexGenerator(""ab"")] private static partial Regex Valid(); } } ", compile: true, allowUnsafe: allowUnsafe)); } [Fact] public async Task Valid_ClassWithFileScopedNamespace() { Assert.Empty(await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; namespace A; partial class C { [RegexGenerator(""ab"")] private static partial Regex Valid(); } ", compile: true)); } [Fact] public async Task Valid_ClassWithNestedNamespaces() { Assert.Empty(await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; namespace A { namespace B { partial class C { [RegexGenerator(""ab"")] private static partial Regex Valid(); } } } ", compile: true)); } [Fact] public async Task Valid_NestedClassWithoutNamespace() { Assert.Empty(await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class B { partial class C { [RegexGenerator(""ab"")] private static partial Regex Valid(); } } ", compile: true)); } [Fact] public async Task Valid_NestedClassWithNamespace() { Assert.Empty(await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; namespace A { partial class B { partial class C { [RegexGenerator(""ab"")] private static partial Regex Valid(); } } } ", compile: true)); } [Fact] public async Task Valid_NestedClassWithFileScopedNamespace() { Assert.Empty(await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; namespace A; partial class B { partial class C { [RegexGenerator(""ab"")] private static partial Regex Valid(); } } ", compile: true)); } [Fact] public async Task Valid_NestedClassesWithNamespace() { Assert.Empty(await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; namespace A { public partial class B { internal partial class C { protected internal partial class D { private protected partial class E { private partial class F { [RegexGenerator(""ab"")] private static partial Regex Valid(); } } } } } } ", compile: true)); } [Fact] public async Task Valid_NullableRegex() { Assert.Empty(await RegexGeneratorHelper.RunGenerator(@" #nullable enable using System.Text.RegularExpressions; partial class C { [RegexGenerator(""ab"")] private static partial Regex? Valid(); } ", compile: true)); } [Fact] public async Task Valid_ClassWithGenericConstraints() { Assert.Empty(await RegexGeneratorHelper.RunGenerator(@" using D; using System.Text.RegularExpressions; namespace A { public partial class B<U> { private partial class C<T> where T : IBlah { [RegexGenerator(""ab"")] private static partial Regex Valid(); } } } namespace D { internal interface IBlah { } } ", compile: true)); } public static IEnumerable<object[]> Valid_Modifiers_MemberData() { foreach (string type in new[] { "class", "struct", "record", "record struct", "record class", "interface" }) { string[] typeModifiers = type switch { "class" => new[] { "", "public", "public sealed", "internal abstract", "internal static" }, _ => new[] { "", "public", "internal" } }; foreach (string typeModifier in typeModifiers) { foreach (bool instance in typeModifier.Contains("static") ? new[] { false } : new[] { false, true }) { string[] methodVisibilities = type switch { "class" when !typeModifier.Contains("sealed") && !typeModifier.Contains("static") => new[] { "public", "internal", "private protected", "protected internal", "private" }, _ => new[] { "public", "internal", "private" } }; foreach (string methodVisibility in methodVisibilities) { yield return new object[] { type, typeModifier, instance, methodVisibility }; } } } } } [Theory] [MemberData(nameof(Valid_Modifiers_MemberData))] public async Task Valid_Modifiers(string type, string typeModifier, bool instance, string methodVisibility) { Assert.Empty(await RegexGeneratorHelper.RunGenerator(@$" using System.Text.RegularExpressions; {typeModifier} partial {type} C {{ [RegexGenerator(""ab"")] {methodVisibility} {(instance ? "" : "static")} partial Regex Valid(); }} ", compile: true)); } [Fact] public async Task Valid_MultiplRegexMethodsPerClass() { Assert.Empty(await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class C1 { [RegexGenerator(""a"")] private static partial Regex A(); [RegexGenerator(""b"")] public static partial Regex B(); [RegexGenerator(""b"")] public static partial Regex C(); } partial class C2 { [RegexGenerator(""d"")] public static partial Regex D(); [RegexGenerator(""d"")] public static partial Regex E(); } ", compile: true)); } [Fact] public async Task Valid_NestedVaryingTypes() { Assert.Empty(await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; public partial class A { public partial record class B { public partial record struct C { public partial record D { public partial struct E { [RegexGenerator(""ab"")] public static partial Regex Valid(); } } } } } ", compile: true)); } [Fact] public async Task MultipleTypeDefinitions_DoesntBreakGeneration() { byte[] referencedAssembly = RegexGeneratorHelper.CreateAssemblyImage(@" namespace System.Text.RegularExpressions; [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class RegexGeneratorAttribute : Attribute { public RegexGeneratorAttribute(string pattern){} }", "TestAssembly"); Assert.Empty(await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class C { [RegexGenerator(""abc"")] private static partial Regex Valid(); }", compile: true, additionalRefs: new[] { MetadataReference.CreateFromImage(referencedAssembly) })); } } }
36.743548
198
0.491945
[ "MIT" ]
Zheng-Xu/runtime
src/libraries/System.Text.RegularExpressions/tests/FunctionalTests/RegexGeneratorParserTests.cs
22,781
C#
 using System; using System.Collections.Generic; using System.Globalization; using System.Text; using ADFSTK.ExternalMFA.Resources; using Microsoft.IdentityServer.Web.Authentication.External; namespace ADFSTK.ExternalMFA { internal class ExternalReefedsPresentation : IAdapterPresentationForm { private readonly ExternalAuthenticationException _ex = null; private readonly string _username = string.Empty; private readonly string _url = string.Empty; private readonly string _trustedUrl = string.Empty; private readonly Dictionary<string, string> _dynamicContents = new Dictionary<string, string>() { {Constants.DynamicContentLabels.markerUserName, String.Empty}, {Constants.DynamicContentLabels.markerOverallError, String.Empty}, {Constants.DynamicContentLabels.markerActionUrl, String.Empty}, {Constants.DynamicContentLabels.markerPageIntroductionTitle, String.Empty}, {Constants.DynamicContentLabels.markerPageIntroductionText, String.Empty}, {Constants.DynamicContentLabels.markerPageTitle, String.Empty}, {Constants.DynamicContentLabels.markerPageTabInfoText,String.Empty }, }; public ExternalReefedsPresentation(string username, string proxyUrl,string trustedUrl) { _username = username; _url = proxyUrl; _trustedUrl = trustedUrl; } public ExternalReefedsPresentation(string username, string url, ExternalAuthenticationException ex) : this(username, url,string.Empty) { _ex = ex; _url = url; } /// <summary> /// Replace template markers with explicitly given replacements. /// </summary> /// <param name="input"></param> /// <param name="replacements"></param> /// <returns></returns> private static string Replace(string input, Dictionary<string, string> replacements) { if (string.IsNullOrEmpty(input) || null == replacements) { return input; } // Use StringBuiler and allocate buffer 3 times larger StringBuilder sb = new StringBuilder(input, input.Length * 3); foreach (string key in replacements.Keys) { sb.Replace(key, replacements[key]); } return sb.ToString(); } #region IAdapterPresentationForm Members public string GetFormHtml(int lcid) { var dynamicContents = new Dictionary<string, string>(_dynamicContents) { [Constants.DynamicContentLabels.markerPageIntroductionTitle] = GetPresentationResource(Constants.ResourceNames.PageIntroductionTitle, lcid), [Constants.DynamicContentLabels.markerPageIntroductionText] = GetPresentationResource(Constants.ResourceNames.PageIntroductionText, lcid), [Constants.DynamicContentLabels.markerPageTitle] = GetPageTitle(lcid), [Constants.DynamicContentLabels.markerSubmitButton] = GetPresentationResource(Constants.ResourceNames.SubmitButtonLabel, lcid), [Constants.DynamicContentLabels.markerView] = Constants.ResourceNames.ViewStart, [Constants.DynamicContentLabels.markerPageTabInfoText] = GetPresentationResource(Constants.ResourceNames.TabInfoText,lcid), }; string authPageTemplate = ResourceHandler.GetPresentationResource(Constants.ResourceNames.AuthPageTab, lcid); if (_ex != null) { dynamicContents[Constants.DynamicContentLabels.markerPageIntroductionText] = GetPresentationResource(Constants.ResourceNames.FailedLogin, lcid); authPageTemplate = ResourceHandler.GetPresentationResource(Constants.ResourceNames.AuthPageError, lcid); } dynamicContents[Constants.DynamicContentLabels.markerLoginPageUsername] = _username; dynamicContents[Constants.DynamicContentLabels.markerLoginExternalTabUrl] = _url; dynamicContents[Constants.DynamicContentLabels.markerPageTrustedUrl] = _trustedUrl; return Replace(authPageTemplate, dynamicContents); } #endregion #region IAdapterPresentationIndirect Members public string GetFormPreRenderHtml(int lcid) { return null; } public string GetPageTitle(int lcid) { return GetPresentationResource(Constants.ResourceNames.PageTitle, lcid); } #endregion protected string GetPresentationResource(string resourceName, int lcid) { return ResourceHandler.GetResource(resourceName, lcid); } } }
43.428571
160
0.664679
[ "Apache-2.0" ]
canariecaf/adfstoolkit
src/ADFSToolkitExternalMFAAdapter/Adapter/ExternalReefedsPresentation.cs
4,866
C#
// StrawberryShake.CodeGeneration.CSharp.ResultInterfaceGenerator #nullable enable namespace StrawberryShake.CodeGeneration.CSharp.Analyzers.StarWars { [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "11.0.0")] public interface IGetPeople_People_PersonConnection : IGetPeople_People { } }
25.692308
80
0.775449
[ "MIT" ]
HonzaBejvl/hotchocolate
src/StrawberryShake/SourceGenerator/test/CodeGeneration.CSharp.Analyzers.Tests/StarWars/Generated/IGetPeople_People_PersonConnection.StarWarsClient.StrawberryShake.cs
336
C#
 using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using NUnit.Framework; using Unity.Editor.Tasks; using Unity.Editor.Tasks.Extensions; using Unity.Editor.Tasks.Helpers; using Unity.Editor.Tasks.Logging; using Unity.VersionControl.Git; namespace BaseTests { using IntegrationTests; #if NUNIT using TestWebServer; #endif using System; using System.Threading; using Unity.VersionControl.Git.IO; using ILogging = Unity.Editor.Tasks.Logging.ILogging; internal class TestRepoData { public TestRepoData(TestData test, string repoName) { RepoPath = test.TestPath.Combine("IOTestsRepo", repoName); DotGitPath = RepoPath.Combine(".git"); if (DotGitPath.FileExists()) { DotGitPath = DotGitPath.ReadAllLines().Where(x => x.StartsWith("gitdir:")) .Select(x => x.Substring(7).Trim().ToSPath()).First(); } BranchesPath = DotGitPath.Combine("refs", "heads"); RemotesPath = DotGitPath.Combine("refs", "remotes"); DotGitIndex = DotGitPath.Combine("index"); DotGitHead = DotGitPath.Combine("HEAD"); DotGitConfig = DotGitPath.Combine("config"); } public readonly SPath RepoPath; public readonly SPath DotGitConfig; public readonly SPath DotGitHead; public readonly SPath DotGitIndex; public readonly SPath RemotesPath; public readonly SPath BranchesPath; public readonly SPath DotGitPath; } internal class TestData : IDisposable { public readonly Stopwatch Watch; public readonly ILogging Logger; public readonly SPath TestPath; public readonly SPath SourceDirectory; public readonly string TestName; public readonly IGitEnvironment Environment; public readonly IApplicationManager ApplicationManager; public IPlatform Platform => ApplicationManager.Platform; public ITaskManager TaskManager => Platform.TaskManager; public IProcessManager ProcessManager => Platform.ProcessManager; public IProcessEnvironment GitProcessEnvironment => Platform.GitProcessEnvironment; public IProcessEnvironment DefaultProcessEnvironment => Platform.DefaultProcessEnvironment; public IGitClient GitClient => ApplicationManager.GitClient; public IRepository Repository => Environment.Repository; public IRepositoryManager RepositoryManager { get; private set; } #if NUNIT public readonly HttpServer HttpServer; #endif public TestRepoData TestRepo { get; private set; } public const string TestRepoMasterCleanSynchronized = "IOTestsRepo_master_clean_sync"; public const string TestRepoMasterCleanUnsynchronized = "IOTestsRepo_master_clean_unsync"; public const string TestRepoMasterCleanUnsynchronizedRussianLanguage = "IOTestsRepo_master_clean_sync_with_russian_language"; public const string TestRepoMasterDirtyUnsynchronized = "IOTestsRepo_master_dirty_unsync"; public const string TestRepoMasterTwoRemotes = "IOTestsRepo_master_two_remotes"; public const string DefaultExtensionFolder = "ExtensionFolder"; public const string DefaultUserProfilePath = "UserProfile"; public const string DefaultUnityProjectPathAndRepositoryPath = "UnityProject"; private readonly CancellationTokenSource cts; public TestData(string testName, ILogging logger, string testRepoName = null, bool withHttpServer = false, ICacheContainer cacheContainer = null, IFileSystem fileSystem = null) { TestName = testName; Logger = logger; Watch = new Stopwatch(); SourceDirectory = TestContext.CurrentContext.TestDirectory.ToSPath(); TestPath = SPath.CreateTempDirectory(testName); SPath.FileSystem = fileSystem ?? new FileSystem(TestPath); if (cacheContainer == null) { var container = new CacheContainer(); container.SetCacheInitializer(CacheType.Branches, () => BranchesCache.Instance); container.SetCacheInitializer(CacheType.GitAheadBehind, () => GitAheadBehindCache.Instance); container.SetCacheInitializer(CacheType.GitLocks, () => GitLocksCache.Instance); container.SetCacheInitializer(CacheType.GitLog, () => GitLogCache.Instance); container.SetCacheInitializer(CacheType.GitStatus, () => GitStatusCache.Instance); container.SetCacheInitializer(CacheType.GitUser, () => GitUserCache.Instance); container.SetCacheInitializer(CacheType.RepositoryInfo, () => RepositoryInfoCache.Instance); cacheContainer = container; } Environment = new IntegrationTestEnvironment(cacheContainer, TestPath, TestPath.Parent, testName); InitializeEnvironment(testRepoName); ApplicationManager = new ApplicationManagerBase(new MainThreadSynchronizationContext(), Environment); if (testRepoName != null) { var testZipFilePath = SourceDirectory.Combine("IOTestsRepo.zip"); ZipHelper.Instance.Extract(testZipFilePath, TestPath, (_, __) => { }, (value, total, name) => true, token: TaskManager.Token); TestRepo = new TestRepoData(this, testRepoName); InstallTestGit(); InitializeRepository(); } #if NUNIT if (withHttpServer) { var filesToServePath = SourceDirectory.Combine("files"); HttpServer = new HttpServer(filesToServePath, 0); var started = new ManualResetEventSlim(); var task = TaskManager.With(HttpServer.Start, TaskAffinity.None); task.OnStart += _ => started.Set(); task.Start(); started.Wait(); } #endif ((ApplicationManagerBase)ApplicationManager).Initialize(); Logger.Trace($"START {testName}"); Watch.Start(); } public void InitializeRepository() { RepositoryManager = Unity.VersionControl.Git.RepositoryManager.CreateInstance(Platform, TaskManager, GitClient, TestRepo.RepoPath); RepositoryManager.Initialize(); Environment.InitializeRepository(TestRepo.RepoPath); Repository.Initialize(RepositoryManager, TaskManager); RepositoryManager.Start(); Repository.Start(); } public void InstallTestGit() { var installDetails = Environment.GitDefaultInstallation; var state = installDetails.GetDefaults(); Environment.GitInstallationState = state; if (installDetails.GitExecutablePath.FileExists() && installDetails.GitLfsExecutablePath.FileExists()) return; var key = installDetails.GitManifest.FileNameWithoutExtension + "_updatelastCheckTime"; Environment.UserSettings.Set(key, DateTimeOffset.Now); var localCache = SourceDirectory.Combine("files/git"); localCache.CopyFiles(installDetails.ZipPath.Parent, true); // skip checking for updates state.GitPackage = DugiteReleaseManifest.Load(TaskManager, installDetails.GitManifest, GitInstaller.GitInstallDetails.ManifestFeed, Environment); var asset = state.GitPackage.DugitePackage; state.GitZipPath = installDetails.ZipPath.Combine(asset.Name); installDetails.GitInstallationPath.DeleteIfExists(); state.GitZipPath.EnsureParentDirectoryExists(); var gitExtractPath = TestPath.Combine("setup", "git_zip_extract_zip_paths").EnsureDirectoryExists(); var source = new UnzipTask(TaskManager, state.GitZipPath, gitExtractPath) .RunSynchronously(); installDetails.GitInstallationPath.EnsureParentDirectoryExists(); source.Move(installDetails.GitInstallationPath); } private void InitializeEnvironment(string testRepoName) { var projectPath = TestPath.Combine(DefaultUnityProjectPathAndRepositoryPath); if (testRepoName != null) { projectPath = TestPath.Combine("IOTestsRepo", testRepoName); } #if UNITY_EDITOR Environment.Initialize(SPath.Default, projectPath, TheEnvironment.instance.Environment.UnityVersion, TheEnvironment.instance.Environment.UnityApplication, TheEnvironment.instance.Environment.UnityApplicationContents); #else SPath unityPath, unityContentsPath; unityPath = CurrentExecutionDirectory; while (!unityPath.IsEmpty && !unityPath.DirectoryExists(".Editor")) unityPath = unityPath.Parent; if (!unityPath.IsEmpty) { unityPath = unityPath.Combine(".Editor"); unityContentsPath = unityPath.Combine("Data"); } else { unityPath = unityContentsPath = SPath.Default; } Environment.Initialize(SPath.Default, projectPath, "2019.2", unityPath, unityContentsPath); #endif } public void Dispose() { Watch.Stop(); #if NUNIT try { if (HttpServer != null) { HttpServer.Stop(); } } catch { } #endif ProcessManager.Dispose(); if (SynchronizationContext.Current is IMainThreadSynchronizationContext ourContext) ourContext.Dispose(); TaskManager.Dispose(); //TestPath.Delete(); Logger.Trace($"STOP {TestName} :{Watch.ElapsedMilliseconds}ms"); } internal SPath CurrentExecutionDirectory => System.Reflection.Assembly.GetExecutingAssembly().Location.ToSPath().Parent; } public partial class BaseTest { protected const int Timeout = 5000; protected const int RandomSeed = 120938; protected void StartTrackTime(Stopwatch watch, ILogging logger, string message = "") { if (!string.IsNullOrEmpty(message)) logger.Trace(message); watch.Reset(); watch.Start(); } protected void StopTrackTimeAndLog(Stopwatch watch, ILogging logger) { watch.Stop(); logger.Trace($"Time: {watch.ElapsedMilliseconds}"); } protected ActionTask GetTask(ITaskManager taskManager, TaskAffinity affinity, int id, Action<int> body) { return new ActionTask(taskManager, _ => body(id)) { Affinity = affinity }; } protected static IEnumerable<object> StartAndWaitForCompletion(params ITask[] tasks) { foreach (var task in tasks) task.Start(); while (!tasks.All(x => x.Task.IsCompleted)) yield return null; } protected static IEnumerable<object> StartAndWaitForCompletion(IEnumerable<ITask> tasks) { foreach (var task in tasks) task.Start(); while (!tasks.All(x => x.Task.IsCompleted)) yield return null; } protected static IEnumerable<object> WaitForCompletion(params ITask[] tasks) { while (!tasks.All(x => x.Task.IsCompleted)) yield return null; } protected static IEnumerable<object> WaitForCompletion(IEnumerable<ITask> tasks) { while (!tasks.All(x => x.Task.IsCompleted)) yield return null; } protected static IEnumerable<object> WaitForCompletion(IEnumerable<Task> tasks) { while (!tasks.All(x => x.IsCompleted)) yield return null; } protected static IEnumerable<object> WaitForCompletion(params Task[] tasks) { while (!tasks.All(x => x.IsCompleted)) yield return null; } } internal static class TestExtensions { public static void Matches(this GitBranch branch, GitBranch other) { Assert.AreEqual(other, branch); } public static void Matches(this GitRemote branch, GitRemote other) { Assert.AreEqual(other, branch); } public static void Matches(this GitStatus branch, GitStatus other) { Assert.AreEqual(other, branch); } public static void Matches(this IEnumerable actual, IEnumerable expected) { CollectionAssert.AreEqual(expected, actual, $"{Environment.NewLine}expected:{expected.Join()}{Environment.NewLine}actual :{actual.Join()}{Environment.NewLine}"); } public static void Matches<T>(this IEnumerable<T> actual, IEnumerable<T> expected) { CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray(), $"{Environment.NewLine}expected:{expected.Join()}{Environment.NewLine}actual :{actual.Join()}{Environment.NewLine}"); } public static void MatchesUnsorted(this IEnumerable actual, IEnumerable expected) { CollectionAssert.AreEquivalent(expected, actual, $"{Environment.NewLine}expected:{expected.Join()}{Environment.NewLine}actual :{actual.Join()}{Environment.NewLine}"); } public static void MatchesUnsorted<T>(this IEnumerable<T> actual, IEnumerable<T> expected) { CollectionAssert.AreEquivalent(expected.ToArray(), actual.ToArray(), $"{Environment.NewLine}expected:{expected.Join()}{Environment.NewLine}actual :{actual.Join()}{Environment.NewLine}"); } public static void Matches(this string actual, string expected) => Assert.AreEqual(expected, actual); public static void Matches(this int actual, int expected) => Assert.AreEqual(expected, actual); public static void Matches(this SPath actual, SPath expected) => Assert.AreEqual(expected, actual); public static UriString FixPort(this UriString url, int port) { var uri = url.ToUri(); return UriString.TryParse(new UriBuilder(uri.Scheme, uri.Host, port, uri.PathAndQuery).Uri.ToString()); } } static class KeyValuePair { public static KeyValuePair<TKey, TValue> Create<TKey, TValue>(TKey key, TValue value) { return new KeyValuePair<TKey, TValue>(key, value); } } }
40.002725
229
0.645596
[ "MIT" ]
Cdddo/Git-for-Unity
src/com.unity.git.ui/Tests/Editor/BaseTest_Shared.cs
14,683
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/ctffunc.h in the Windows SDK for Windows 10.0.22000.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; using System.Runtime.Versioning; using static TerraFX.Interop.Windows.IID; namespace TerraFX.Interop.Windows.UnitTests; /// <summary>Provides validation of the <see cref="ITfFnGetLinguisticAlternates" /> struct.</summary> [SupportedOSPlatform("windows8.1")] public static unsafe partial class ITfFnGetLinguisticAlternatesTests { /// <summary>Validates that the <see cref="Guid" /> of the <see cref="ITfFnGetLinguisticAlternates" /> struct is correct.</summary> [Test] public static void GuidOfTest() { Assert.That(typeof(ITfFnGetLinguisticAlternates).GUID, Is.EqualTo(IID_ITfFnGetLinguisticAlternates)); } /// <summary>Validates that the <see cref="ITfFnGetLinguisticAlternates" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<ITfFnGetLinguisticAlternates>(), Is.EqualTo(sizeof(ITfFnGetLinguisticAlternates))); } /// <summary>Validates that the <see cref="ITfFnGetLinguisticAlternates" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(ITfFnGetLinguisticAlternates).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="ITfFnGetLinguisticAlternates" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { if (Environment.Is64BitProcess) { Assert.That(sizeof(ITfFnGetLinguisticAlternates), Is.EqualTo(8)); } else { Assert.That(sizeof(ITfFnGetLinguisticAlternates), Is.EqualTo(4)); } } }
38.09434
145
0.716196
[ "MIT" ]
reflectronic/terrafx.interop.windows
tests/Interop/Windows/Windows/um/ctffunc/ITfFnGetLinguisticAlternatesTests.cs
2,021
C#
[TaskCategoryAttribute] // RVA: 0x151600 Offset: 0x151701 VA: 0x151600 [TaskDescriptionAttribute] // RVA: 0x151600 Offset: 0x151701 VA: 0x151600 public class GetEnableEmission : Action // TypeDefIndex: 11189 { // Fields [TooltipAttribute] // RVA: 0x18CA80 Offset: 0x18CB81 VA: 0x18CA80 public SharedGameObject targetGameObject; // 0x50 [TooltipAttribute] // RVA: 0x18CAC0 Offset: 0x18CBC1 VA: 0x18CAC0 [RequiredFieldAttribute] // RVA: 0x18CAC0 Offset: 0x18CBC1 VA: 0x18CAC0 public SharedBool storeResult; // 0x58 private ParticleSystem particleSystem; // 0x60 private GameObject prevGameObject; // 0x68 // Methods // RVA: 0x2879BD0 Offset: 0x2879CD1 VA: 0x2879BD0 Slot: 5 public override void OnStart() { } // RVA: 0x2879CD0 Offset: 0x2879DD1 VA: 0x2879CD0 Slot: 6 public override TaskStatus OnUpdate() { } // RVA: 0x2879DF0 Offset: 0x2879EF1 VA: 0x2879DF0 Slot: 16 public override void OnReset() { } // RVA: 0x2879E40 Offset: 0x2879F41 VA: 0x2879E40 public void .ctor() { } }
34.482759
73
0.749
[ "MIT" ]
SinsofSloth/RF5-global-metadata
BehaviorDesigner/Runtime/Tasks/Unity/UnityParticleSystem/GetEnableEmission.cs
1,000
C#
using CsvHelper; using Dosh.Core.DoshFile; using Dosh.Core.Logger; using Dosh.Core.Provider.Crawler; using Dosh.Middleware.DB; using System; using System.Globalization; using System.IO; namespace db_crawl { public class DBCrawler : ICrawler { /// <summary> /// Logger /// </summary> public ILogger Logger { get; set; } /// <summary> /// DBClient /// </summary> public IDBClient DBClient { get; set; } /// <summary> /// DoshFileModel /// </summary> public DoshFileModel DoshFileModel { get; set; } /// <summary> /// ExportDirectoryRootPath /// </summary> public string ExportDirectoryRootPath { get; set; } /// <summary> /// DBDefinition /// </summary> private readonly DBDefinition DBDefinition; /// <summary> /// BotConfig /// </summary> private readonly BotConfig BotConfig; /// <summary> /// Resource disposed flag /// </summary> private bool disposed = false; /// <summary> /// Gathering the result /// </summary> public void Gather() { var directory = createExportDirectory(ExportDirectoryRootPath); exportRecordToCsv(directory); } /// <summary> /// Export records to CSV /// </summary> private void exportRecordToCsv(string exportDirectoryPath) { DBClient.Connect(); foreach (var targetTable in BotConfig.Target) { var records = DBClient.ExecuteQuery($"select * from {targetTable}"); using (var writer = new StreamWriter(Path.Combine(exportDirectoryPath, $"{targetTable}.csv"), true)) using (var csvWriter = new CsvWriter(writer, CultureInfo.CurrentCulture)) { records.ForEach(record => { csvWriter.WriteField(record); csvWriter.NextRecord(); }); csvWriter.NextRecord(); csvWriter.Flush(); } } } /// <summary> /// Create directory /// </summary> private string createExportDirectory(string exportDirectoryRootPath) { if (!Directory.Exists(exportDirectoryRootPath)) { throw new Exception(); } var directory = Path.Combine(exportDirectoryRootPath, "DB"); try { Directory.CreateDirectory(directory); } catch (IOException ioEx) { } catch (UnauthorizedAccessException anAuthEx) { } return directory; } /// <summary> /// Destroy the resource. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Destroy the resource. /// </summary> /// <param name="disposing">disposing</param> protected void Dispose(bool disposing) { if (!disposed) { if (disposing) { } Logger.Dispose(); disposed = true; } } /// <summary> /// Finalizer /// </summary> ~DBCrawler() { Dispose(false); } } }
25.43662
116
0.482835
[ "MIT" ]
atEaE/dosh
Providers/Crawler/db-crawl/DBCrawler.cs
3,614
C#
// <copyright file="TextureBatchServiceTests.cs" company="KinsonDigital"> // Copyright (c) KinsonDigital. All rights reserved. // </copyright> namespace VelaptorTests.Services { // ReSharper disable UseObjectOrCollectionInitializer using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Drawing; using System.Linq; using Velaptor.Graphics; using Velaptor.OpenGL; using Velaptor.Services; using VelaptorTests.Helpers; using Xunit; /// <summary> /// Tests the <see cref="TextureBatchService"/> class. /// </summary> public class TextureBatchServiceTests { #region Prop Tests [Fact] public void BatchSize_WhenSettingValue_ReturnsCorrectResult() { // Arrange var service = new TextureBatchService(); // Act service.BatchSize = 123u; var actual = service.BatchSize; // Assert Assert.Equal(123u, actual); } [Fact] public void BatchItems_WhenSettingValue_ReturnsCorrectResult() { // Arrange var batchItem1 = (true, new SpriteBatchItem() { Angle = 1, Effects = RenderEffects.None, Size = 2, DestRect = new RectangleF(3, 4, 5, 6), SrcRect = new RectangleF(7, 8, 9, 10), TextureId = 11, TintColor = Color.FromArgb(12, 13, 14, 15), ViewPortSize = new SizeF(16, 17), }); var batchItem2 = (true, new SpriteBatchItem() { Angle = 18, Effects = RenderEffects.FlipHorizontally, Size = 19, DestRect = new RectangleF(20, 21, 22, 23), SrcRect = new RectangleF(24, 25, 26, 27), TextureId = 28, TintColor = Color.FromArgb(29, 30, 31, 32), ViewPortSize = new SizeF(33, 34), }); var batchItems = new List<(bool, SpriteBatchItem)> { batchItem1, batchItem2 }; var expected = new ReadOnlyDictionary<uint, (bool, SpriteBatchItem)>(batchItems.ToDictionary()); var service = new TextureBatchService(); // Act service.BatchItems = batchItems.ToReadOnlyDictionary(); var actual = service.BatchItems; // Assert AssertExtensions.ItemsEqual(expected.Keys.ToArray(), actual.Keys.ToArray()); AssertExtensions.ItemsEqual(expected.Values.ToArray(), actual.Values.ToArray()); } #endregion #region Method Tests [Fact] public void Add_WhenSwitchingTextures_InvokesBatchFilledEvent() { // Arrange var batchItem1 = default(SpriteBatchItem); batchItem1.TextureId = 10; var batchItem2 = default(SpriteBatchItem); batchItem2.TextureId = 20; var service = new TextureBatchService(); service.BatchSize = 100; service.Add(batchItem1); // Act & Assert Assert.Raises<EventArgs>(e => { service.BatchFilled += e; }, e => { service.BatchFilled -= e; }, () => { service.Add(batchItem2); }); // Assert.Equal(1, service.BatchItems.Count); } [Fact] public void Add_WhenBatchIsFull_InvokesBatchFilledEvent() { // Arrange var batchItem1 = default(SpriteBatchItem); batchItem1.TextureId = 10; var batchItem2 = default(SpriteBatchItem); batchItem2.TextureId = 10; var service = new TextureBatchService(); service.BatchSize = 1; service.Add(batchItem1); // Act & Assert Assert.Raises<EventArgs>(e => { service.BatchFilled += e; }, e => { service.BatchFilled -= e; }, () => { service.Add(batchItem2); }); Assert.Equal(2, service.BatchItems.Count); } [Fact] public void AddRange_WhenInvoked_InvokesBatchFilledEvent() { // Arrange var batchItem1 = default(SpriteBatchItem); batchItem1.TextureId = 10; var batchItem2 = default(SpriteBatchItem); batchItem2.TextureId = 10; var service = new TextureBatchService(); service.BatchSize = 1; // Act & Assert Assert.Raises<EventArgs>(e => { service.BatchFilled += e; }, e => { service.BatchFilled -= e; }, () => { service.AddRange(new[] { batchItem1, batchItem2 }); }); Assert.Equal(2, service.BatchItems.Count); } [Fact] public void EmptyBatch_WhenInvoked_EmptiesAllItemsReadyToRender() { // Arrange var batchItem1 = default(SpriteBatchItem); batchItem1.TextureId = 10; var batchItem2 = default(SpriteBatchItem); batchItem2.TextureId = 10; var service = new TextureBatchService(); service.BatchSize = 2; service.AddRange(new[] { batchItem1, batchItem2 }); // Act service.EmptyBatch(); // Assert Assert.NotEqual(batchItem1, service.BatchItems[0].item); } [Fact] public void EmptyBatch_WithNoItemsReadyToRender_DoesNotEmptyItems() { // Arrange var batchItem1 = default(SpriteBatchItem); batchItem1.TextureId = 10; var batchItem2 = default(SpriteBatchItem); batchItem2.TextureId = 10; var service = new TextureBatchService(); service.BatchSize = 2; service.BatchItems = new List<(bool, SpriteBatchItem)> { (false, batchItem1), (false, batchItem2) }.ToReadOnlyDictionary(); // Act service.EmptyBatch(); // Assert Assert.Equal(batchItem1, service.BatchItems[0].item); Assert.Equal(batchItem2, service.BatchItems[1].item); } #endregion } }
31.318841
135
0.530002
[ "MIT" ]
KinsonDigital/Velaptor
Testing/VelaptorTests/Services/TextureBatchServiceTests.cs
6,485
C#
using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; namespace XamarinFingerPrint.iOS { public class Application { // This is the main entry point of the application. static void Main(string[] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. UIApplication.Main(args, null, "AppDelegate"); } } }
23.333333
91
0.638776
[ "MIT" ]
Tmaturano/XamarinFingerPrint
XamarinFingerPrint.iOS/Main.cs
492
C#
using Newtonsoft.Json; using System; using System.Net; using System.Net.Http; using System.Net.Http.Formatting; using System.Web.Http; //using WebAPI.Models; namespace WebAPI.Controllers { public class TokenController : ApiController { // GET api/Token [HttpGet] public Guid Get() { return new Guid("f025758f-5f7c-445d-90fb-52bc44fc36f9"); } // GET api/Token //public HttpResponseMessage Get(int id) //{ // try // { // Guid guidToken = new Guid("f025758f-5f7c-445d-90fb-52bc44fc36f9"); // KnockKnock model = new KnockKnock(); // model.ApplicantId = guidToken; // var jsonToken = JsonConvert.SerializeObject(model); // IContentNegotiator negotiator = this.Configuration.Services.GetContentNegotiator(); // ContentNegotiationResult result = negotiator.Negotiate(typeof(KnockKnock), this.Request, this.Configuration.Formatters); // if (result == null) // { // var response = new HttpResponseMessage(HttpStatusCode.NotAcceptable); // throw new HttpResponseException(response); // } // return new HttpResponseMessage() // { // Content = new ObjectContent<KnockKnock>( // model, // type of object to be serialized // result.Formatter, // The media formatter // result.MediaType.MediaType // The MIME type // ) // }; // } // catch (Exception) // { // return new HttpResponseMessage(HttpStatusCode.InternalServerError); // } //} } }
32.754386
138
0.524906
[ "MIT" ]
biscuolai/WebAPI
WebAPI/Controllers/TokenController.cs
1,869
C#
// This source code is dual-licensed under the Apache License, version // 2.0, and the Mozilla Public License, version 2.0. // // The APL v2.0: // //--------------------------------------------------------------------------- // Copyright (c) 2007-2020 VMware, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //--------------------------------------------------------------------------- // // The MPL v2.0: // //--------------------------------------------------------------------------- // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. // // Copyright (c) 2007-2020 VMware, Inc. All rights reserved. //--------------------------------------------------------------------------- using System; using System.Collections.Generic; using RabbitMQ.Client.client.framing; using RabbitMQ.Client.Impl; namespace RabbitMQ.Client.Framing.Impl { internal sealed class ExchangeUnbind : MethodBase { // deprecated // ushort _reserved1 public string _destination; public string _source; public string _routingKey; public bool _nowait; public IDictionary<string, object> _arguments; public ExchangeUnbind() { } public ExchangeUnbind(string Destination, string Source, string RoutingKey, bool Nowait, IDictionary<string, object> Arguments) { _destination = Destination; _source = Source; _routingKey = RoutingKey; _nowait = Nowait; _arguments = Arguments; } public ExchangeUnbind(ReadOnlySpan<byte> span) { int offset = 2; offset += WireFormatting.ReadShortstr(span.Slice(offset), out _destination); offset += WireFormatting.ReadShortstr(span.Slice(offset), out _source); offset += WireFormatting.ReadShortstr(span.Slice(offset), out _routingKey); offset += WireFormatting.ReadBits(span.Slice(offset), out _nowait); WireFormatting.ReadDictionary(span.Slice(offset), out var tmpDictionary); _arguments = tmpDictionary; } public override ProtocolCommandId ProtocolCommandId => ProtocolCommandId.ExchangeUnbind; public override string ProtocolMethodName => "exchange.unbind"; public override int WriteArgumentsTo(Span<byte> span) { int offset = WireFormatting.WriteShort(ref span.GetStart(), default); offset += WireFormatting.WriteShortstr(ref span.GetOffset(offset), _destination); offset += WireFormatting.WriteShortstr(ref span.GetOffset(offset), _source); offset += WireFormatting.WriteShortstr(ref span.GetOffset(offset), _routingKey); offset += WireFormatting.WriteBits(ref span.GetOffset(offset), _nowait); return offset + WireFormatting.WriteTable(ref span.GetOffset(offset), _arguments); } public override int GetRequiredBufferSize() { int bufferSize = 2 + 1 + 1 + 1 + 1; // bytes for _reserved1, length of _destination, length of _source, length of _routingKey, bit fields bufferSize += WireFormatting.GetByteCount(_destination); // _destination in bytes bufferSize += WireFormatting.GetByteCount(_source); // _source in bytes bufferSize += WireFormatting.GetByteCount(_routingKey); // _routingKey in bytes bufferSize += WireFormatting.GetTableByteCount(_arguments); // _arguments in bytes return bufferSize; } } }
42.836735
149
0.621963
[ "MPL-2.0-no-copyleft-exception", "MPL-2.0", "Apache-2.0" ]
ArdeshirV/rabbitmq-dotnet-client
projects/RabbitMQ.Client/client/framing/ExchangeUnbind.cs
4,198
C#
/** * Copyright 2015 Canada Health Infoway, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: $LastChangedBy: tmcgrady $ * Last modified: $LastChangedDate: 2011-05-04 15:47:15 -0400 (Wed, 04 May 2011) $ * Revision: $LastChangedRevision: 2623 $ */ /* This class was auto-generated by the message builder generator tools. */ namespace Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_03.Immunization.Merged { using Ca.Infoway.Messagebuilder.Annotation; using Ca.Infoway.Messagebuilder.Datatype; using Ca.Infoway.Messagebuilder.Datatype.Impl; using Ca.Infoway.Messagebuilder.Model; using Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_03.Domainvalue; using System; /** * <summary>POIZ_MT030060CA.ImmunizationReason: (no business * name)</summary> * * <p>Needed for explicitly communicating the reason why a * patient was administered as vaccine.</p> <p>The reason why * an immunization event occurred.</p> */ [Hl7PartTypeMappingAttribute(new string[] {"POIZ_MT030050CA.ImmunizationReason","POIZ_MT030060CA.ImmunizationReason","POIZ_MT060150CA.ImmunizationReason"})] public class ImmunizationReason : MessagePartBean, Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_03.Immunization.Merged.IChoice { private ST text; private CV reasonCode; public ImmunizationReason() { this.text = new STImpl(); this.reasonCode = new CVImpl(); } /** * <summary>Business Name: ImmunizationReasonText</summary> * * <remarks>Un-merged Business Name: ImmunizationReasonText * Relationship: POIZ_MT030050CA.ImmunizationReason.text * Conformance/Cardinality: OPTIONAL (0-1) Un-merged Business * Name: ImmunizationReasonText Relationship: * POIZ_MT030060CA.ImmunizationReason.text * Conformance/Cardinality: OPTIONAL (0-1) <p>Provides * additional context and description relating to the reason * for immunization. Not all implementations will support text. * As a result, this attribute is optional.</p> <p>A textual or * multimedia description (or reference to a description) of * the reason.</p> Un-merged Business Name: * ImmunizationReasonText Relationship: * POIZ_MT060150CA.ImmunizationReason.text * Conformance/Cardinality: OPTIONAL (0-1)</remarks> */ [Hl7XmlMappingAttribute(new string[] {"text"})] public String Text { get { return this.text.Value; } set { this.text.Value = value; } } /** * <summary>Business Name: ImmunizationReason</summary> * * <remarks>Un-merged Business Name: ImmunizationReason * Relationship: POIZ_MT030050CA.ImmunizationReason.reasonCode * Conformance/Cardinality: MANDATORY (1) Un-merged Business * Name: ImmunizationReason Relationship: * POIZ_MT030060CA.ImmunizationReason.reasonCode * Conformance/Cardinality: MANDATORY (1) <p>Allows sorting and * categorizing different kinds of immunization reasons. * Ensures that reasons are gathered in a consistent analyzable * manner. As a result, this attribute is mandatory.</p> <p>A * coded value denoting a reason for immunizing a patient.</p> * Un-merged Business Name: ImmunizationReason Relationship: * POIZ_MT060150CA.ImmunizationReason.reasonCode * Conformance/Cardinality: MANDATORY (1)</remarks> */ [Hl7XmlMappingAttribute(new string[] {"reasonCode"})] public ActImmunizationReason ReasonCode { get { return (ActImmunizationReason) this.reasonCode.Value; } set { this.reasonCode.Value = value; } } } }
46.28866
161
0.663252
[ "ECL-2.0", "Apache-2.0" ]
CanadaHealthInfoway/message-builder-dotnet
message-builder-release-r02_04_03/Main/Ca/Infoway/Messagebuilder/Model/Pcs_mr2009_r02_04_03/Immunization/Merged/ImmunizationReason.cs
4,490
C#
using Contoso.Utils; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reflection; using System.Text; namespace Contoso.Domain { internal static class Helpers { } }
16.466667
37
0.765182
[ "MIT" ]
BlaiseD/Contoso
.NetCore/ContosoUniversity/CreateDomainConsole/Helpers.cs
249
C#
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace IoTSharp.Migrations { public partial class modyfyflowoperation : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_FlowOperations_BaseEvents_BaseEventEventId", table: "FlowOperations"); migrationBuilder.DropForeignKey( name: "FK_FlowOperations_FlowRules_FlowRuleRuleId", table: "FlowOperations"); migrationBuilder.DropForeignKey( name: "FK_FlowOperations_Flows_FlowId", table: "FlowOperations"); migrationBuilder.DropIndex( name: "IX_FlowOperations_BaseEventEventId", table: "FlowOperations"); migrationBuilder.DropIndex( name: "IX_FlowOperations_FlowRuleRuleId", table: "FlowOperations"); migrationBuilder.DropColumn( name: "BaseEventEventId", table: "FlowOperations"); migrationBuilder.DropColumn( name: "FlowRuleRuleId", table: "FlowOperations"); migrationBuilder.AlterColumn<Guid>( name: "FlowId", table: "FlowOperations", type: "uuid", nullable: false, defaultValue: new Guid("00000000-0000-0000-0000-000000000000"), oldClrType: typeof(Guid), oldType: "uuid", oldNullable: true); migrationBuilder.AddColumn<Guid>( name: "BaseEventId", table: "FlowOperations", type: "uuid", nullable: false, defaultValue: new Guid("00000000-0000-0000-0000-000000000000")); migrationBuilder.AddColumn<Guid>( name: "FlowRuleId", table: "FlowOperations", type: "uuid", nullable: false, defaultValue: new Guid("00000000-0000-0000-0000-000000000000")); migrationBuilder.CreateIndex( name: "IX_FlowOperations_BaseEventId", table: "FlowOperations", column: "BaseEventId"); migrationBuilder.CreateIndex( name: "IX_FlowOperations_FlowRuleId", table: "FlowOperations", column: "FlowRuleId"); migrationBuilder.AddForeignKey( name: "FK_FlowOperations_BaseEvents_BaseEventId", table: "FlowOperations", column: "BaseEventId", principalTable: "BaseEvents", principalColumn: "EventId", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_FlowOperations_FlowRules_FlowRuleId", table: "FlowOperations", column: "FlowRuleId", principalTable: "FlowRules", principalColumn: "RuleId", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_FlowOperations_Flows_FlowId", table: "FlowOperations", column: "FlowId", principalTable: "Flows", principalColumn: "FlowId", onDelete: ReferentialAction.Cascade); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_FlowOperations_BaseEvents_BaseEventId", table: "FlowOperations"); migrationBuilder.DropForeignKey( name: "FK_FlowOperations_FlowRules_FlowRuleId", table: "FlowOperations"); migrationBuilder.DropForeignKey( name: "FK_FlowOperations_Flows_FlowId", table: "FlowOperations"); migrationBuilder.DropIndex( name: "IX_FlowOperations_BaseEventId", table: "FlowOperations"); migrationBuilder.DropIndex( name: "IX_FlowOperations_FlowRuleId", table: "FlowOperations"); migrationBuilder.DropColumn( name: "BaseEventId", table: "FlowOperations"); migrationBuilder.DropColumn( name: "FlowRuleId", table: "FlowOperations"); migrationBuilder.AlterColumn<Guid>( name: "FlowId", table: "FlowOperations", type: "uuid", nullable: true, oldClrType: typeof(Guid), oldType: "uuid"); migrationBuilder.AddColumn<Guid>( name: "BaseEventEventId", table: "FlowOperations", type: "uuid", nullable: true); migrationBuilder.AddColumn<Guid>( name: "FlowRuleRuleId", table: "FlowOperations", type: "uuid", nullable: true); migrationBuilder.CreateIndex( name: "IX_FlowOperations_BaseEventEventId", table: "FlowOperations", column: "BaseEventEventId"); migrationBuilder.CreateIndex( name: "IX_FlowOperations_FlowRuleRuleId", table: "FlowOperations", column: "FlowRuleRuleId"); migrationBuilder.AddForeignKey( name: "FK_FlowOperations_BaseEvents_BaseEventEventId", table: "FlowOperations", column: "BaseEventEventId", principalTable: "BaseEvents", principalColumn: "EventId", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_FlowOperations_FlowRules_FlowRuleRuleId", table: "FlowOperations", column: "FlowRuleRuleId", principalTable: "FlowRules", principalColumn: "RuleId", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_FlowOperations_Flows_FlowId", table: "FlowOperations", column: "FlowId", principalTable: "Flows", principalColumn: "FlowId", onDelete: ReferentialAction.Restrict); } } }
35.918033
80
0.54237
[ "MIT" ]
NanoFabricFX/IoTSharp
IoTSharp.Data.PostgreSQL/Migrations/20211217110202_modyfyflowoperation.cs
6,575
C#
using System; using System.Linq; using NUnit.Framework; using Rhino.Mocks; using StoryTeller.Engine; using StoryTeller.Engine.Constraints; using StoryTeller.Model; namespace StoryTeller.Testing.Engine { [TestFixture] public class FixtureTester { #region Setup/Teardown [SetUp] public void SetUp() { } #endregion [Test] public void add_a_named_grammar() { var fixture = new Fixture(); var grammar = MockRepository.GenerateMock<IGrammar>(); fixture["theGrammar"] = grammar; fixture["theGrammar"].ShouldBeTheSameAs(grammar); } [Test] public void adding_a_composite_grammar_programmatically() { var fixture = new Fixture(); fixture["theGrammar"] = Fixture.Paragraph("The Grammar", x => { }); fixture["theGrammar"] .ShouldBeOfType<ParagraphGrammar>().Title().ShouldEqual("The Grammar"); } [Test] public void has_a_constraint_model() { new Fixture().Policies.ShouldBeOfType<Policies>(); } [Test] public void loading_a_fixture_that_is_marked_as_Hidden_sets_the_constraint_to_private() { new HiddenFixture().Policies.IsPrivate.ShouldBeTrue(); } [Test] public void loading_a_fixture_that_is_not_marked_as_hidden_should_not_be_private() { new NotHiddenFixture().Policies.IsPrivate.ShouldBeFalse(); } } // SAMPLE: HiddenFixture [Hidden] public class HiddenFixture : Fixture { } // END: HiddenFixture public class NotHiddenFixture : Fixture { } [TestFixture] public class when_creating_a_grammar_marked_as_a_table_grammar { #region Setup/Teardown [SetUp] public void SetUp() { var fixture = new TableGrammarFixture(); grammar = fixture["DoSomething"]; } #endregion private IGrammar grammar; [Test] public void inner_grammar_should_be_created_to_match_the_method() { var inner = grammar.ShouldBeOfType<TableGrammar>().InnerGrammar.ShouldBeOfType<ValueCheckMethod>(); inner.GetCells().Count.ShouldEqual(3); } [Test] public void should_be_a_table_grammar() { grammar.ShouldBeOfType<TableGrammar>(); } [Test] public void should_use_the_label_from_the_attribute() { grammar.ShouldBeOfType<TableGrammar>().LabelName.ShouldEqual("Check some examples"); } [Test] public void step_name_should_be_Rows_by_default() { grammar.ShouldBeOfType<TableGrammar>().LeafName().ShouldEqual("DoSomething"); } } public class TableGrammarFixture : Fixture { [ExposeAsTable("Check some examples", "DoSomething")] public string DoSomething(string Name, int Age) { return string.Format("{0} is {1} years old", Name, Age); } } [TestFixture] public class when_reading_grammars_from_a_fixture { #region Setup/Teardown [SetUp] public void SetUp() { fixture = new FixtureWithSetUpTearDownAndDescription(); } #endregion private FixtureWithSetUpTearDownAndDescription fixture; [Test] public void do_not_create_grammar_for_setup() { fixture.HasGrammar("SetUp").ShouldBeFalse(); } [Test] public void do_not_create_grammar_for_teardown() { fixture.HasGrammar("TearDown").ShouldBeFalse(); } [Test] public void should_only_have_the_single_explicitly_defined_Grammar() { fixture.GrammarCount.ShouldEqual(1); } } // SAMPLE: FixtureWithSetUpTearDownAndDescription public class FixtureWithSetUpTearDownAndDescription : Fixture { public override string Description { get { return "something"; } } public override void SetUp(ITestContext context) { // do something before the Section using this Fixture } public override void TearDown() { // do something after the Section using this Fixture } public void Go() { } } // END: FixtureWithSetUpTearDownAndDescription [TestFixture] public class when_reading_a_fixture_that_has_errors_while_scanning_for_grammars { #region Setup/Teardown [SetUp] public void SetUp() { fixture = new BadGrammarFixture(); error = fixture.Errors.First(); } #endregion private BadGrammarFixture fixture; private GrammarError error; [Test] public void has_a_grammar_message() { error.Message.ShouldEqual("Could not create Grammar 'Bad' of Fixture 'BadGrammar'"); } [Test] public void has_the_grammar_error_text_from_the_exception() { error.ErrorText.ShouldContain("NotImplementedException"); } } [TestFixture] public class when_reading_grammars_for_the_Hidden_attribute { #region Setup/Teardown [SetUp] public void SetUp() { fixture = new HiddenGrammarsFixture(); } #endregion private HiddenGrammarsFixture fixture; [Test] public void grammars_decorated_with_hidden_should_be_hidden() { fixture.Policies.IsHidden("Hidden1").ShouldBeTrue(); fixture.Policies.IsHidden("Hidden2").ShouldBeTrue(); } [Test] public void grammars_not_decorated_with_hidden_should_not_be_hidden() { fixture.Policies.IsHidden("NotHidden1").ShouldBeFalse(); fixture.Policies.IsHidden("NotHidden2").ShouldBeFalse(); } } public class HiddenGrammarsFixture : Fixture { [Hidden] public void Hidden1() { } public void NotHidden1() { } [Hidden] public IGrammar Hidden2() { return Paragraph("something", x => { }); } public IGrammar NotHidden2() { return Paragraph("something", x => { }); } } public class BadGrammarFixture : Fixture { public IGrammar Bad() { throw new NotImplementedException(); } } }
25.444853
112
0.566537
[ "Apache-2.0" ]
DarthFubuMVC/storyteller
src/StoryTeller.Testing/Engine/FixtureTester.cs
6,921
C#
// ---------------------------------------------------------------------------------- // Microsoft Developer & Platform Evangelism // // Copyright (c) Microsoft Corporation. All rights reserved. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. // ---------------------------------------------------------------------------------- // The example companies, organizations, products, domain names, // e-mail addresses, logos, people, places, and events depicted // herein are fictitious. No association with any real company, // organization, product, domain name, email address, logo, person, // places, or events is intended or should be inferred. // ---------------------------------------------------------------------------------- using System; using System.Windows; using System.Windows.Controls; using System.Windows.Navigation; namespace WindowsPhoneRecipes { public partial class CategoryPage { public string Category { get; set; } public CategoryPage() { InitializeComponent(); WindowsPhoneRecipes.Logger.Instance.AddLine(); } private void btnNext_Click(object sender, RoutedEventArgs e) { // Navigate to the new page NavigationService.Navigate(new Uri("/ItemPage.xaml?cat=" + Category + "&item=" + (sender as Button).Name.Substring(7), UriKind.Relative)); } private void btnMenu_Click(object sender, RoutedEventArgs e) { NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative)); } private void btnCategoryList_Click(object sender, RoutedEventArgs e) { NavigationService.Navigate(new Uri("/CategoriesListingPage.xaml", UriKind.Relative)); } // When page is navigated to, set data context protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); WindowsPhoneRecipes.Logger.Instance.AddLine(); Category = this.NavigationContext.QueryString["cat"]; if (DataContext == null) this.DataContext = this; //simulate a big load that you want to avoid during recursive back navigation if (NonLinearNavigationService.Instance.IsRecursiveBackNavigation == true) { WindowsPhoneRecipes.Logger.Instance.AddLine("IsRecursiveBackNavigation = true"); return; } //else /* * DO WORK HERE - like animation, data biding, and so on... */ this.ApplicationBar.IsVisible = true; //simulate large UI blocking work - that should be avoided all togerher //System.Threading.Thread.Sleep(5000); } // FOR DEBUGGING ONLY! //static int x = 0; protected override void OnNavigatedFrom(NavigationEventArgs e) { base.OnNavigatedFrom(e); WindowsPhoneRecipes.Logger.Instance.AddLine(); // on navigating away from the page, hide the appbar so we dont see it if we are recursive back this.ApplicationBar.IsVisible = false; // FOR DEBUGGING only! Simualte user canceling nav event during recursive back //if (x == 0) //{ // x++; //} //else //{ // //for debuging user canceling navigation // // e.Cancel = true; //} } protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e) { base.OnBackKeyPress(e); // due to a bug, BackKey doesnt route navigation events so we handle it if (NavigationService.CanGoBack) { e.Cancel = true; NavigationService.GoBack(); } } } }
34.241379
150
0.585599
[ "MIT" ]
SimonDarksideJ/XNAGameStudio
Samples/NonLinear-WP-SLApp-Navigation-Service/NonLinearNavigationService/WindowsPhoneNonLinearNavigationServiceSample/CategoryPage.xaml.cs
3,974
C#
using System; using System.Collections.Generic; using System.Text; namespace sbid._M { // 命题逻辑关系(合取/析取/非/蕴含) public enum LogicRelation { CONJ, DISJ, NEG, IMPL } }
14.538462
33
0.640212
[ "MIT" ]
LauZyHou/sbid-ava
sbid/_M/CTL/LogicRelation.cs
217
C#
/* * Copyright (c) 2015, Firely (info@fire.ly) and contributors * See the file CONTRIBUTORS for details. * * This file is licensed under the BSD 3-Clause license * available at https://raw.githubusercontent.com/FirelyTeam/firely-net-sdk/master/LICENSE */ using Hl7.Fhir.Language; using Hl7.FhirPath.Expressions; using Hl7.FhirPath.Parser; using Hl7.FhirPath.Sprache; using Microsoft.VisualStudio.TestTools.UnitTesting; using P = Hl7.Fhir.ElementModel.Types; namespace Hl7.FhirPath.Tests { [TestClass] public class FhirPathExpressionTest { [TestMethod] public void FhirPath_Gramm_Literal() { var parser = Grammar.Literal.End(); AssertParser.SucceedsMatch(parser, "'hi there'", new ConstantExpression("hi there")); var m = new ConstantExpression(3); AssertParser.SucceedsMatch(parser, "3", m); AssertParser.SucceedsMatch(parser, "3.14", new ConstantExpression(3.14m)); AssertParser.SucceedsMatch(parser, "@2013-12", new ConstantExpression(P.Date.Parse("2013-12"))); AssertParser.SucceedsMatch(parser, "@2013-12T", new ConstantExpression(P.DateTime.Parse("2013-12"))); AssertParser.SucceedsMatch(parser, "@T12:23:34", new ConstantExpression(P.Time.Parse("12:23:34"))); AssertParser.SucceedsMatch(parser, "true", new ConstantExpression(true)); AssertParser.SucceedsMatch(parser, "@2014-12-13T12:00:00+02:00", new ConstantExpression(P.DateTime.Parse("2014-12-13T12:00:00+02:00"))); AssertParser.FailsMatch(parser, "%constant"); AssertParser.FailsMatch(parser, "`quotedstring`"); AssertParser.FailsMatch(parser, "A23identifier"); } [TestMethod] public void FhirPath_Gramm_Invocation() { var parser = Grammar.InvocationExpression.End(); AssertParser.SucceedsMatch(parser, "childname", new ChildExpression(AxisExpression.That, "childname")); // AssertParser.SucceedsMatch(parser, "$this", AxisExpression.This); AssertParser.SucceedsMatch(parser, "doSomething()", new FunctionCallExpression(AxisExpression.That, "doSomething", TypeSpecifier.Any)); AssertParser.SucceedsMatch(parser, "doSomething ( ) ", new FunctionCallExpression(AxisExpression.That, "doSomething", TypeSpecifier.Any)); AssertParser.SucceedsMatch(parser, "doSomething ( 3.14 ) ", new FunctionCallExpression(AxisExpression.That, "doSomething", TypeSpecifier.Any, new ConstantExpression(3.14m))); AssertParser.SucceedsMatch(parser, "doSomething('hi', 3.14, 3, $this, $index, somethingElse(true))", new FunctionCallExpression(AxisExpression.That, "doSomething", TypeSpecifier.Any, new ConstantExpression("hi"), new ConstantExpression(3.14m), new ConstantExpression(3), AxisExpression.This, AxisExpression.Index, new FunctionCallExpression(AxisExpression.That, "somethingElse", TypeSpecifier.Any, new ConstantExpression(true)))); AssertParser.SucceedsMatch(parser, "as(Patient)", new FunctionCallExpression(AxisExpression.That, "as", TypeSpecifier.Any, new ConstantExpression("Patient"))); AssertParser.FailsMatch(parser, "$that"); // AssertParser.FailsMatch(parser, "as(Patient.identifier)"); AssertParser.FailsMatch(parser, "as('Patient')"); AssertParser.FailsMatch(parser, "doSomething("); } [TestMethod] public void FhirPath_Gramm_Term() { var parser = Grammar.Term.End(); AssertParser.SucceedsMatch(parser, "childname", new ChildExpression(AxisExpression.This, "childname")); AssertParser.SucceedsMatch(parser, "$this", AxisExpression.This); AssertParser.SucceedsMatch(parser, "doSomething()", new FunctionCallExpression(AxisExpression.This, "doSomething", TypeSpecifier.Any)); AssertParser.SucceedsMatch(parser, "doSomething('hi', 3.14)", new FunctionCallExpression(AxisExpression.This, "doSomething", TypeSpecifier.Any, new ConstantExpression("hi"), new ConstantExpression(3.14m))); AssertParser.SucceedsMatch(parser, "%external", new VariableRefExpression("external")); AssertParser.SucceedsMatch(parser, "@2013-12", new ConstantExpression(P.Date.Parse("2013-12"))); AssertParser.SucceedsMatch(parser, "@2013-12T", new ConstantExpression(P.DateTime.Parse("2013-12"))); AssertParser.SucceedsMatch(parser, "3", new ConstantExpression(3)); AssertParser.SucceedsMatch(parser, "true", new ConstantExpression(true)); AssertParser.SucceedsMatch(parser, "(3)", new ConstantExpression(3)); AssertParser.SucceedsMatch(parser, "{}", NewNodeListInitExpression.Empty); AssertParser.SucceedsMatch(parser, "@2014-12-13T12:00:00+02:00", new ConstantExpression(P.DateTime.Parse("2014-12-13T12:00:00+02:00"))); AssertParser.SucceedsMatch(parser, "78 'kg'", new ConstantExpression(new P.Quantity(78m, "kg"))); AssertParser.SucceedsMatch(parser, "10.1 'mg'", new ConstantExpression(new P.Quantity(10.1m, "mg"))); } [TestMethod] public void FhirPath_Gramm_Term_ExternalRef() { var parser = Grammar.Term.End(); AssertParser.SucceedsMatch(parser, "%`ext-11179-de-is-data-element-concept`", new FunctionCallExpression(AxisExpression.That, "builtin.coreexturl", TypeSpecifier.String, new ConstantExpression("11179-de-is-data-element-concept"))); AssertParser.SucceedsMatch(parser, "%`vs-administrative-gender`", new FunctionCallExpression(AxisExpression.That, "builtin.corevsurl", TypeSpecifier.String, new ConstantExpression("administrative-gender"))); } private static readonly Expression PATIENTNAME = new ChildExpression(new ChildExpression(AxisExpression.This, "Patient"), "name"); [TestMethod] public void FhirPath_Gramm_Quantity() { var parser = Grammar.Quantity.End(); AssertParser.SucceedsMatch(parser, "78 'kg'", new P.Quantity(78m, "kg")); AssertParser.SucceedsMatch(parser, "78.0 'kg'", new P.Quantity(78m, "kg")); AssertParser.SucceedsMatch(parser, "78.0'kg'", new P.Quantity(78m, "kg")); AssertParser.SucceedsMatch(parser, "4 months", P.Quantity.ForCalendarDuration(4m, "month")); AssertParser.SucceedsMatch(parser, "4 'mo'", new P.Quantity(4m, "mo")); AssertParser.SucceedsMatch(parser, "1 '1'", new P.Quantity(1m, P.Quantity.UCUM_UNIT)); AssertParser.FailsMatch(parser, "78"); // still a integer AssertParser.FailsMatch(parser, "78.0"); // still a decimal AssertParser.FailsMatch(parser, "78 kg"); AssertParser.FailsMatch(parser, "four 'kg'"); AssertParser.FailsMatch(parser, "4 decennia"); } [TestMethod] public void FhirPath_Gramm_Expression_Invocation() { var parser = Grammar.InvocationExpression.End(); AssertParser.SucceedsMatch(parser, "Patient.name.doSomething(true)", new FunctionCallExpression(PATIENTNAME, "doSomething", TypeSpecifier.Any, new ConstantExpression(true))); AssertParser.FailsMatch(parser, "Patient."); //AssertParser.FailsMatch(parser, "Patient. name"); //oops //AssertParser.FailsMatch(parser, "Patient . name"); //AssertParser.FailsMatch(parser, "Patient .name"); } [TestMethod] public void FhirPath_Gramm_Expression_Indexer() { var parser = Grammar.InvocationExpression.End(); AssertParser.SucceedsMatch(parser, "Patient.name", PATIENTNAME); AssertParser.SucceedsMatch(parser, "Patient.name [4 ]", new IndexerExpression(PATIENTNAME, new ConstantExpression(4))); AssertParser.SucceedsMatch(parser, "$this[4].name", new ChildExpression( new IndexerExpression(AxisExpression.This, new ConstantExpression(4)), "name")); AssertParser.FailsMatch(parser, "Patient.name["); AssertParser.FailsMatch(parser, "Patient.name]"); AssertParser.FailsMatch(parser, "Patient.name[]"); AssertParser.FailsMatch(parser, "Patient.name[4,]"); AssertParser.FailsMatch(parser, "Patient.name[4,5]"); } [TestMethod] public void FhirPath_Gramm_Expression_Polarity() { var parser = Grammar.PolarityExpression.End(); AssertParser.SucceedsMatch(parser, "4", new ConstantExpression(4)); AssertParser.SucceedsMatch(parser, "-4", new UnaryExpression('-', new ConstantExpression(4))); AssertParser.SucceedsMatch(parser, "-Patient.name", new UnaryExpression('-', PATIENTNAME)); AssertParser.SucceedsMatch(parser, "+Patient.name", new UnaryExpression('+', PATIENTNAME)); } [TestMethod] public void FhirPath_Gramm_Mul() { var parser = Grammar.MulExpression.End(); AssertParser.SucceedsMatch(parser, "Patient.name", PATIENTNAME); AssertParser.SucceedsMatch(parser, "4* Patient.name", new BinaryExpression('*', new ConstantExpression(4), PATIENTNAME)); AssertParser.SucceedsMatch(parser, "5 div 6", constOp("div", 5, 6)); AssertParser.FailsMatch(parser, "4*"); // AssertParser.FailsMatch(parser, "5div6"); oops } [TestMethod] public void FhirPath_Gramm_Add() { var parser = Grammar.AddExpression.End(); AssertParser.SucceedsMatch(parser, "-4", new UnaryExpression('-', new ConstantExpression(4))); AssertParser.SucceedsMatch(parser, "4 + 6", constOp("+", 4, 6)); AssertParser.FailsMatch(parser, "4+"); // AssertParser.FailsMatch(parser, "5div6"); oops } [TestMethod] public void FhirPath_Gramm_Type() { var parser = Grammar.TypeExpression.End(); AssertParser.SucceedsMatch(parser, "4 is integer", new BinaryExpression("is", new ConstantExpression(4), new ConstantExpression("integer"))); AssertParser.SucceedsMatch(parser, "8 as notoddbuteven", new BinaryExpression("as", new ConstantExpression(8), new ConstantExpression("notoddbuteven"))); AssertParser.FailsMatch(parser, "4 is 5"); // AssertParser.FailsMatch(parser, "5div6"); oops } private Expression constOp(string op, object left, object right) { return new BinaryExpression(op, new ConstantExpression(left), new ConstantExpression(right)); } [TestMethod] public void FhirPath_Gramm_InEq() { var parser = Grammar.Expression.End(); AssertParser.SucceedsMatch(parser, "4 < 5 and 5 > 4 or 4 <= 6 xor 6 >= 5", new BinaryExpression("xor", new BinaryExpression("or", new BinaryExpression("and", constOp("<", 4, 5), constOp(">", 5, 4)), constOp("<=", 4, 6)), constOp(">=", 6, 5))); AssertParser.FailsMatch(parser, "<>"); } [TestMethod] public void FhirPath_Gramm_Eq() { var parser = Grammar.Expression.End(); AssertParser.SucceedsMatch(parser, "4=4 implies 4 != 5 and ('h' ~ 'H' or 'a' !~ 'b')", new BinaryExpression("implies", constOp("=", 4, 4), new BinaryExpression("and", constOp("!=", 4, 5), new BinaryExpression("or", constOp("~", 'h', 'H'), constOp("!~", 'a', 'b'))))); AssertParser.FailsMatch(parser, "true implies false and 4 != 5 and 4 <> 6 and ('h' ~ 'H' or 'a' !~ 'b')"); } [TestMethod] public void FhirPath_Expression_Equals() { Expression x = new ConstantExpression("hi there"); Expression y = new VariableRefExpression("hi there"); Assert.IsFalse(x.Equals(y)); Assert.IsFalse(x == y); } } }
48.675781
194
0.628762
[ "BSD-3-Clause" ]
FirelyTeam/fhir-net-common
src/Hl7.FhirPath.Tests/Tests/FhirPathGrammarTest.cs
12,463
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.33440 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace IoTLab.Device { using Gadgeteer; using GTM = Gadgeteer.Modules; public partial class Program : Gadgeteer.Program { /// <summary>The Button module using socket 7 of the mainboard.</summary> private Gadgeteer.Modules.GHIElectronics.Button button; /// <summary>The Ethernet ENC28 module using socket 6 of the mainboard.</summary> private Gadgeteer.Modules.GHIElectronics.EthernetENC28 ethernetENC28; /// <summary>The LED 7C module using socket 5 of the mainboard.</summary> private Gadgeteer.Modules.GHIElectronics.LED7C led7C; /// <summary>The USB Client SP module using socket 8 of the mainboard.</summary> private Gadgeteer.Modules.GHIElectronics.USBClientSP usbClientSP; /// <summary>This property provides access to the Mainboard API. This is normally not necessary for an end user program.</summary> protected new static GHIElectronics.Gadgeteer.FEZCerberus Mainboard { get { return ((GHIElectronics.Gadgeteer.FEZCerberus)(Gadgeteer.Program.Mainboard)); } set { Gadgeteer.Program.Mainboard = value; } } /// <summary>This method runs automatically when the device is powered, and calls ProgramStarted.</summary> public static void Main() { // Important to initialize the Mainboard first Program.Mainboard = new GHIElectronics.Gadgeteer.FEZCerberus(); Program p = new Program(); p.InitializeModules(); p.ProgramStarted(); // Starts Dispatcher p.Run(); } private void InitializeModules() { this.button = new GTM.GHIElectronics.Button(7); this.ethernetENC28 = new GTM.GHIElectronics.EthernetENC28(6); this.led7C = new GTM.GHIElectronics.LED7C(5); this.usbClientSP = new GTM.GHIElectronics.USBClientSP(8); } } }
41.457627
138
0.586263
[ "Apache-2.0" ]
danvy/techdays15iotlab
src/IoTLab/IoTLab.Device/Program.generated.cs
2,446
C#
namespace MovieMood.Services.Mapping { // ReSharper disable once UnusedTypeParameter public interface IMapTo<T> { } }
16.875
49
0.696296
[ "MIT" ]
Drumev00/MovieMood
MovieMood/Services/MovieMood.Services.Mapping/IMapTo.cs
137
C#
using CadEditor; using System; //css_include shared_settings/BlockUtils.cs; public class Data { public OffsetRec getScreensOffset() { return new OffsetRec(0xa770, 1 , 16*75, 16, 75); } public bool isBigBlockEditorEnabled() { return false; } public bool isBlockEditorEnabled() { return true; } public bool isEnemyEditorEnabled() { return false; } public GetVideoPageAddrFunc getVideoPageAddrFunc() { return getVideoAddress; } public GetVideoChunkFunc getVideoChunkFunc() { return getVideoChunk; } public SetVideoChunkFunc setVideoChunkFunc() { return null; } public bool isBuildScreenFromSmallBlocks() { return true; } public OffsetRec getBlocksOffset() { return new OffsetRec(0xafd3, 1 , 0x1000); } public int getBlocksCount() { return 131; } public int getBigBlocksCount() { return 131; } public int getPalBytesAddr() { return 0xb23f; } public GetBlocksFunc getBlocksFunc() { return BlockUtils.getBlocksLinear2x2Masked;} public SetBlocksFunc setBlocksFunc() { return BlockUtils.setBlocksLinear2x2Masked;} public GetPalFunc getPalFunc() { return getPallete;} public SetPalFunc setPalFunc() { return null;} //---------------------------------------------------------------------------- public byte[] getPallete(int palId) { return Utils.readBinFile("pal7.bin"); } public int getVideoAddress(int id) { return -1; } public byte[] getVideoChunk(int videoPageId) { return Utils.readVideoBankFromFile("chr7.bin", videoPageId); } }
37.744186
93
0.651263
[ "MIT" ]
spiiin/CadEditor
CadEditor/settings_nes/whomp_em/Settings_WhompEm-7-4.cs
1,623
C#
using System.Windows.Input; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Web; using MudBlazor.Utilities; namespace MudBlazor { public partial class MudListItem : MudComponentBase { protected string Classname => new CssBuilder("mud-list-item") .AddClass("mud-list-item-dense", Dense || MudList?.Dense==true) .AddClass("mud-list-item-gutters", !DisableGutters && !(MudList?.DisableGutters==true)) .AddClass("mud-list-item-clickable", MudList?.Clickable) .AddClass($"mud-ripple", MudList?.Clickable==true && !DisableRipple) .AddClass(Class) .Build(); [Parameter] public string Text { get; set; } /// <summary> /// Avatar to use if set. /// </summary> [Parameter] public string Avatar { get; set; } /// <summary> /// Link to a URL when clicked. /// </summary> [Parameter] public string Href { get; set; } /// <summary> /// Avatar CSS Class to applie if Avtar is set. /// </summary> [Parameter] public string AvatarClass { get; set; } /// <summary> /// If true, disables ripple effect. /// </summary> [Parameter] public bool DisableRipple { get; set; } /// <summary> /// Icon to use if set. /// </summary> [Parameter] public string Icon { get; set; } /// <summary> /// If true, the List Subheader will be indented. /// </summary> [Parameter] public bool Inset { get; set; } /// <summary> /// If true, compact vertical padding will be used. /// </summary> [Parameter] public bool Dense { get; set; } /// <summary> /// If true, the left and right padding is removed. /// </summary> [Parameter] public bool DisableGutters { get; set; } /// <summary> /// If Nested list and If Expanded true expands the nested list, otherwise collapse it. /// </summary> [Parameter] public bool Expanded { get; set; } /// <summary> /// Command parameter. /// </summary> [Parameter] public object CommandParameter { get; set; } /// <summary> /// Command executed when the user clicks on an element. /// </summary> [Parameter] public ICommand Command { get; set; } [Inject] public Microsoft.AspNetCore.Components.NavigationManager UriHelper { get; set; } [CascadingParameter] MudList MudList { get; set; } [Parameter] public RenderFragment ChildContent { get; set; } [Parameter] public RenderFragment NestedList { get; set; } /// <summary> /// List click event. /// </summary> [Parameter] public EventCallback<MouseEventArgs> OnClick { get; set; } protected void OnClickHandler(MouseEventArgs ev) { if (NestedList != null) { Expanded = !Expanded; } else if (Href != null) { UriHelper.NavigateTo(Href); } else { OnClick.InvokeAsync(ev); if (Command?.CanExecute(CommandParameter) ?? false) { Command.Execute(CommandParameter); } } } public Typo textTypo { get; set; } protected override void OnParametersSet() { if(Dense || MudList?.Dense==true) { textTypo = Typo.body2; } else if(!Dense || !MudList?.Dense==true) { textTypo = Typo.body1; } } } }
31.433333
97
0.530753
[ "MIT" ]
Codinkat/MudBlazor
src/MudBlazor/Components/List/MudListItem.razor.cs
3,774
C#
namespace Kesco.Lib.Win.Document.Classes { /// <summary> /// Изменение угла поворота /// </summary> internal struct RotateTransition { /// <summary> /// Было /// </summary> internal int From { get; set; } /// <summary> /// Стало /// </summary> internal int To { get; set; } /// <summary> /// Флаг. Угол изменился /// </summary> internal bool Changed { get { return From != To; } } } }
19.233333
41
0.419411
[ "MIT" ]
Kesco-m/Kesco.Lib.Win.Document
Classes/RotateTransition.cs
626
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Management.Automation; using System.Management.Automation.Host; using System.Management.Automation.Internal; using System.Management.Automation.Runspaces; using Dbg = System.Management.Automation.Diagnostics; namespace Microsoft.PowerShell.Commands { /// <summary> /// Contains information about a single history entry. /// </summary> public class HistoryInfo { /// <summary> /// Constructor. /// </summary> /// <param name="pipelineId">Id of pipeline in which command associated /// with this history entry is executed</param> /// <param name="cmdline">Command string.</param> /// <param name="status">Status of pipeline execution.</param> /// <param name="startTime">StartTime of execution.</param> /// <param name="endTime">EndTime of execution.</param> internal HistoryInfo(long pipelineId, string cmdline, PipelineState status, DateTime startTime, DateTime endTime) { Dbg.Assert(cmdline != null, "caller should validate the parameter"); _pipelineId = pipelineId; CommandLine = cmdline; ExecutionStatus = status; StartExecutionTime = startTime; EndExecutionTime = endTime; Cleared = false; } /// <summary> /// Copy constructor to support cloning. /// </summary> /// <param name="history"></param> private HistoryInfo(HistoryInfo history) { Id = history.Id; _pipelineId = history._pipelineId; CommandLine = history.CommandLine; ExecutionStatus = history.ExecutionStatus; StartExecutionTime = history.StartExecutionTime; EndExecutionTime = history.EndExecutionTime; Cleared = history.Cleared; } /// <summary> /// Id of this history entry. /// </summary> /// <value></value> public long Id { get; private set; } /// <summary> /// CommandLine string. /// </summary> /// <value></value> public string CommandLine { get; private set; } /// <summary> /// Execution status of associated pipeline. /// </summary> /// <value></value> public PipelineState ExecutionStatus { get; private set; } /// <summary> /// Start time of execution of associated pipeline. /// </summary> /// <value></value> public DateTime StartExecutionTime { get; } /// <summary> /// End time of execution of associated pipeline. /// </summary> /// <value></value> public DateTime EndExecutionTime { get; private set; } /// <summary> /// The time it took to execute the associeated pipeline. /// </summary> public TimeSpan Duration => EndExecutionTime - StartExecutionTime; /// <summary> /// Override for ToString() method. /// </summary> /// <returns></returns> public override string ToString() { if (string.IsNullOrEmpty(CommandLine)) { return base.ToString(); } else { return CommandLine; } } /// <summary> /// Cleared status of an entry. /// </summary> internal bool Cleared { get; set; } = false; /// <summary> /// Sets Id. /// </summary> /// <param name="id"></param> internal void SetId(long id) => Id = id; /// <summary> /// Set status. /// </summary> /// <param name="status"></param> internal void SetStatus(PipelineState status) => ExecutionStatus = status; /// <summary> /// Set endtime. /// </summary> /// <param name="endTime"></param> internal void SetEndTime(DateTime endTime) => EndExecutionTime = endTime; /// <summary> /// Sets command. /// </summary> /// <param name="command"></param> internal void SetCommand(string command) => CommandLine = command; /// <summary> /// Id of the pipeline corresponding to this history entry. /// </summary> private readonly long _pipelineId; /// <summary> /// Returns a clone of this object. /// </summary> /// <returns></returns> public HistoryInfo Clone() { return new HistoryInfo(this); } } /// <summary> /// This class implements history and provides APIs for adding and fetching /// entries from history. /// </summary> internal class History { /// <summary> /// Default history size. /// </summary> internal const int DefaultHistorySize = 4096; #region constructors /// <summary> /// Constructs history store. /// </summary> internal History(ExecutionContext context) { // Create history size variable. Add ValidateRangeAttribute to // validate the range. Collection<Attribute> attrs = new Collection<Attribute>(); attrs.Add(new ValidateRangeAttribute(1, (int)Int16.MaxValue)); PSVariable historySizeVar = new PSVariable(SpecialVariables.HistorySize, DefaultHistorySize, ScopedItemOptions.None, attrs); historySizeVar.Description = SessionStateStrings.MaxHistoryCountDescription; context.EngineSessionState.SetVariable(historySizeVar, false, CommandOrigin.Internal); _capacity = DefaultHistorySize; _buffer = new HistoryInfo[_capacity]; } #endregion constructors #region internal /// <summary> /// Create a new history entry. /// </summary> /// <param name="pipelineId"></param> /// <param name="cmdline"></param> /// <param name="status"></param> /// <param name="startTime"></param> /// <param name="endTime"></param> /// <param name="skipIfLocked">If true, the entry will not be added when the history is locked.</param> /// <returns>Id for the new created entry. Use this id to fetch the /// entry. Returns -1 if the entry is not added.</returns> /// <remarks>This function is thread safe</remarks> internal long AddEntry(long pipelineId, string cmdline, PipelineState status, DateTime startTime, DateTime endTime, bool skipIfLocked) { if (!System.Threading.Monitor.TryEnter(_syncRoot, skipIfLocked ? 0 : System.Threading.Timeout.Infinite)) { return -1; } try { ReallocateBufferIfNeeded(); HistoryInfo entry = new HistoryInfo(pipelineId, cmdline, status, startTime, endTime); return Add(entry); } finally { System.Threading.Monitor.Exit(_syncRoot); } } /// <summary> /// Update the history entry corresponding to id. /// </summary> /// <param name="id">Id of history entry to be updated.</param> /// <param name="status">Status to be updated.</param> /// <param name="endTime">EndTime to be updated.</param> /// <param name="skipIfLocked">If true, the entry will not be added when the history is locked.</param> /// <returns></returns> internal void UpdateEntry(long id, PipelineState status, DateTime endTime, bool skipIfLocked) { if (!System.Threading.Monitor.TryEnter(_syncRoot, skipIfLocked ? 0 : System.Threading.Timeout.Infinite)) { return; } try { HistoryInfo entry = CoreGetEntry(id); if (entry != null) { entry.SetStatus(status); entry.SetEndTime(endTime); } } finally { System.Threading.Monitor.Exit(_syncRoot); } } /// <summary> /// Gets entry from buffer for given id. This id should be the /// id returned by Add method. /// </summary> /// <param name="id">Id of the entry to be fetched.</param> /// <returns>Entry corresponding to id if it is present else null /// </returns> internal HistoryInfo GetEntry(long id) { lock (_syncRoot) { ReallocateBufferIfNeeded(); HistoryInfo entry = CoreGetEntry(id); if (entry != null) if (entry.Cleared == false) return entry.Clone(); return null; } } /// <summary> /// Get count HistoryEntries. /// </summary> /// <param name="id"></param> /// <param name="count"></param> /// <param name="newest"></param> /// <returns>History entries.</returns> internal HistoryInfo[] GetEntries(long id, long count, SwitchParameter newest) { ReallocateBufferIfNeeded(); if (count < -1) { throw PSTraceSource.NewArgumentOutOfRangeException(nameof(count), count); } if (newest.ToString() == null) { throw PSTraceSource.NewArgumentNullException(nameof(newest)); } if (count == -1 || count > _countEntriesAdded || count > _countEntriesInBuffer) count = _countEntriesInBuffer; if (count == 0 || _countEntriesInBuffer == 0) { return Array.Empty<HistoryInfo>(); } lock (_syncRoot) { // Using list instead of an array to store the entries.With array we are getting null values // when the historybuffer size is changed List<HistoryInfo> entriesList = new List<HistoryInfo>(); if (id > 0) { long firstId, baseId; baseId = id; // get id,count,newest values if (!newest.IsPresent) { // get older entries // Calculate the first id (i.e lowest id to fetch) firstId = baseId - count + 1; // If first id is less than the lowest id in history store, // assign lowest id as first ID if (firstId < 1) { firstId = 1; } for (long i = baseId; i >= firstId; --i) { if (firstId <= 1) break; // if entry is null , continue the loop with the next entry if (_buffer[GetIndexFromId(i)] == null) continue; if (_buffer[GetIndexFromId(i)].Cleared) { // we have to clear count entries before an id, so if an entry is null,decrement // first id as long as its is greater than the lowest entry in the buffer. firstId--; continue; } } for (long i = firstId; i <= baseId; ++i) { // if an entry is null after being cleared by clear-history cmdlet, // continue with the next entry if (_buffer[GetIndexFromId(i)] == null || _buffer[GetIndexFromId(i)].Cleared) continue; entriesList.Add(_buffer[GetIndexFromId(i)].Clone()); } } else { // get latest entries // first id becomes the id +count no of entries from the end of the buffer firstId = baseId + count - 1; // if first id is more than the no of entries in the buffer, first id will be the last entry in the buffer if (firstId >= _countEntriesAdded) { firstId = _countEntriesAdded; } for (long i = baseId; i <= firstId; i++) { if (firstId >= _countEntriesAdded) break; // if entry is null , continue the loop with the next entry if (_buffer[GetIndexFromId(i)] == null) continue; if (_buffer[GetIndexFromId(i)].Cleared) { // we have to clear count entries before an id, so if an entry is null,increment first id firstId++; continue; } } for (long i = firstId; i >= baseId; --i) { // if an entry is null after being cleared by clear-history cmdlet, // continue with the next entry if (_buffer[GetIndexFromId(i)] == null || _buffer[GetIndexFromId(i)].Cleared) continue; entriesList.Add(_buffer[GetIndexFromId(i)].Clone()); } } } else { // get entries for count,newest long index, SmallestID = 0; // if we change the defaulthistory size and when no of entries exceed the size, then // we need to get the smallest entry in the buffer when we want to clear the oldest entry // eg if size is 5 and then the entries can be 7,6,1,2,3 if (_capacity != DefaultHistorySize) SmallestID = SmallestIDinBuffer(); if (!newest.IsPresent) { // get oldest count entries index = 1; if (_capacity != DefaultHistorySize) { if (_countEntriesAdded > _capacity) index = SmallestID; } for (long i = count - 1; i >= 0;) { if (index > _countEntriesAdded) break; if ((index <= 0 || GetIndexFromId(index) >= _buffer.Length) || (_buffer[GetIndexFromId(index)].Cleared)) { index++; continue; } else { entriesList.Add(_buffer[GetIndexFromId(index)].Clone()); i--; index++; } } } else { index = _countEntriesAdded;//SmallestIDinBuffer for (long i = count - 1; i >= 0;) { // if an entry is cleared continue to the next entry if (_capacity != DefaultHistorySize) { if (_countEntriesAdded > _capacity) { if (index < SmallestID) break; } } if (index < 1) break; if ((index <= 0 || GetIndexFromId(index) >= _buffer.Length) || (_buffer[GetIndexFromId(index)].Cleared)) { index--; continue; } else { // clone the entry from the history buffer entriesList.Add(_buffer[GetIndexFromId(index)].Clone()); i--; index--; } } } } HistoryInfo[] entries = new HistoryInfo[entriesList.Count]; entriesList.CopyTo(entries); return entries; } } /// <summary> /// Get History Entries based on the WildCard Pattern value. /// If passed 0, returns all the values, else return on the basis of count. /// </summary> /// <param name="wildcardpattern"></param> /// <param name="count"></param> /// <param name="newest"></param> /// <returns></returns> internal HistoryInfo[] GetEntries(WildcardPattern wildcardpattern, long count, SwitchParameter newest) { lock (_syncRoot) { if (count < -1) { throw PSTraceSource.NewArgumentOutOfRangeException(nameof(count), count); } if (newest.ToString() == null) { throw PSTraceSource.NewArgumentNullException(nameof(newest)); } if (count > _countEntriesAdded || count == -1) { count = _countEntriesInBuffer; } List<HistoryInfo> cmdlist = new List<HistoryInfo>(); long SmallestID = 1; // if buffersize is changes,Get the smallest entry that's not cleared in the buffer if (_capacity != DefaultHistorySize) SmallestID = SmallestIDinBuffer(); if (count != 0) { if (!newest.IsPresent) { long id = 1; if (_capacity != DefaultHistorySize) { if (_countEntriesAdded > _capacity) id = SmallestID; } for (long i = 0; i <= count - 1;) { if (id > _countEntriesAdded) break; if (_buffer[GetIndexFromId(id)].Cleared == false && wildcardpattern.IsMatch(_buffer[GetIndexFromId(id)].CommandLine.Trim())) { cmdlist.Add(_buffer[GetIndexFromId(id)].Clone()); i++; } id++; } } else { long id = _countEntriesAdded; for (long i = 0; i <= count - 1;) { // if buffersize is changed,we have to loop from max entry to min entry thats not cleared if (_capacity != DefaultHistorySize) { if (_countEntriesAdded > _capacity) { if (id < SmallestID) break; } } if (id < 1) break; if (_buffer[GetIndexFromId(id)].Cleared == false && wildcardpattern.IsMatch(_buffer[GetIndexFromId(id)].CommandLine.Trim())) { cmdlist.Add(_buffer[GetIndexFromId(id)].Clone()); i++; } id--; } } } else { for (long i = 1; i <= _countEntriesAdded; i++) { if (_buffer[GetIndexFromId(i)].Cleared == false && wildcardpattern.IsMatch(_buffer[GetIndexFromId(i)].CommandLine.Trim())) { cmdlist.Add(_buffer[GetIndexFromId(i)].Clone()); } } } HistoryInfo[] entries = new HistoryInfo[cmdlist.Count]; cmdlist.CopyTo(entries); return entries; } } /// <summary> /// Clears the history entry from buffer for a given id. /// </summary> /// <param name="id">Id of the entry to be Cleared.</param> /// <returns>Nothing.</returns> internal void ClearEntry(long id) { lock (_syncRoot) { if (id < 0) { throw PSTraceSource.NewArgumentOutOfRangeException(nameof(id), id); } // no entries are present to clear if (_countEntriesInBuffer == 0) return; // throw an exception if id is out of range if (id > _countEntriesAdded) { return; } HistoryInfo entry = CoreGetEntry(id); if (entry != null) { entry.Cleared = true; _countEntriesInBuffer--; } return; } } ///<summary> /// gets the total number of entries added ///</summary> ///<returns>count of total entries added.</returns> internal int Buffercapacity() { return _capacity; } #endregion internal #region private /// <summary> /// Adds an entry to the buffer. If buffer is full, overwrites /// oldest entry in the buffer. /// </summary> /// <param name="entry"></param> /// <returns>Returns id for the entry. This id should be used to fetch /// the entry from the buffer.</returns> /// <remarks>Id starts from 1 and is incremented by 1 for each new entry</remarks> private long Add(HistoryInfo entry) { if (entry == null) { throw PSTraceSource.NewArgumentNullException(nameof(entry)); } _buffer[GetIndexForNewEntry()] = entry; // Increment count of entries added so far _countEntriesAdded++; // Id of an entry in history is same as its number in history store. entry.SetId(_countEntriesAdded); // Increment count of entries in buffer by 1 IncrementCountOfEntriesInBuffer(); return _countEntriesAdded; } /// <summary> /// Gets entry from buffer for given id. This id should be the /// id returned by Add method. /// </summary> /// <param name="id">Id of the entry to be fetched.</param> /// <returns>Entry corresponding to id if it is present else null /// </returns> private HistoryInfo CoreGetEntry(long id) { if (id <= 0) { throw PSTraceSource.NewArgumentOutOfRangeException(nameof(id), id); } if (_countEntriesInBuffer == 0) return null; if (id > _countEntriesAdded) { return null; } // if (_buffer[GetIndexFromId(id)].Cleared == false ) return _buffer[GetIndexFromId(id)]; // else // return null; } /// <summary> /// Gets the smallest id in the buffer. /// </summary> /// <returns></returns> private long SmallestIDinBuffer() { long minID = 0; if (_buffer == null) return minID; for (int i = 0; i < _buffer.Length; i++) { // assign the first entry in the buffer as min. if (_buffer[i] != null && _buffer[i].Cleared == false) { minID = _buffer[i].Id; break; } } // check for the minimum id that is not cleared for (int i = 0; i < _buffer.Length; i++) { if (_buffer[i] != null && _buffer[i].Cleared == false) if (minID > _buffer[i].Id) minID = _buffer[i].Id; } return minID; } /// <summary> /// Reallocates the buffer if history size changed. /// </summary> private void ReallocateBufferIfNeeded() { // Get current value of histoysize variable int historySize = GetHistorySize(); if (historySize == _capacity) return; HistoryInfo[] tempBuffer = new HistoryInfo[historySize]; // Calculate number of entries to copy in new buffer. int numberOfEntries = _countEntriesInBuffer; // when buffer size is changed,we have to consider the totalnumber of entries added if (numberOfEntries < _countEntriesAdded) numberOfEntries = (int)_countEntriesAdded; if (_countEntriesInBuffer > historySize) numberOfEntries = historySize; for (int i = numberOfEntries; i > 0; --i) { long nextId = _countEntriesAdded - i + 1; tempBuffer[GetIndexFromId(nextId, historySize)] = _buffer[GetIndexFromId(nextId)]; } _countEntriesInBuffer = numberOfEntries; _capacity = historySize; _buffer = tempBuffer; } /// <summary> /// Get the index for new entry. /// </summary> /// <returns>Index for new entry.</returns> private int GetIndexForNewEntry() { return (int)(_countEntriesAdded % _capacity); } /// <summary> /// Gets index in buffer for an entry with given Id. /// </summary> /// <returns></returns> private int GetIndexFromId(long id) { return (int)((id - 1) % _capacity); } /// <summary> /// Gets index in buffer for an entry with given Id using passed in /// capacity. /// </summary> /// <param name="id"></param> /// <param name="capacity"></param> /// <returns></returns> private static int GetIndexFromId(long id, int capacity) { return (int)((id - 1) % capacity); } /// <summary> /// Increment number of entries in buffer by 1. /// </summary> private void IncrementCountOfEntriesInBuffer() { if (_countEntriesInBuffer < _capacity) _countEntriesInBuffer++; } /// <summary> /// Get the current history size. /// </summary> /// <returns></returns> private int GetHistorySize() { int historySize = 0; var executionContext = LocalPipeline.GetExecutionContextFromTLS(); object obj = (executionContext != null) ? executionContext.GetVariableValue(SpecialVariables.HistorySizeVarPath) : null; if (obj != null) { try { historySize = (int)LanguagePrimitives.ConvertTo(obj, typeof(int), System.Globalization.CultureInfo.InvariantCulture); } catch (InvalidCastException) { } } if (historySize <= 0) { historySize = DefaultHistorySize; } return historySize; } /// <summary> /// Buffer. /// </summary> private HistoryInfo[] _buffer; /// <summary> /// Capacity of circular buffer. /// </summary> private int _capacity; /// <summary> /// Number of entries in buffer currently. /// </summary> private int _countEntriesInBuffer; /// <summary> /// Total number of entries added till now including those which have /// been overwritten after buffer got full. This is also number of /// last entry added. /// </summary> private long _countEntriesAdded; /// <summary> /// Private object for synchronization. /// </summary> private readonly object _syncRoot = new object(); #endregion private /// <summary> /// Return the ID of the next history item to be added. /// </summary> internal long GetNextHistoryId() { return _countEntriesAdded + 1; } #region invoke_loop_detection /// <summary> /// This is a set of HistoryInfo ids which are currently being executed in the /// pipelines of the Runspace that is holding this 'History' instance. /// </summary> private readonly HashSet<long> _invokeHistoryIds = new HashSet<long>(); internal bool PresentInInvokeHistoryEntrySet(HistoryInfo entry) { return _invokeHistoryIds.Contains(entry.Id); } internal void AddToInvokeHistoryEntrySet(HistoryInfo entry) { _invokeHistoryIds.Add(entry.Id); } internal void RemoveFromInvokeHistoryEntrySet(HistoryInfo entry) { _invokeHistoryIds.Remove(entry.Id); } #endregion invoke_loop_detection } /// <summary> /// This class Implements the get-history command. /// </summary> [Cmdlet(VerbsCommon.Get, "History", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096788")] [OutputType(typeof(HistoryInfo))] public class GetHistoryCommand : PSCmdlet { /// <summary> /// Ids of entries to display. /// </summary> private long[] _id; /// <summary> /// Ids of entries to display. /// </summary> /// <value></value> [Parameter(Position = 0, ValueFromPipeline = true)] [ValidateRangeAttribute((long)1, long.MaxValue)] public long[] Id { get { return _id; } set { _id = value; } } /// <summary> /// Is Count parameter specified. /// </summary> private bool _countParameterSpecified; /// <summary> /// Count of entries to display. By default, count is the length of the history buffer. /// So "Get-History" returns all history entries. /// </summary> private int _count; /// <summary> /// No of History Entries (starting from last) that are to be displayed. /// </summary> [Parameter(Position = 1)] [ValidateRangeAttribute(0, (int)Int16.MaxValue)] public int Count { get { return _count; } set { _countParameterSpecified = true; _count = value; } } /// <summary> /// Implements the Processing() method for show/History command. /// </summary> protected override void ProcessRecord() { History history = ((LocalRunspace)Context.CurrentRunspace).History; if (_id != null) { if (!_countParameterSpecified) { // If Id parameter is specified and count is not specified, // get history foreach (long id in _id) { Dbg.Assert(id > 0, "ValidateRangeAttribute should not allow this"); HistoryInfo entry = history.GetEntry(id); if (entry != null && entry.Id == id) { WriteObject(entry); } else { Exception ex = new ArgumentException ( StringUtil.Format(HistoryStrings.NoHistoryForId, id) ); WriteError ( new ErrorRecord ( ex, "GetHistoryNoHistoryForId", ErrorCategory.ObjectNotFound, id ) ); } } } else if (_id.Length > 1) { Exception ex = new ArgumentException ( StringUtil.Format(HistoryStrings.NoCountWithMultipleIds) ); ThrowTerminatingError ( new ErrorRecord ( ex, "GetHistoryNoCountWithMultipleIds", ErrorCategory.InvalidArgument, _count ) ); } else { long id = _id[0]; Dbg.Assert(id > 0, "ValidateRangeAttribute should not allow this"); WriteObject(history.GetEntries(id, _count, false), true); } } else { // The default value for _count is the size of the history buffer. if (!_countParameterSpecified) { _count = history.Buffercapacity(); } HistoryInfo[] entries = history.GetEntries(0, _count, true); for (long i = entries.Length - 1; i >= 0; i--) WriteObject(entries[i]); } } } /// <summary> /// This class implements the Invoke-History command. /// </summary> [Cmdlet(VerbsLifecycle.Invoke, "History", SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096586")] public class InvokeHistoryCommand : PSCmdlet { #region Parameters /// <summary> /// Invoke cmd can execute only one history entry. If multiple /// ids are provided, we throw error. /// </summary> private bool _multipleIdProvided; private string _id; /// <summary> /// Accepts a string value indicating a previously executed command to /// re-execute. /// If string can be parsed to long, /// it will be used as HistoryId /// else /// as a string value indicating a previously executed command to /// re-execute. This string is the first n characters of the command /// that is to be re-executed. /// </summary> [Parameter(Position = 0, ValueFromPipelineByPropertyName = true)] public string Id { get { return _id; } set { if (_id != null) { // Id has been set already. _multipleIdProvided = true; } _id = value; } } #endregion /// <summary> /// Implements the BeginProcessing() method for eval/History command. /// </summary> protected override void EndProcessing() { // Invoke-history can execute only one command. If multiple // ids were provided, throw exception if (_multipleIdProvided) { ThrowTerminatingError( new ErrorRecord( new ArgumentException(HistoryStrings.InvokeHistoryMultipleCommandsError), "InvokeHistoryMultipleCommandsError", ErrorCategory.InvalidArgument, targetObject: null)); } var ctxRunspace = (LocalRunspace)Context.CurrentRunspace; History history = ctxRunspace.History; Dbg.Assert(history != null, "History should be non null"); // Get the history entry to invoke HistoryInfo entry = GetHistoryEntryToInvoke(history); string commandToInvoke = entry.CommandLine; if (!ShouldProcess(commandToInvoke)) { return; } // Check if there is a loop in invoke-history if (history.PresentInInvokeHistoryEntrySet(entry)) { ThrowTerminatingError( new ErrorRecord( new InvalidOperationException(HistoryStrings.InvokeHistoryLoopDetected), "InvokeHistoryLoopDetected", ErrorCategory.InvalidOperation, targetObject: null)); } else { history.AddToInvokeHistoryEntrySet(entry); } // Replace Invoke-History with string which is getting invoked ReplaceHistoryString(entry, ctxRunspace); try { // Echo command Host.UI.WriteLine(commandToInvoke); } catch (HostException) { // when the host is not interactive, HostException is thrown // do nothing } // Items invoked as History should act as though they were submitted by the user - so should still come from // the runspace itself. For this reason, it is insufficient to just use the InvokeScript method on the Cmdlet class. using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace)) { ps.AddScript(commandToInvoke); EventHandler<DataAddedEventArgs> debugAdded = (object sender, DataAddedEventArgs e) => { DebugRecord record = (DebugRecord)((PSDataCollection<DebugRecord>)sender)[e.Index]; WriteDebug(record.Message); }; EventHandler<DataAddedEventArgs> errorAdded = (object sender, DataAddedEventArgs e) => { ErrorRecord record = (ErrorRecord)((PSDataCollection<ErrorRecord>)sender)[e.Index]; WriteError(record); }; EventHandler<DataAddedEventArgs> informationAdded = (object sender, DataAddedEventArgs e) => { InformationRecord record = (InformationRecord)((PSDataCollection<InformationRecord>)sender)[e.Index]; WriteInformation(record); }; EventHandler<DataAddedEventArgs> progressAdded = (object sender, DataAddedEventArgs e) => { ProgressRecord record = (ProgressRecord)((PSDataCollection<ProgressRecord>)sender)[e.Index]; WriteProgress(record); }; EventHandler<DataAddedEventArgs> verboseAdded = (object sender, DataAddedEventArgs e) => { VerboseRecord record = (VerboseRecord)((PSDataCollection<VerboseRecord>)sender)[e.Index]; WriteVerbose(record.Message); }; EventHandler<DataAddedEventArgs> warningAdded = (object sender, DataAddedEventArgs e) => { WarningRecord record = (WarningRecord)((PSDataCollection<WarningRecord>)sender)[e.Index]; WriteWarning(record.Message); }; ps.Streams.Debug.DataAdded += debugAdded; ps.Streams.Error.DataAdded += errorAdded; ps.Streams.Information.DataAdded += informationAdded; ps.Streams.Progress.DataAdded += progressAdded; ps.Streams.Verbose.DataAdded += verboseAdded; ps.Streams.Warning.DataAdded += warningAdded; LocalRunspace localRunspace = ps.Runspace as LocalRunspace; try { // Indicate to the system that we are in nested prompt mode, since we are emulating running the command at the prompt. // This ensures that the command being run as nested runs in the correct language mode, because CreatePipelineProcessor() // always forces CommandOrigin to Internal for nested running commands, and Command.CreateCommandProcessor() forces Internal // commands to always run in FullLanguage mode unless in a nested prompt. if (localRunspace != null) { localRunspace.InInternalNestedPrompt = ps.IsNested; } Collection<PSObject> results = ps.Invoke(); if (results.Count > 0) { WriteObject(results, true); } } finally { history.RemoveFromInvokeHistoryEntrySet(entry); if (localRunspace != null) { localRunspace.InInternalNestedPrompt = false; } ps.Streams.Debug.DataAdded -= debugAdded; ps.Streams.Error.DataAdded -= errorAdded; ps.Streams.Information.DataAdded -= informationAdded; ps.Streams.Progress.DataAdded -= progressAdded; ps.Streams.Verbose.DataAdded -= verboseAdded; ps.Streams.Warning.DataAdded -= warningAdded; } } } /// <summary> /// Helper function which gets history entry to invoke. /// </summary> [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly", Justification = "It's ok to use ID in the ArgumentException")] private HistoryInfo GetHistoryEntryToInvoke(History history) { HistoryInfo entry = null; // User didn't specify any input parameter. Invoke the last // entry if (_id == null) { HistoryInfo[] entries = history.GetEntries(0, 1, true); if (entries.Length == 1) { entry = entries[0]; } else { Exception ex = new InvalidOperationException ( StringUtil.Format(HistoryStrings.NoLastHistoryEntryFound) ); ThrowTerminatingError ( new ErrorRecord ( ex, "InvokeHistoryNoLastHistoryEntryFound", ErrorCategory.InvalidOperation, null ) ); } } else { // Parse input PopulateIdAndCommandLine(); // User specified a commandline. Get list of all history entries // and find latest match if (_commandLine != null) { HistoryInfo[] entries = history.GetEntries(0, -1, false); // and search backwards through the entries for (int i = entries.Length - 1; i >= 0; i--) { if (entries[i].CommandLine.StartsWith(_commandLine, StringComparison.Ordinal)) { entry = entries[i]; break; } } if (entry == null) { Exception ex = new ArgumentException ( StringUtil.Format(HistoryStrings.NoHistoryForCommandline, _commandLine) ); ThrowTerminatingError ( new ErrorRecord ( ex, "InvokeHistoryNoHistoryForCommandline", ErrorCategory.ObjectNotFound, _commandLine ) ); } } else { if (_historyId <= 0) { Exception ex = new ArgumentOutOfRangeException ( "Id", StringUtil.Format(HistoryStrings.InvalidIdGetHistory, _historyId) ); ThrowTerminatingError ( new ErrorRecord ( ex, "InvokeHistoryInvalidIdGetHistory", ErrorCategory.InvalidArgument, _historyId ) ); } else { // Retrieve the command at the index we've specified entry = history.GetEntry(_historyId); if (entry == null || entry.Id != _historyId) { Exception ex = new ArgumentException ( StringUtil.Format(HistoryStrings.NoHistoryForId, _historyId) ); ThrowTerminatingError ( new ErrorRecord ( ex, "InvokeHistoryNoHistoryForId", ErrorCategory.ObjectNotFound, _historyId ) ); } } } } return entry; } /// <summary> /// Id of history entry to execute. /// </summary> private long _historyId = -1; /// <summary> /// Commandline to execute. /// </summary> private string _commandLine; /// <summary> /// Parse Id parameter to populate _historyId and _commandLine. /// </summary> private void PopulateIdAndCommandLine() { if (_id == null) return; try { _historyId = (long)LanguagePrimitives.ConvertTo(_id, typeof(long), System.Globalization.CultureInfo.InvariantCulture); } catch (PSInvalidCastException) { _commandLine = _id; return; } } /// <summary> /// Invoke-history is replaced in history by the command it executed. /// This replacement happens only if Invoke-History is single element /// in the pipeline. If there are more than one element in pipeline /// (ex A | Invoke-History 2 | B) then we cannot do this replacement. /// </summary> private void ReplaceHistoryString(HistoryInfo entry, LocalRunspace localRunspace) { var pipeline = (LocalPipeline)localRunspace.GetCurrentlyRunningPipeline(); if (pipeline.AddToHistory) { pipeline.HistoryString = entry.CommandLine; } } } /// <summary> /// This class Implements the add-history command. /// </summary> [Cmdlet(VerbsCommon.Add, "History", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096479")] [OutputType(typeof(HistoryInfo))] public class AddHistoryCommand : PSCmdlet { #region parameters /// <summary> /// This parameter specifies the current pipeline object. /// </summary> [Parameter(Position = 0, ValueFromPipeline = true)] public PSObject[] InputObject { get; set; } private bool _passthru; /// <summary> /// A Boolean that indicates whether history objects should be /// passed to the next element in the pipeline. /// </summary> [Parameter()] public SwitchParameter Passthru { get { return _passthru; } set { _passthru = value; } } #endregion parameters /// <summary> /// Override for BeginProcessing. /// </summary> protected override void BeginProcessing() { // Get currently running pipeline and add history entry for // this pipeline. // Note:Generally History entry for current pipeline is added // on completion of pipeline (See LocalPipeline implementation). // However Add-history adds additional entries in to history and // additional entries must be added after history for current pipeline. // This is done by adding the history entry for current pipeline below. LocalPipeline lpl = (LocalPipeline)((RunspaceBase)Context.CurrentRunspace).GetCurrentlyRunningPipeline(); lpl.AddHistoryEntryFromAddHistoryCmdlet(); } /// <summary> /// Override for ProcessRecord. /// </summary> protected override void ProcessRecord() { History history = ((LocalRunspace)Context.CurrentRunspace).History; Dbg.Assert(history != null, "History should be non null"); if (InputObject != null) { foreach (PSObject input in InputObject) { // Wrap the inputobject in PSObject and convert it to // HistoryInfo object. HistoryInfo infoToAdd = GetHistoryInfoObject(input); if (infoToAdd != null) { long id = history.AddEntry ( 0, infoToAdd.CommandLine, infoToAdd.ExecutionStatus, infoToAdd.StartExecutionTime, infoToAdd.EndExecutionTime, false ); if (Passthru) { HistoryInfo infoAdded = history.GetEntry(id); WriteObject(infoAdded); } } } } } /// <summary> /// Convert mshObject that has the properties of an HistoryInfo /// object in to HistoryInfo object. /// </summary> /// <param name="mshObject"> /// mshObject to be converted to HistoryInfo. /// </param> /// <returns> /// HistoryInfo object if conversion is successful else null. /// </returns> #pragma warning disable 0162 private HistoryInfo GetHistoryInfoObject(PSObject mshObject) { do { if (mshObject == null) { break; } // Read CommandLine property if (!(GetPropertyValue(mshObject, "CommandLine") is string commandLine)) { break; } // Read ExecutionStatus property object pipelineState = GetPropertyValue(mshObject, "ExecutionStatus"); if (pipelineState == null) { break; } PipelineState executionStatus; if (pipelineState is PipelineState) { executionStatus = (PipelineState)pipelineState; } else if (pipelineState is PSObject) { PSObject serializedPipelineState = pipelineState as PSObject; object baseObject = serializedPipelineState.BaseObject; if (baseObject is not int) { break; } executionStatus = (PipelineState)baseObject; if (executionStatus < PipelineState.NotStarted || executionStatus > PipelineState.Failed) { break; } } else if (pipelineState is string) { try { executionStatus = (PipelineState)Enum.Parse(typeof(PipelineState), (string)pipelineState); } catch (ArgumentException) { break; } } else { break; } // Read StartExecutionTime property DateTime startExecutionTime; object temp = GetPropertyValue(mshObject, "StartExecutionTime"); if (temp == null) { break; } else if (temp is DateTime) { startExecutionTime = (DateTime)temp; } else if (temp is string) { try { startExecutionTime = DateTime.Parse((string)temp, System.Globalization.CultureInfo.CurrentCulture); } catch (FormatException) { break; } } else { break; } // Read EndExecutionTime property DateTime endExecutionTime; temp = GetPropertyValue(mshObject, "EndExecutionTime"); if (temp == null) { break; } else if (temp is DateTime) { endExecutionTime = (DateTime)temp; } else if (temp is string) { try { endExecutionTime = DateTime.Parse((string)temp, System.Globalization.CultureInfo.CurrentCulture); } catch (FormatException) { break; } } else { break; } return new HistoryInfo ( 0, commandLine, executionStatus, startExecutionTime, endExecutionTime ); } while (false); // If we are here, an error has occured. Exception ex = new InvalidDataException ( StringUtil.Format(HistoryStrings.AddHistoryInvalidInput) ); WriteError ( new ErrorRecord ( ex, "AddHistoryInvalidInput", ErrorCategory.InvalidData, mshObject ) ); return null; } #pragma warning restore 0162 private static object GetPropertyValue(PSObject mshObject, string propertyName) { PSMemberInfo propertyInfo = mshObject.Properties[propertyName]; if (propertyInfo == null) return null; return propertyInfo.Value; } } ///<summary> /// This Class implements the Clear History cmdlet ///</summary> [Cmdlet(VerbsCommon.Clear, "History", SupportsShouldProcess = true, DefaultParameterSetName = "IDParameter", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096691")] public class ClearHistoryCommand : PSCmdlet { #region Command Line Parameters /// <summary> /// Specifies the ID of a command in the session history.Clear history clears the entries /// wit the specified ID(s) /// </summary> [Parameter(ParameterSetName = "IDParameter", Position = 0, HelpMessage = "Specifies the ID of a command in the session history.Clear history clears only the specified command")] [ValidateRangeAttribute((int)1, int.MaxValue)] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public int[] Id { get { return _id; } set { _id = value; } } /// <summary> /// Id of a history entry. /// </summary> private int[] _id; /// <summary> /// Command line name of an entry in the session history. /// </summary> [Parameter(ParameterSetName = "CommandLineParameter", HelpMessage = "Specifies the name of a command in the session history")] [ValidateNotNullOrEmpty()] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] CommandLine { get { return _commandline; } set { _commandline = value; } } /// <summary> /// Commandline parameter. /// </summary> private string[] _commandline = null; ///<summary> /// Clears the specified number of history entries ///</summary> [Parameter(Mandatory = false, Position = 1, HelpMessage = "Clears the specified number of history entries")] [ValidateRangeAttribute((int)1, int.MaxValue)] public int Count { get { return _count; } set { _countParameterSpecified = true; _count = value; } } /// <summary> /// Count of the history entries. /// </summary> private int _count = 32; /// <summary> /// A boolean variable to indicate if the count parameter specified. /// </summary> private bool _countParameterSpecified = false; /// <summary> /// Specifies whether new entries to be cleared or the default old ones. /// </summary> [Parameter(Mandatory = false, HelpMessage = "Specifies whether new entries to be cleared or the default old ones.")] public SwitchParameter Newest { get { return _newest; } set { _newest = value; } } /// <summary> /// Switch parameter on the history entries. /// </summary> private SwitchParameter _newest; #endregion Command Line Parameters /// <summary> /// Overriding Begin Processing. /// </summary> protected override void BeginProcessing() { _history = ((LocalRunspace)Context.CurrentRunspace).History; } /// <summary> /// Overriding Process Record. /// </summary> protected override void ProcessRecord() { // case statement to identify the parameter set switch (ParameterSetName) { case "IDParameter": ClearHistoryByID(); break; case "CommandLineParameter": ClearHistoryByCmdLine(); break; default: ThrowTerminatingError( new ErrorRecord( new ArgumentException("Invalid ParameterSet Name"), "Unable to access the session history", ErrorCategory.InvalidOperation, null)); return; } } #region Private /// <summary> /// Clears the session history based on the id parameter /// takes no parameters /// <returns>Nothing.</returns> /// </summary> private void ClearHistoryByID() { if (_countParameterSpecified && Count < 0) { Exception ex = new ArgumentException ( StringUtil.Format("HistoryStrings", "InvalidCountValue") ); ThrowTerminatingError ( new ErrorRecord ( ex, "ClearHistoryInvalidCountValue", ErrorCategory.InvalidArgument, _count ) ); } // if id parameter is not present if (_id != null) { // if count parameter is not present if (!_countParameterSpecified) { // clearing the entry for each id in the id[] parameter. foreach (long id in _id) { Dbg.Assert(id > 0, "ValidateRangeAttribute should not allow this"); HistoryInfo entry = _history.GetEntry(id); if (entry != null && entry.Id == id) { _history.ClearEntry(entry.Id); } else {// throw an exception if an entry for an id is not found Exception ex = new ArgumentException ( StringUtil.Format(HistoryStrings.NoHistoryForId, id) ); WriteError ( new ErrorRecord ( ex, "GetHistoryNoHistoryForId", ErrorCategory.ObjectNotFound, id ) ); } } } else if (_id.Length > 1) {// throwing an exception for invalid parameter combinations Exception ex = new ArgumentException ( StringUtil.Format(HistoryStrings.NoCountWithMultipleIds) ); ThrowTerminatingError ( new ErrorRecord ( ex, "GetHistoryNoCountWithMultipleIds", ErrorCategory.InvalidArgument, _count ) ); } else {// if id,count and newest parameters are present // throw an exception for invalid count values long id = _id[0]; Dbg.Assert(id > 0, "ValidateRangeAttribute should not allow this"); ClearHistoryEntries(id, _count, null, _newest); } } else { // confirmation message if all the clearhistory cmdlet is used without any parameters if (_countParameterSpecified == false) { string message = StringUtil.Format(HistoryStrings.ClearHistoryWarning, "Warning");// "The command would clear all the entry(s) from the session history,Are you sure you want to continue ?"; if (!ShouldProcess(message)) { return; } ClearHistoryEntries(0, -1, null, _newest); } else { ClearHistoryEntries(0, _count, null, _newest); } } } /// <summary> /// Clears the session history based on the Commandline parameter /// takes no parameters /// <returns>Nothing.</returns> /// </summary> private void ClearHistoryByCmdLine() { // throw an exception for invalid count values if (_countParameterSpecified && Count < 0) { Exception ex = new ArgumentException ( StringUtil.Format(HistoryStrings.InvalidCountValue) ); ThrowTerminatingError ( new ErrorRecord ( ex, "ClearHistoryInvalidCountValue", ErrorCategory.InvalidArgument, _count ) ); } // if command line is not present if (_commandline != null) { // if count parameter is not present if (!_countParameterSpecified) { foreach (string cmd in _commandline) { ClearHistoryEntries(0, 1, cmd, _newest); } } else if (_commandline.Length > 1) {// throwing exceptions for invalid parameter combinations Exception ex = new ArgumentException ( StringUtil.Format(HistoryStrings.NoCountWithMultipleCmdLine) ); ThrowTerminatingError ( new ErrorRecord ( ex, "NoCountWithMultipleCmdLine ", ErrorCategory.InvalidArgument, _commandline ) ); } else { // if commandline,count and newest parameters are present. ClearHistoryEntries(0, _count, _commandline[0], _newest); } } } /// <summary> /// Clears the session history based on the input parameter /// <param name="id" >Id of the entry to be cleared.</param> /// <param name="count" >Count of entries to be cleared.</param> /// <param name="cmdline" >Cmdline string to be cleared.</param> /// <param name="newest" >Order of the entries.</param> /// <returns>Nothing.</returns> /// </summary> private void ClearHistoryEntries(long id, int count, string cmdline, SwitchParameter newest) { // if cmdline is null,use default parameter set notion. if (cmdline == null) { // if id is present,clears count entries from id if (id > 0) { HistoryInfo entry = _history.GetEntry(id); if (entry == null || entry.Id != id) { Exception ex = new ArgumentException ( StringUtil.Format(HistoryStrings.NoHistoryForId, id) ); WriteError ( new ErrorRecord ( ex, "GetHistoryNoHistoryForId", ErrorCategory.ObjectNotFound, id ) ); } _entries = _history.GetEntries(id, count, newest); } else {// if only count is present _entries = _history.GetEntries(0, count, newest); } } else { // creates a wild card pattern WildcardPattern wildcardpattern = WildcardPattern.Get(cmdline, WildcardOptions.IgnoreCase); // count set to zero if not specified. if (!_countParameterSpecified && WildcardPattern.ContainsWildcardCharacters(cmdline)) { count = 0; } // Return the matching history entries for the command line parameter // if newest id false...gets the oldest entry _entries = _history.GetEntries(wildcardpattern, count, newest); } // Clear the History value. foreach (HistoryInfo entry in _entries) { if (entry != null && entry.Cleared == false) _history.ClearEntry(entry.Id); } return; } /// <summary> /// History obj. /// </summary> private History _history; /// <summary> /// Array of historyinfo objects. /// </summary> private HistoryInfo[] _entries; #endregion Private } }
36.201112
241
0.459605
[ "MIT" ]
artdevelopertj/PowerShell
src/System.Management.Automation/engine/hostifaces/History.cs
71,642
C#
/******************************************************************************* * Copyright (C) 2012 eBay Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using AsimovDeploy.WinAgent.Framework.Common; using AsimovDeploy.WinAgent.Framework.Events; using AsimovDeploy.WinAgent.Framework.Models.PackageSources; using AsimovDeploy.WinAgent.Framework.Models.UnitActions; namespace AsimovDeploy.WinAgent.Framework.Models.Units { public abstract class DeployUnit { public string Name { get; set; } public PackageInfo PackageInfo { get; set; } public string DataDirectory { get; set; } public DeployStatus DeployStatus { get; protected set; } public DeployedVersion Version { get; protected set; } public string[] OnlyOnAgents { get; set; } public UnitActionList Actions { get; set; } = new UnitActionList { new RollbackUnitAction() }; public ActionParameterList DeployParameters { get; protected set; } = new ActionParameterList(); public ActionParameterList Credentials { get; protected set; } = new ActionParameterList(); public bool HasDeployParameters => GetDeployParameters().Count > 0 || GetCredentials().Count > 0; public string Group { get; set; } = "N/A"; public abstract string UnitType { get; } public List<string> Tags { get; set; } = new List<string> { "os:Windows", $"host:{Environment.MachineName}" }; public abstract AsimovTask GetDeployTask(AsimovVersion version, ParameterValues parameterValues, AsimovUser user, string correlationId); public abstract void SetupDeployActions(); public virtual DeployUnitInfo GetUnitInfo(bool refreshUnitStatus) { var deployUnitInfo = new DeployUnitInfo { Name = Name, Group = Group, HasDeployParameters = HasDeployParameters }; if (Version == null) { Version = VersionUtil.GetCurrentVersion(DataDirectory); if (Version.DeployFailed) DeployStatus = DeployStatus.DeployFailed; } if (!Version.DeployFailed) { if (Version.DeployTimestamp == DateTime.MinValue) { deployUnitInfo.LastDeployed = string.Empty; } else { deployUnitInfo.LastDeployed = $"Deployed by {Version.UserName} {DateUtils.GetFriendlyAge(Version.DeployTimestamp)}"; } } deployUnitInfo.Version = Version; deployUnitInfo.DeployStatus = DeployStatus; if (refreshUnitStatus) { UpdateUnitStatus(); } return deployUnitInfo; } protected virtual void UpdateUnitStatus() { } public IList<DeployedVersion> GetDeployedVersions() => VersionUtil.ReadVersionLog(DataDirectory); public bool IsValidForAgent(string agentName) { if (OnlyOnAgents?.Any(x => x == agentName) ?? true) return true; return OnlyOnAgents.Where(t => t.Contains("*")).Any(agent => new Regex("^" + agent.Replace("*", ".*")).IsMatch(agentName)); } public void StartingDeploy(AsimovVersion newVersion, string logFileName, AsimovUser user, string correlationId, ParameterValues parameters) { DeployStatus = DeployStatus.Deploying; Version = new DeployedVersion { DeployTimestamp = DateTime.Now, VersionId = newVersion.Id, VersionNumber = newVersion.Number, VersionBranch = newVersion.Branch, VersionTimestamp = newVersion.Timestamp, VersionCommit = newVersion.Commit, LogFileName = logFileName, UserId = user.UserId, UserName = user.UserName, DeployFailed = false, CorrelationId = correlationId, Parameters = parameters.GetInternalDictionary() }; NotificationPublisher.PublishNotifications(new DeployStartedEvent(Name, Version)); } public void DeployCompleted() { DeployStatus = DeployStatus.NA; VersionUtil.UpdateVersionLog(DataDirectory, Version); var unitInfo = GetUnitInfo(true); NotificationPublisher.PublishNotifications(new DeployCompletedEvent(Name, Version, unitInfo.Status)); } public void DeployFailed() { DeployStatus = DeployStatus.DeployFailed; Version.DeployFailed = true; VersionUtil.UpdateVersionLog(DataDirectory, Version); NotificationPublisher.PublishNotifications(new DeployFailedEvent(Name, Version)); } public virtual ActionParameterList GetDeployParameters() { return DeployParameters; } public virtual ActionParameterList GetCredentials() { return Credentials; } public void Refresh() { GetUnitInfo(true); } } }
35.993976
147
0.599833
[ "Apache-2.0" ]
Korla/asimov-deploy-winagent
src/AsimovDeploy.WinAgent/Framework/Models/Units/DeployUnit.cs
5,975
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 rds-2014-10-31.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.RDS.Model { /// <summary> /// Contains the results of a successful invocation of the <a>DescribeEventSubscriptions</a> /// action. /// </summary> public partial class CreateEventSubscriptionResult : AmazonWebServiceResponse { private EventSubscription _response; public EventSubscription EventSubscription { get { return this._response; } set { this._response = value; } } } }
30.613636
101
0.705271
[ "Apache-2.0" ]
samritchie/aws-sdk-net
AWSSDK_DotNet35/Amazon.RDS/Model/CreateEventSubscriptionResult.cs
1,347
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Mission_Text_Script : MonoBehaviour { string s_1 = "Welcome "; string secret_1 = "This is the story about "; string secret_2 = " a small game development project "; string s_2 = " First of " ; string s_3 = " this is a Bomberman game. "; string secret_3 = " Hope you like it. " ; string secret_4 = " Here is an example of how level progression could work. "; string s_4 = " Text "; string secret_5 = " secret "; string s_5 = "Text "; string secret_6 = " Secret"; string s_6 = " text" ; string secret_7 = " secret." ; string s_7 = "\n"+ "Cheers Grebtsew"; // Use this for initialization void Start () { Text t = GetComponent<Text>(); t.text = create_text(); } private string create_text(){ string res = ""; int i = PlayerPrefs.GetInt("current_level"); Debug.Log(i); res += s_1; if(i >= 1){ res+= secret_1; } else { res += "-- --- -- -----"; } if(i >= 2){ res+= secret_2; } else { res += "-- ---- -- ---"; } res += s_2; res += s_3; if(i >= 3){ res += secret_3; } else { res += "--- --- ------"; } if(i >= 4){ res += secret_4; } else { res += "-------------------"; } res += s_4; if(i >= 5){ res += secret_5; } else { res += "--- -- ----"; } res += s_5; if(i >= 6){ res += secret_6; } else { res += "------- -- --"; } res += s_6; if(i >= 7){ res += secret_7; } else { res += "--- -- ----"; } res += s_7; return res; } // Update is called once per frame void Update () { } }
18.355556
79
0.520581
[ "MIT" ]
Atomotos/Smoloons
Assets/Scripts/Mission_Text_Script.cs
1,654
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /* * Common file that contains interface definitions for generic server and client * transport managers. * */ using System.Management.Automation.Tracing; using System.Text; using System.IO; using System.Xml; using System.Collections.Generic; using System.Globalization; using System.Threading; using System.Management.Automation.Internal; #if !UNIX using System.Security.Principal; #endif // Don't expose the System.Management.Automation namespace here. This is transport layer // and it shouldn't know anything about the engine. using System.Management.Automation.Remoting.Client; // TODO: this seems ugly...Remoting datatypes should be in remoting namespace using System.Management.Automation.Runspaces.Internal; using PSRemotingCryptoHelper = System.Management.Automation.Internal.PSRemotingCryptoHelper; using RunspaceConnectionInfo = System.Management.Automation.Runspaces.RunspaceConnectionInfo; using TypeTable = System.Management.Automation.Runspaces.TypeTable; using Dbg = System.Management.Automation.Diagnostics; namespace System.Management.Automation.Remoting { #region TransportErrorOccuredEventArgs internal enum TransportMethodEnum { CreateShellEx = 0, RunShellCommandEx = 1, SendShellInputEx = 2, ReceiveShellOutputEx = 3, CloseShellOperationEx = 4, CommandInputEx = 5, ReceiveCommandOutputEx = 6, DisconnectShellEx = 7, ReconnectShellEx = 8, ConnectShellEx = 9, ReconnectShellCommandEx = 10, ConnectShellCommandEx = 11, Unknown = 12, } /// <summary> /// Event arguments passed to TransportErrorOccured handlers. /// </summary> internal class TransportErrorOccuredEventArgs : EventArgs { /// <summary> /// Constructor. /// </summary> /// <param name="e"> /// Error occurred. /// </param> /// <param name="m"> /// The transport method that raised the error /// </param> internal TransportErrorOccuredEventArgs(PSRemotingTransportException e, TransportMethodEnum m) { Exception = e; ReportingTransportMethod = m; } /// <summary> /// Gets the error occurred. /// </summary> internal PSRemotingTransportException Exception { get; set; } /// <summary> /// Transport method that is reporting this error. /// </summary> internal TransportMethodEnum ReportingTransportMethod { get; } } #endregion #region ConnectionStatusEventArgs /// <summary> /// Robust Connection notifications. /// </summary> internal enum ConnectionStatus { NetworkFailureDetected = 1, ConnectionRetryAttempt = 2, ConnectionRetrySucceeded = 3, AutoDisconnectStarting = 4, AutoDisconnectSucceeded = 5, InternalErrorAbort = 6 } /// <summary> /// ConnectionStatusEventArgs. /// </summary> internal class ConnectionStatusEventArgs : EventArgs { internal ConnectionStatusEventArgs(ConnectionStatus notification) { Notification = notification; } internal ConnectionStatus Notification { get; } } #endregion #region CreateCompleteEventArgs /// <summary> /// CreateCompleteEventArgs. /// </summary> internal class CreateCompleteEventArgs : EventArgs { internal RunspaceConnectionInfo ConnectionInfo { get; } internal CreateCompleteEventArgs( RunspaceConnectionInfo connectionInfo) { ConnectionInfo = connectionInfo; } } #endregion /// <summary> /// Contains implementation that is common to both client and server /// transport managers. /// </summary> internal abstract class BaseTransportManager : IDisposable { #region tracer [TraceSourceAttribute("Transport", "Traces BaseWSManTransportManager")] private static readonly PSTraceSource s_baseTracer = PSTraceSource.GetTracer("Transport", "Traces BaseWSManTransportManager"); #endregion #region Global Constants // KeepAlive: Server 4 minutes, Client 3 minutes // The server timeout value has to be bigger than the client timeout value. // This is due to the WinRM implementation on the Listener. // So We added a 1 minute network delay to count for this. internal const int ServerDefaultKeepAliveTimeoutMs = 4 * 60 * 1000; // milliseconds = 4 minutes internal const int ClientDefaultOperationTimeoutMs = 3 * 60 * 1000; // milliseconds = 3 minutes // Close timeout: to prevent unbounded close operation, we set a 1 minute bound. internal const int ClientCloseTimeoutMs = 60 * 1000; // This value instructs the server to use whatever setting it has for idle timeout. internal const int UseServerDefaultIdleTimeout = -1; internal const uint UseServerDefaultIdleTimeoutUInt = UInt32.MaxValue; // Minimum allowed idle timeout time is 60 seconds. internal const int MinimumIdleTimeout = 60 * 1000; internal const int DefaultFragmentSize = 32 << 10; // 32KB // Quota related consts and session variables. internal const int MaximumReceivedDataSize = 50 << 20; // 50MB internal const int MaximumReceivedObjectSize = 10 << 20; // 10MB // Session variables supporting powershell quotas. internal const string MAX_RECEIVED_DATA_PER_COMMAND_MB = "PSMaximumReceivedDataSizePerCommandMB"; internal const string MAX_RECEIVED_OBJECT_SIZE_MB = "PSMaximumReceivedObjectSizeMB"; #endregion #region Private Data // fragmentor used to fragment & defragment objects added to this collection. private readonly ReceiveDataCollection.OnDataAvailableCallback _onDataAvailableCallback; // crypto helper used for encrypting/decrypting // secure string #endregion #region EventHandlers internal event EventHandler<TransportErrorOccuredEventArgs> WSManTransportErrorOccured; /// <summary> /// Event that is raised when a remote object is available. The event is raised /// from a WSMan transport thread. Since this thread can hold on to a HTTP /// connection, the event handler should complete processing as fast as possible. /// Importantly the event handler should not generate any call that results in a /// user request like host.ReadLine(). /// </summary> internal event EventHandler<RemoteDataEventArgs> DataReceived; /// <summary> /// Listen to this event to observe the PowerShell guid of the processed object. /// </summary> public event EventHandler PowerShellGuidObserver; #endregion #region Constructor protected BaseTransportManager(PSRemotingCryptoHelper cryptoHelper) { CryptoHelper = cryptoHelper; // create a common fragmentor used by this transport manager to send and receive data. // so type information is serialized only the first time an object of a particular type // is sent. only data is serialized for the rest of the objects of the same type. Fragmentor = new Fragmentor(DefaultFragmentSize, cryptoHelper); ReceivedDataCollection = new PriorityReceiveDataCollection(Fragmentor, (this is BaseClientTransportManager)); _onDataAvailableCallback = new ReceiveDataCollection.OnDataAvailableCallback(OnDataAvailableCallback); } #endregion #region Helper Methods internal Fragmentor Fragmentor { get; set; } /// <summary> /// This is needed to deserialize objects coming from the network. /// This may be null..in which case type rehydration does not happen. /// At construction time we may not have typetable (server runspace /// is created only when a request from the client)..so this is /// a property on the base transport manager to allow for setting at /// a later time. /// </summary> internal TypeTable TypeTable { get { return Fragmentor.TypeTable; } set { Fragmentor.TypeTable = value; } } /// <summary> /// Uses the "OnDataAvailableCallback" to handle Deserialized objects. /// </summary> /// <param name="data"> /// data to process /// </param> /// <param name="stream"> /// priority stream this data belongs to /// </param> internal virtual void ProcessRawData(byte[] data, string stream) { try { ProcessRawData(data, stream, _onDataAvailableCallback); } catch (Exception exception) { // This will get executed on a thread pool thread.. // so we need to protect that thread, hence catching // all exceptions s_baseTracer.WriteLine("Exception processing data. {0}", exception.Message); PSRemotingTransportException e = new PSRemotingTransportException(exception.Message, exception); TransportErrorOccuredEventArgs eventargs = new TransportErrorOccuredEventArgs(e, TransportMethodEnum.ReceiveShellOutputEx); RaiseErrorHandler(eventargs); return; } } /// <summary> /// </summary> /// <param name="data"> /// data to process /// </param> /// <param name="stream"> /// priority stream this data belongs to /// </param> /// <param name="dataAvailableCallback"> /// used by the caller to supply a callback to handle deserialized object. /// </param> /// <exception cref="Exception"> /// Since dataAvailableCallback is called in this method, and the handler /// may be handled by 3rd party code (eventually),this may throw any exception. /// </exception> internal void ProcessRawData(byte[] data, string stream, ReceiveDataCollection.OnDataAvailableCallback dataAvailableCallback) { Dbg.Assert(data != null, "Cannot process null data"); s_baseTracer.WriteLine("Processing incoming data for stream {0}.", stream); bool shouldProcess = false; DataPriorityType dataPriority = DataPriorityType.Default; if (stream.Equals(WSManNativeApi.WSMAN_STREAM_ID_STDIN, StringComparison.OrdinalIgnoreCase) || stream.Equals(WSManNativeApi.WSMAN_STREAM_ID_STDOUT, StringComparison.OrdinalIgnoreCase)) { shouldProcess = true; } else if (stream.Equals(WSManNativeApi.WSMAN_STREAM_ID_PROMPTRESPONSE, StringComparison.OrdinalIgnoreCase)) { dataPriority = DataPriorityType.PromptResponse; shouldProcess = true; } if (!shouldProcess) { // we dont support this stream..so ignore the data Dbg.Assert(false, string.Format(CultureInfo.InvariantCulture, "Data should be from one of the streams : {0} or {1} or {2}", WSManNativeApi.WSMAN_STREAM_ID_STDIN, WSManNativeApi.WSMAN_STREAM_ID_STDOUT, WSManNativeApi.WSMAN_STREAM_ID_PROMPTRESPONSE)); s_baseTracer.WriteLine("{0} is not a valid stream", stream); } // process data ReceivedDataCollection.ProcessRawData(data, dataPriority, dataAvailableCallback); } /// <summary> /// </summary> /// <param name="remoteObject"></param> /// <exception cref="Exception"> /// The handler may be handled by 3rd party code (eventually), /// this may throw any exception. /// </exception> internal void OnDataAvailableCallback(RemoteDataObject<PSObject> remoteObject) { // log the data to crimson logs PSEtwLog.LogAnalyticInformational(PSEventId.TransportReceivedObject, PSOpcode.Open, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, remoteObject.RunspacePoolId.ToString(), remoteObject.PowerShellId.ToString(), (UInt32)(remoteObject.Destination), (UInt32)(remoteObject.DataType), (UInt32)(remoteObject.TargetInterface)); // This might throw exceptions which the caller handles. PowerShellGuidObserver.SafeInvoke(remoteObject.PowerShellId, EventArgs.Empty); RemoteDataEventArgs eventArgs = new RemoteDataEventArgs(remoteObject); DataReceived.SafeInvoke(this, eventArgs); } /// <summary> /// Copy the DataReceived event handlers to the supplied transport Manager. /// </summary> /// <param name="transportManager"></param> public void MigrateDataReadyEventHandlers(BaseTransportManager transportManager) { foreach (Delegate handler in transportManager.DataReceived.GetInvocationList()) { DataReceived += (EventHandler<RemoteDataEventArgs>)handler; } } /// <summary> /// Raise the error handlers. /// </summary> /// <param name="eventArgs"></param> internal virtual void RaiseErrorHandler(TransportErrorOccuredEventArgs eventArgs) { WSManTransportErrorOccured.SafeInvoke(this, eventArgs); } /// <summary> /// Crypto handler to be used for encrypting/decrypting /// secure strings. /// </summary> internal PSRemotingCryptoHelper CryptoHelper { get; set; } /// <summary> /// A data buffer used to store data received from remote machine. /// </summary> internal PriorityReceiveDataCollection ReceivedDataCollection { get; } #endregion #region IDisposable implementation /// <summary> /// Dispose the transport and release resources. /// </summary> public void Dispose() { Dispose(true); // if already disposing..no need to let finalizer thread // put resources to clean this object. System.GC.SuppressFinalize(this); } internal virtual void Dispose(bool isDisposing) { if (isDisposing) { ReceivedDataCollection.Dispose(); } } #endregion } } namespace System.Management.Automation.Remoting.Client { internal abstract class BaseClientTransportManager : BaseTransportManager, IDisposable { #region Tracer [TraceSourceAttribute("ClientTransport", "Traces ClientTransportManager")] protected static PSTraceSource tracer = PSTraceSource.GetTracer("ClientTransport", "Traces ClientTransportManager"); #endregion #region Data protected bool isClosed; protected object syncObject = new object(); protected PrioritySendDataCollection dataToBeSent; // used to handle callbacks from the server..these are used to synchronize received callbacks private readonly Queue<CallbackNotificationInformation> _callbackNotificationQueue; private readonly ReceiveDataCollection.OnDataAvailableCallback _onDataAvailableCallback; private bool _isServicingCallbacks; private bool _suspendQueueServicing; private bool _isDebuggerSuspend; // this is used log crimson messages. // keeps track of whether a receive request has been placed on transport protected bool receiveDataInitiated; #endregion #region Constructors protected BaseClientTransportManager(Guid runspaceId, PSRemotingCryptoHelper cryptoHelper) : base(cryptoHelper) { RunspacePoolInstanceId = runspaceId; dataToBeSent = new PrioritySendDataCollection(); _onDataAvailableCallback = new ReceiveDataCollection.OnDataAvailableCallback(OnDataAvailableHandler); _callbackNotificationQueue = new Queue<CallbackNotificationInformation>(); } #endregion #region Events /// <summary> /// Event that is raised when a create operation on transport has been successfully completed /// The event is raised /// from a WSMan transport thread. Since this thread can hold on to a HTTP /// connection, the event handler should complete processing as fast as possible. /// Importantly the event handler should not generate any call that results in a /// user request like host.ReadLine(). /// /// Errors (occurred during connection attempt) are reported through WSManTransportErrorOccured /// event. /// </summary> internal event EventHandler<CreateCompleteEventArgs> CreateCompleted; /// <summary> /// Event that is raised when a remote connection is successfully closed. The event is raised /// from a WSMan transport thread. Since this thread can hold on to a HTTP /// connection, the event handler should complete processing as fast as possible. /// Importantly the event handler should not generate any call that results in a /// user request like host.ReadLine(). /// /// Errors (occurred during connection attempt) are reported through WSManTransportErrorOccured /// event. /// </summary> /// <remarks> /// The eventhandler should make sure not to throw any exceptions. /// </remarks> internal event EventHandler<EventArgs> CloseCompleted; /// <summary> /// Indicated successful completion of a connect operation on transport /// /// Errors are reported through WSManTransportErrorOccured /// event. /// </summary> internal event EventHandler<EventArgs> ConnectCompleted; /// <summary> /// Indicated successful completion of a disconnect operation on transport /// /// Errors are reported through WSManTransportErrorOccured /// event. /// </summary> internal event EventHandler<EventArgs> DisconnectCompleted; /// <summary> /// Indicated successful completion of a reconnect operation on transport /// /// Errors are reported through WSManTransportErrorOccured /// event. /// </summary> internal event EventHandler<EventArgs> ReconnectCompleted; /// <summary> /// Indicates that the transport/command is ready for a disconnect operation. /// /// Errors are reported through WSManTransportErrorOccured event. /// </summary> internal event EventHandler<EventArgs> ReadyForDisconnect; /// <summary> /// Event to pass Robust Connection notifications to client. /// </summary> internal event EventHandler<ConnectionStatusEventArgs> RobustConnectionNotification; /// <summary> /// Indicates successful processing of a delay stream request on a receive operation /// /// this event is useful when PS wants to invoke a pipeline in disconnected mode. /// </summary> internal event EventHandler<EventArgs> DelayStreamRequestProcessed; #endregion #region Properties /// <summary> /// Gets the data collection which is used by this transport manager to send /// data to the server. /// </summary> internal PrioritySendDataCollection DataToBeSentCollection { get { return dataToBeSent; } } /// <summary> /// Used to log crimson messages. /// </summary> internal Guid RunspacePoolInstanceId { get; } /// <summary> /// Raise the Connect completed handler. /// </summary> internal void RaiseCreateCompleted(CreateCompleteEventArgs eventArgs) { CreateCompleted.SafeInvoke(this, eventArgs); } internal void RaiseConnectCompleted() { ConnectCompleted.SafeInvoke(this, EventArgs.Empty); } internal void RaiseDisconnectCompleted() { DisconnectCompleted.SafeInvoke(this, EventArgs.Empty); } internal void RaiseReconnectCompleted() { ReconnectCompleted.SafeInvoke(this, EventArgs.Empty); } /// <summary> /// Raise the close completed handler. /// </summary> internal void RaiseCloseCompleted() { CloseCompleted.SafeInvoke(this, EventArgs.Empty); } /// <summary> /// Raise the ReadyForDisconnect event. /// </summary> internal void RaiseReadyForDisconnect() { ReadyForDisconnect.SafeInvoke(this, EventArgs.Empty); } /// <summary> /// Queue the robust connection notification event. /// </summary> /// <param name="flags">Determines what kind of notification.</param> internal void QueueRobustConnectionNotification(int flags) { ConnectionStatusEventArgs args = null; switch (flags) { case (int)WSManNativeApi.WSManCallbackFlags.WSMAN_FLAG_CALLBACK_NETWORK_FAILURE_DETECTED: args = new ConnectionStatusEventArgs(ConnectionStatus.NetworkFailureDetected); break; case (int)WSManNativeApi.WSManCallbackFlags.WSMAN_FLAG_CALLBACK_RETRYING_AFTER_NETWORK_FAILURE: args = new ConnectionStatusEventArgs(ConnectionStatus.ConnectionRetryAttempt); break; case (int)WSManNativeApi.WSManCallbackFlags.WSMAN_FLAG_CALLBACK_RECONNECTED_AFTER_NETWORK_FAILURE: args = new ConnectionStatusEventArgs(ConnectionStatus.ConnectionRetrySucceeded); break; case (int)WSManNativeApi.WSManCallbackFlags.WSMAN_FLAG_CALLBACK_SHELL_AUTODISCONNECTING: args = new ConnectionStatusEventArgs(ConnectionStatus.AutoDisconnectStarting); break; case (int)WSManNativeApi.WSManCallbackFlags.WSMAN_FLAG_CALLBACK_SHELL_AUTODISCONNECTED: args = new ConnectionStatusEventArgs(ConnectionStatus.AutoDisconnectSucceeded); break; case (int)WSManNativeApi.WSManCallbackFlags.WSMAN_FLAG_CALLBACK_RETRY_ABORTED_DUE_TO_INTERNAL_ERROR: args = new ConnectionStatusEventArgs(ConnectionStatus.InternalErrorAbort); break; } // Queue worker item to raise the event so that all robust connection // events are raised in the same order as received. EnqueueAndStartProcessingThread(null, null, args); } /// <summary> /// Raise the Robust Connection notification event. /// </summary> /// <param name="args">ConnectionStatusEventArgs.</param> internal void RaiseRobustConnectionNotification(ConnectionStatusEventArgs args) { RobustConnectionNotification.SafeInvoke(this, args); } internal void RaiseDelayStreamProcessedEvent() { DelayStreamRequestProcessed.SafeInvoke(this, EventArgs.Empty); } #endregion #region Received Data Processing Thread internal override void ProcessRawData(byte[] data, string stream) { if (isClosed) { return; } try { base.ProcessRawData(data, stream, _onDataAvailableCallback); } catch (PSRemotingTransportException pte) { // PSRemotingTransportException need not be wrapped in another PSRemotingTransportException. tracer.WriteLine("Exception processing data. {0}", pte.Message); TransportErrorOccuredEventArgs eventargs = new TransportErrorOccuredEventArgs(pte, TransportMethodEnum.ReceiveShellOutputEx); EnqueueAndStartProcessingThread(null, eventargs, null); return; } catch (Exception exception) { // Enqueue an Exception to process in a thread-pool thread. Processing // Exception in a thread pool thread is important as calling // WSManCloseShell/Command from a Receive callback results in a deadlock. tracer.WriteLine("Exception processing data. {0}", exception.Message); PSRemotingTransportException e = new PSRemotingTransportException(exception.Message); TransportErrorOccuredEventArgs eventargs = new TransportErrorOccuredEventArgs(e, TransportMethodEnum.ReceiveShellOutputEx); EnqueueAndStartProcessingThread(null, eventargs, null); return; } } private void OnDataAvailableHandler(RemoteDataObject<PSObject> remoteObject) { EnqueueAndStartProcessingThread(remoteObject, null, null); } /// <summary> /// Enqueue a deserialized object or an Exception to process in a thread pool /// thread. Processing Exception in a thread pool thread is important as calling /// WSManCloseShell/Command from a Receive callback results in a deadlock. /// </summary> /// <param name="remoteObject"> /// Deserialized Object to process in a thread-pool thread. This should be null /// when <paramref name="transportException"/> is specified. /// </param> /// <param name="privateData"> /// Data that is neither RemoteObject or Exception. This is used by Client Command /// Transport manager to raise SignalCompleted callback. /// </param> /// <param name="transportErrorArgs"> /// Error containing transport exception. /// </param> internal void EnqueueAndStartProcessingThread(RemoteDataObject<PSObject> remoteObject, TransportErrorOccuredEventArgs transportErrorArgs, object privateData) { if (isClosed) { return; } lock (_callbackNotificationQueue) { if ((remoteObject != null) || (transportErrorArgs != null) || (privateData != null)) { CallbackNotificationInformation rcvdDataInfo = new CallbackNotificationInformation(); rcvdDataInfo.remoteObject = remoteObject; rcvdDataInfo.transportError = transportErrorArgs; rcvdDataInfo.privateData = privateData; if (remoteObject != null && (remoteObject.DataType == RemotingDataType.PublicKey || remoteObject.DataType == RemotingDataType.EncryptedSessionKey || remoteObject.DataType == RemotingDataType.PublicKeyRequest)) { CryptoHelper.Session.BaseSessionDataStructureHandler.RaiseKeyExchangeMessageReceived(remoteObject); } else { _callbackNotificationQueue.Enqueue(rcvdDataInfo); } } if (_suspendQueueServicing && _isDebuggerSuspend) { // Remove debugger queue suspension if remoteObject requires user response. _suspendQueueServicing = !CheckForInteractiveHostCall(remoteObject); } if (_isServicingCallbacks || _suspendQueueServicing) { // a thread pool thread is already processing callbacks or // the queue processing is suspended. return; } if (_callbackNotificationQueue.Count > 0) { _isServicingCallbacks = true; // Start a thread pool thread to process callbacks. #if !UNIX WindowsIdentity identityToImpersonate; Utils.TryGetWindowsImpersonatedIdentity(out identityToImpersonate); Utils.QueueWorkItemWithImpersonation( identityToImpersonate, new WaitCallback(ServicePendingCallbacks), null); #else ThreadPool.QueueUserWorkItem(new WaitCallback(ServicePendingCallbacks)); #endif } } } /// <summary> /// Helper method to check RemoteDataObject for a host call requiring user /// interaction. /// </summary> /// <param name="remoteObject">Remote data object.</param> /// <returns>True if remote data object requires a user response.</returns> private bool CheckForInteractiveHostCall(RemoteDataObject<PSObject> remoteObject) { bool interactiveHostCall = false; if ((remoteObject != null) && (remoteObject.DataType == RemotingDataType.RemoteHostCallUsingPowerShellHost)) { RemoteHostMethodId methodId = 0; try { methodId = RemotingDecoder.GetPropertyValue<RemoteHostMethodId>(remoteObject.Data, RemoteDataNameStrings.MethodId); } catch (PSArgumentNullException) { } catch (PSRemotingDataStructureException) { } // If new remote host call methods are added then we need to evaluate if they are interactive. Dbg.Assert(methodId <= RemoteHostMethodId.PromptForChoiceMultipleSelection, "A new remote host method Id was added. Update switch statement as needed."); switch (methodId) { case RemoteHostMethodId.Prompt: case RemoteHostMethodId.PromptForChoice: case RemoteHostMethodId.PromptForChoiceMultipleSelection: case RemoteHostMethodId.PromptForCredential1: case RemoteHostMethodId.PromptForCredential2: case RemoteHostMethodId.ReadKey: case RemoteHostMethodId.ReadLine: case RemoteHostMethodId.ReadLineAsSecureString: interactiveHostCall = true; break; } } return interactiveHostCall; } internal void ServicePendingCallbacks(object objectToProcess) { tracer.WriteLine("ServicePendingCallbacks thread is starting"); PSEtwLog.ReplaceActivityIdForCurrentThread(RunspacePoolInstanceId, PSEventId.OperationalTransferEventRunspacePool, PSEventId.AnalyticTransferEventRunspacePool, PSKeyword.Transport, PSTask.None); try { while (true) { // if the transport manager is closed return. if (isClosed) { return; } CallbackNotificationInformation rcvdDataInfo = null; lock (_callbackNotificationQueue) { // If queue is empty or if queue servicing is suspended // then break out of loop. if (_callbackNotificationQueue.Count == 0 || _suspendQueueServicing) { break; } rcvdDataInfo = _callbackNotificationQueue.Dequeue(); } // Handle callback. if (rcvdDataInfo != null) { // Handling transport exception in thread-pool thread if (rcvdDataInfo.transportError != null) { RaiseErrorHandler(rcvdDataInfo.transportError); break; } else if (rcvdDataInfo.privateData != null) { ProcessPrivateData(rcvdDataInfo.privateData); } else { base.OnDataAvailableCallback(rcvdDataInfo.remoteObject); } } } } catch (Exception exception) { // This will get executed on a thread pool thread.. // so we need to protect that thread, hence catching // all exceptions tracer.WriteLine("Exception processing data. {0}", exception.Message); PSRemotingTransportException e = new PSRemotingTransportException(exception.Message, exception); TransportErrorOccuredEventArgs eventargs = new TransportErrorOccuredEventArgs(e, TransportMethodEnum.ReceiveShellOutputEx); RaiseErrorHandler(eventargs); return; } finally { lock (_callbackNotificationQueue) { tracer.WriteLine("ServicePendingCallbacks thread is exiting"); _isServicingCallbacks = false; // check if any new runspace request has arrived.. EnqueueAndStartProcessingThread(null, null, null); } } } internal bool IsServicing { get { lock (_callbackNotificationQueue) { return _isServicingCallbacks; } } } internal void SuspendQueue(bool debuggerSuspend = false) { lock (_callbackNotificationQueue) { _isDebuggerSuspend = debuggerSuspend; _suspendQueueServicing = true; } } internal void ResumeQueue() { lock (_callbackNotificationQueue) { _isDebuggerSuspend = false; if (_suspendQueueServicing) { _suspendQueueServicing = false; // Process any items in queue. EnqueueAndStartProcessingThread(null, null, null); } } } /// <summary> /// Used by ServicePendingCallbacks to give the control to derived classes for /// processing data that the base class does not understand. /// </summary> /// <param name="privateData"> /// Derived class specific data to process. For command transport manager this /// should be a boolean. /// </param> internal virtual void ProcessPrivateData(object privateData) { } internal class CallbackNotificationInformation { // only one of the following 2 should be present.. // anyway transportException takes precedence over remoteObject. internal RemoteDataObject<PSObject> remoteObject; internal TransportErrorOccuredEventArgs transportError; // Used by ServicePendingCallbacks to give the control to derived classes for // processing data that the base class does not understand. internal object privateData; } #endregion #region Abstract / Virtual methods internal abstract void CreateAsync(); internal abstract void ConnectAsync(); /// <summary> /// The caller should make sure the call is synchronized. /// </summary> internal virtual void CloseAsync() { // Clear the send collection dataToBeSent.Clear(); } internal virtual void StartReceivingData() { throw new NotImplementedException(); } /// <summary> /// Method to have transport prepare for a disconnect operation. /// </summary> internal virtual void PrepareForDisconnect() { throw new NotImplementedException(); } /// <summary> /// Method to resume post disconnect operations. /// </summary> internal virtual void PrepareForConnect() { throw new NotImplementedException(); } #endregion #region Clean up /// <summary> /// Finalizer. /// </summary> ~BaseClientTransportManager() { if (isClosed) { Dispose(false); } else { // wait for the close to be completed and then release the resources. this.CloseCompleted += (object source, EventArgs args) => Dispose(false); try { // looks like Dispose is not called for this transport manager // try closing the transport manager. CloseAsync(); } catch (ObjectDisposedException) { // intentionally blank } } } internal override void Dispose(bool isDisposing) { // clear event handlers this.CreateCompleted = null; this.CloseCompleted = null; this.ConnectCompleted = null; this.DisconnectCompleted = null; this.ReconnectCompleted = null; // let base dispose its resources. base.Dispose(isDisposing); } #endregion } internal abstract class BaseClientSessionTransportManager : BaseClientTransportManager, IDisposable { #region Constructors protected BaseClientSessionTransportManager(Guid runspaceId, PSRemotingCryptoHelper cryptoHelper) : base(runspaceId, cryptoHelper) { } #endregion #region Abstract / Virtual Methods /// <summary> /// Creates a command transport manager. This will create a new PrioritySendDataCollection which should be used to /// send data to the server. /// </summary> /// <param name="connectionInfo"> /// Connection info to be used for creating the command. /// </param> /// <param name="cmd"> /// Command for which transport manager is created. /// </param> /// <param name="noInput"> /// true if the command has input. /// </param> /// <returns></returns> internal virtual BaseClientCommandTransportManager CreateClientCommandTransportManager(RunspaceConnectionInfo connectionInfo, ClientRemotePowerShell cmd, bool noInput) { throw new NotImplementedException(); } /// <summary> /// RunspacePool data structure handler uses this method to remove association of a command transport manager /// from a session transport manager. /// </summary> /// <param name="powerShellCmdId"></param> internal virtual void RemoveCommandTransportManager(Guid powerShellCmdId) { } /// <summary> /// Temporarily disconnect an active session. /// </summary> internal virtual void DisconnectAsync() { throw new NotImplementedException(); } /// <summary> /// Reconnect back a temporarily disconnected session. /// </summary> internal virtual void ReconnectAsync() { throw new NotImplementedException(); } /// <summary> /// Redirect the transport manager to point to a new URI. /// </summary> /// <param name="newUri"> /// Redirect Uri to connect to. /// </param> /// <param name="connectionInfo"> /// Connection info object used for retrieving credential, auth. mechanism etc. /// </param> internal virtual void Redirect(Uri newUri, RunspaceConnectionInfo connectionInfo) { throw new NotImplementedException(); } /// <summary> /// Used by callers to prepare the session transportmanager for a URI redirection. /// This must be called only after Create callback (or Error form create) is received. /// Callers must catch the close completed event and call Redirect to perform the redirection. /// </summary> internal virtual void PrepareForRedirection() { throw new NotImplementedException(); } #endregion } internal abstract class BaseClientCommandTransportManager : BaseClientTransportManager, IDisposable { #region Private / Protected Data // pipeline in the form cmd1 | cmd2.. this is used by authz module for early validation. protected StringBuilder cmdText; protected SerializedDataStream serializedPipeline; protected Guid powershellInstanceId; protected Guid PowershellInstanceId { get { return powershellInstanceId; } } #endregion internal bool startInDisconnectedMode = false; #region Constructors protected BaseClientCommandTransportManager(ClientRemotePowerShell shell, PSRemotingCryptoHelper cryptoHelper, BaseClientSessionTransportManager sessnTM) : base(sessnTM.RunspacePoolInstanceId, cryptoHelper) { Fragmentor.FragmentSize = sessnTM.Fragmentor.FragmentSize; Fragmentor.TypeTable = sessnTM.Fragmentor.TypeTable; dataToBeSent.Fragmentor = base.Fragmentor; // used for Crimson logging. powershellInstanceId = shell.PowerShell.InstanceId; cmdText = new StringBuilder(); foreach (System.Management.Automation.Runspaces.Command cmd in shell.PowerShell.Commands.Commands) { cmdText.Append(cmd.CommandText); cmdText.Append(" | "); } cmdText.Remove(cmdText.Length - 3, 3); // remove ending " | " RemoteDataObject message; if (shell.PowerShell.IsGetCommandMetadataSpecialPipeline) { message = RemotingEncoder.GenerateGetCommandMetadata(shell); } else { message = RemotingEncoder.GenerateCreatePowerShell(shell); } serializedPipeline = new SerializedDataStream(base.Fragmentor.FragmentSize); Fragmentor.Fragment<object>(message, serializedPipeline); } #endregion #region Events internal event EventHandler<EventArgs> SignalCompleted; internal void RaiseSignalCompleted() { SignalCompleted.SafeInvoke(this, EventArgs.Empty); } #endregion #region Overrides internal override void Dispose(bool isDisposing) { base.Dispose(isDisposing); if (isDisposing) { // dispose serialized pipeline serializedPipeline.Dispose(); } } #endregion #region Abstract / Virtual Methods /// <summary> /// Reconnects a previously disconnected commandTM. Implemented by WSMan transport /// Note that there is not explicit disconnect on commandTM. It is implicity disconnected /// when disconnect is called on sessionTM . The TM's also dont maintain specific connection state /// This is done by DSHandlers. /// </summary> internal virtual void ReconnectAsync() { throw new NotImplementedException(); } /// <summary> /// Used by powershell/pipeline to send a stop message to the server command. /// </summary> internal virtual void SendStopSignal() { throw new NotImplementedException(); } #endregion } } namespace System.Management.Automation.Remoting.Server { /// <summary> /// This represents an abstraction for server transport manager. /// </summary> internal abstract class AbstractServerTransportManager : BaseTransportManager { #region Private Data private readonly object _syncObject = new object(); // used to listen to data available events from serialized datastream. private readonly SerializedDataStream.OnDataAvailableCallback _onDataAvailable; // the following variable are used by onDataAvailableCallback. private bool _shouldFlushData; private bool _reportAsPending; private Guid _runspacePoolInstanceId; private Guid _powerShellInstanceId; private RemotingDataType _dataType; private RemotingTargetInterface _targetInterface; // End: the following variable are used by onDataAvailableCallback. private Queue<Tuple<RemoteDataObject, bool, bool>> _dataToBeSentQueue; private bool _isSerializing; #endregion #region Constructor protected AbstractServerTransportManager(int fragmentSize, PSRemotingCryptoHelper cryptoHelper) : base(cryptoHelper) { base.Fragmentor.FragmentSize = fragmentSize; _onDataAvailable = new SerializedDataStream.OnDataAvailableCallback(OnDataAvailable); } #endregion #region Helper Methods /// <summary> /// Sends an object from the server end. The object is fragmented and each fragment is sent /// separately. The call blocks until all the fragments are sent to the client. If there /// is a failure sending any of the fragments WSManTransportErrorOccured event is raised. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="data"></param> /// <param name="flush"> /// true to immediately send data to client. /// </param> /// <param name="reportPending"> /// reported as true when host message requests are sent to client /// </param> internal void SendDataToClient<T>(RemoteDataObject<T> data, bool flush, bool reportPending = false) { // make sure only one data packet can be sent in its entirety at any // given point of time using this transport manager. lock (_syncObject) { // Win8: 491001 Icm -computername $env:COMPUTERNAME {Get-NetIpInterface} fails with Unexpected ObjectId // This is because the output object has some extended script properties. Getter of one of the // script properties is calling write-progress. Write-Progress in turn results in a progress record // being sent to client. This breaks the fragmentation rule when the original object (without progress) // does not fit in fragmented packet. // ******************** repro using powershell ********************************* // icm . { // $a = new-object psobject // $a.pstypenames.Insert(0, "Microsoft.PowerShell.Test.Bug491001") // Update-TypeData -TypeName Microsoft.PowerShell.Test.Bug491001 -MemberType ScriptProperty -MemberName name -Value {( 1..50kb | % { get-random -min 97 -max 122 | % { [char]$psitem } }) -join ""} // Update-TypeData -TypeName Microsoft.PowerShell.Test.Bug491001 -MemberType ScriptProperty -MemberName Verbose -Value {write-progress "blah" -Completed; "Some verbose data"} // Update-TypeData -TypeName Microsoft.PowerShell.Test.Bug491001 -MemberType ScriptProperty -MemberName zname -Value {( 1..10kb | % { get-random -min 97 -max 122 | % { [char]$psitem } }) -join ""} // $a // } // 1. The value of "name" property is huge 50kb and cannot fit in one fragment (with fragment size 32kb) // 2. The value of "Verbose" is actually writing a progress record // 3. The value of "zname" property is also huge // 4. Notice the ascending order of property names. This is because serializer serializes properties in sort order // ******************** End of repro ****************************************** // To fix the issue, I am creating a Queue and enqueuing the data objects if we are already serializing another data object // Notice this is in lock() above. An object is serialized in its entirety in one thread. So, in my example above "name", // "verbose","zname" properties are serialized in one thread. So lock() essentially protects from serializing other objects // and not this (parent)object. RemoteDataObject dataToBeSent = RemoteDataObject.CreateFrom(data.Destination, data.DataType, data.RunspacePoolId, data.PowerShellId, data.Data); if (_isSerializing) { if (_dataToBeSentQueue == null) { _dataToBeSentQueue = new Queue<Tuple<RemoteDataObject, bool, bool>>(); } _dataToBeSentQueue.Enqueue(new Tuple<RemoteDataObject, bool, bool>(dataToBeSent, flush, reportPending)); return; } _isSerializing = true; try { do { // tell stream to notify us whenever a fragment is available instead of writing data // into internal buffers. This will save write + read + dispose.) using (SerializedDataStream serializedData = new SerializedDataStream(Fragmentor.FragmentSize, _onDataAvailable)) { _shouldFlushData = flush; _reportAsPending = reportPending; _runspacePoolInstanceId = dataToBeSent.RunspacePoolId; _powerShellInstanceId = dataToBeSent.PowerShellId; _dataType = dataToBeSent.DataType; _targetInterface = dataToBeSent.TargetInterface; Fragmentor.Fragment<object>(dataToBeSent, serializedData); } if ((_dataToBeSentQueue != null) && (_dataToBeSentQueue.Count > 0)) { Tuple<RemoteDataObject, bool, bool> dataToBeSentQueueItem = _dataToBeSentQueue.Dequeue(); dataToBeSent = dataToBeSentQueueItem.Item1; flush = dataToBeSentQueueItem.Item2; reportPending = dataToBeSentQueueItem.Item3; } else { dataToBeSent = null; } } while (dataToBeSent != null); } finally { _isSerializing = false; } } } private void OnDataAvailable(byte[] dataToSend, bool isEndFragment) { Dbg.Assert(dataToSend != null, "ServerTransportManager cannot send null fragment"); // log to crimson log. PSEtwLog.LogAnalyticInformational(PSEventId.ServerSendData, PSOpcode.Send, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, _runspacePoolInstanceId.ToString(), _powerShellInstanceId.ToString(), dataToSend.Length.ToString(CultureInfo.InvariantCulture), (UInt32)_dataType, (UInt32)_targetInterface); SendDataToClient(dataToSend, isEndFragment && _shouldFlushData, _reportAsPending, isEndFragment); } /// <summary> /// Sends an object to the server end. The object is fragmented and each fragment is sent /// separately. The call blocks until all the fragments are sent to the client. If there /// is a failure sending any of the fragments WSManTransportErrorOccured event is raised. /// </summary> /// <param name="psObjectData"></param> /// <param name="flush"> /// true to immediately send data to client. /// </param> /// <param name="reportAsPending"> /// reported as true when sending host message requests are reported true /// </param> internal void SendDataToClient(RemoteDataObject psObjectData, bool flush, bool reportAsPending = false) { SendDataToClient<object>((RemoteDataObject<object>)(psObjectData), flush, reportAsPending); } /// <summary> /// Reports error from a thread pool thread. Thread Pool is used in order to /// not block Pipeline closing. This method is generally called when the /// TransportManager fails to Send data (SendDataToClient). Pipeline Execution /// Thread directly calls SendDataToClient method from its execution thread, /// so we cannot call Stop from the same thread (as it will result in a deadlock) /// </summary> internal void ReportError(int errorCode, string methodName) { string messageResource = RemotingErrorIdStrings.GeneralError; string errorMessage = string.Format(CultureInfo.InvariantCulture, messageResource, new object[] { errorCode, methodName }); PSRemotingTransportException e = new PSRemotingTransportException(errorMessage); e.ErrorCode = errorCode; // Use thread-pool thread to raise the error handler..see explanation // in the method summary ThreadPool.QueueUserWorkItem(new WaitCallback( (object state) => { TransportErrorOccuredEventArgs eventArgs = new TransportErrorOccuredEventArgs(e, TransportMethodEnum.Unknown); RaiseErrorHandler(eventArgs); })); } /// <summary> /// Raises the closing event. /// </summary> internal void RaiseClosingEvent() { Closing.SafeInvoke(this, EventArgs.Empty); } #endregion #region Event Handlers /// <summary> /// Event that is raised when this transport manager is closing. /// </summary> internal event EventHandler Closing; #endregion #region Abstract interfaces /// <summary> /// </summary> /// <param name="data"></param> /// <param name="flush"> /// flush data by sending data immediately to the client. /// </param> /// <param name="reportAsPending"> /// reported as true when sending host message requests to client /// </param> /// <param name="reportAsDataBoundary"> /// reported as true when data being reported is as object boundary, i.e the corresponding fragment is an end fragment /// </param> protected abstract void SendDataToClient(byte[] data, bool flush, bool reportAsPending, bool reportAsDataBoundary); /// <summary> /// </summary> internal abstract void ReportExecutionStatusAsRunning(); /// <summary> /// </summary> /// <param name="reasonForClose"> /// message describing why the transport manager must be closed /// </param> internal abstract void Close(Exception reasonForClose); /// <summary> /// Prepare the transport manager to send data (because a command /// is about to start). This is used by underlying infrastructure /// to send ACK to client..so client can start sending input and /// other data to server. /// </summary> internal virtual void Prepare() { // command may hijack the calling thread to run the command // so this method call notifies the ReceivedData buffer to // allow another thread to ProcessRawData. ReceivedDataCollection.AllowTwoThreadsToProcessRawData(); } #endregion } /// <summary> /// This represents an abstraction for server session transport manager. /// </summary> internal abstract class AbstractServerSessionTransportManager : AbstractServerTransportManager { #region Constructors protected AbstractServerSessionTransportManager(int fragmentSize, PSRemotingCryptoHelper cryptoHelper) : base(fragmentSize, cryptoHelper) { } #endregion #region Abstract interfaces /// <summary> /// Server RunspacePool driver uses this method to attach to a server transport manager. /// </summary> /// <param name="powerShellCmdId"></param> /// <returns></returns> internal abstract AbstractServerTransportManager GetCommandTransportManager(Guid powerShellCmdId); /// <summary> /// Server RunspacePool driver uses this method to remove association of a command transport manager /// from a session transport manager. /// </summary> /// <param name="powerShellCmdId"></param> internal abstract void RemoveCommandTransportManager(Guid powerShellCmdId); #endregion } /// <summary> /// A container for helper functions that accomplish common client and server tasks. /// </summary> internal static class ServerOperationHelpers { #region Public Helper Methods /// <summary> /// A helper method to extract a base-64 encoded XML element from a specified input /// buffer. The calls required are not compatible with the Managed C++ CoreCLR /// mscorlib, but this operation is supported as managed C# code. /// </summary> /// <param name="xmlBuffer">The input buffer to search. It must be base-64 encoded XML.</param> /// <param name="xmlTag">The XML tag used to identify the value to extract.</param> /// <returns>The extracted tag converted from a base-64 string.</returns> internal static byte[] ExtractEncodedXmlElement(string xmlBuffer, string xmlTag) { if (xmlBuffer == null || xmlTag == null) return new byte[1]; // the inboundShellInformation is in Xml format as per the SOAP WSMan spec. // Retrieve the string (Base64 encoded) we are interested in. XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.CheckCharacters = false; readerSettings.IgnoreComments = true; readerSettings.IgnoreProcessingInstructions = true; readerSettings.XmlResolver = null; readerSettings.ConformanceLevel = ConformanceLevel.Fragment; readerSettings.MaxCharactersFromEntities = 1024; readerSettings.DtdProcessing = System.Xml.DtdProcessing.Prohibit; XmlReader reader = XmlReader.Create(new StringReader(xmlBuffer), readerSettings); string additionalData; if (reader.MoveToContent() == XmlNodeType.Element) { additionalData = reader.ReadElementContentAsString(xmlTag, reader.NamespaceURI); } else // No element found, so return a default value { return new byte[1]; } return Convert.FromBase64String(additionalData); } #endregion } }
39.77547
219
0.596845
[ "MIT" ]
wbhsm/PowerShell
src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs
61,294
C#
namespace BizHawk.Client.EmuHawk { partial class QuickNesConfig { /// <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() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(QuickNesConfig)); this.propertyGrid1 = new System.Windows.Forms.PropertyGrid(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.buttonOK = new System.Windows.Forms.Button(); this.buttonCancel = new System.Windows.Forms.Button(); this.buttonPal = new System.Windows.Forms.Button(); this.buttonPalReset = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.groupBox1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.SuspendLayout(); // // propertyGrid1 // this.propertyGrid1.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.propertyGrid1.Location = new System.Drawing.Point(12, 12); this.propertyGrid1.Name = "propertyGrid1"; this.propertyGrid1.PropertySort = System.Windows.Forms.PropertySort.Alphabetical; this.propertyGrid1.Size = new System.Drawing.Size(465, 189); this.propertyGrid1.TabIndex = 0; this.propertyGrid1.ToolbarVisible = false; // // groupBox1 // this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.groupBox1.Controls.Add(this.pictureBox1); this.groupBox1.Location = new System.Drawing.Point(12, 207); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(465, 156); this.groupBox1.TabIndex = 1; this.groupBox1.TabStop = false; this.groupBox1.Text = "Palette Preview:"; // // pictureBox1 // this.pictureBox1.Location = new System.Drawing.Point(6, 19); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(453, 131); this.pictureBox1.TabIndex = 0; this.pictureBox1.TabStop = false; // // buttonOK // this.buttonOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonOK.Location = new System.Drawing.Point(321, 369); this.buttonOK.Name = "buttonOK"; this.buttonOK.Size = new System.Drawing.Size(75, 23); this.buttonOK.TabIndex = 2; this.buttonOK.Text = "OK"; this.buttonOK.UseVisualStyleBackColor = true; this.buttonOK.Click += new System.EventHandler(this.ButtonOk_Click); // // buttonCancel // this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.buttonCancel.Location = new System.Drawing.Point(402, 369); this.buttonCancel.Name = "buttonCancel"; this.buttonCancel.Size = new System.Drawing.Size(75, 23); this.buttonCancel.TabIndex = 3; this.buttonCancel.Text = "Cancel"; this.buttonCancel.UseVisualStyleBackColor = true; // // buttonPal // this.buttonPal.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.buttonPal.Location = new System.Drawing.Point(61, 369); this.buttonPal.Name = "buttonPal"; this.buttonPal.Size = new System.Drawing.Size(75, 23); this.buttonPal.TabIndex = 4; this.buttonPal.Text = "Browse..."; this.buttonPal.UseVisualStyleBackColor = true; this.buttonPal.Click += new System.EventHandler(this.ButtonPal_Click); // // buttonPalReset // this.buttonPalReset.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.buttonPalReset.Location = new System.Drawing.Point(142, 369); this.buttonPalReset.Name = "buttonPalReset"; this.buttonPalReset.Size = new System.Drawing.Size(151, 23); this.buttonPalReset.TabIndex = 5; this.buttonPalReset.Text = "Reset to QuickNES Default"; this.buttonPalReset.UseVisualStyleBackColor = true; this.buttonPalReset.Click += new System.EventHandler(this.ButtonPalReset_Click); // // label1 // this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(12, 374); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(43, 13); this.label1.TabIndex = 6; this.label1.Text = "Palette:"; // // QuickNesConfig // this.AcceptButton = this.buttonOK; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.buttonCancel; this.ClientSize = new System.Drawing.Size(489, 404); this.Controls.Add(this.label1); this.Controls.Add(this.buttonPalReset); this.Controls.Add(this.buttonPal); this.Controls.Add(this.buttonCancel); this.Controls.Add(this.buttonOK); this.Controls.Add(this.groupBox1); this.Controls.Add(this.propertyGrid1); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MinimumSize = new System.Drawing.Size(390, 285); this.Name = "QuickNesConfig"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "NES Graphics Settings"; this.Load += new System.EventHandler(this.QuickNesConfig_Load); this.groupBox1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.PropertyGrid propertyGrid1; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Button buttonOK; private System.Windows.Forms.Button buttonCancel; private System.Windows.Forms.Button buttonPal; private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.Button buttonPalReset; private System.Windows.Forms.Label label1; } }
42.672619
155
0.727856
[ "MIT" ]
CognitiaAI/StreetFighterRL
emulator/Bizhawk/BizHawk-master/BizHawk.Client.EmuHawk/config/NES/QuickNesConfig.Designer.cs
7,171
C#
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace TW.Vault.Lib { public class ASPUtil { public IWebHostEnvironment HostingEnvironment { get; private set; } String basePath; public ASPUtil(IWebHostEnvironment hostingEnvironment, String basePath = "") { this.HostingEnvironment = hostingEnvironment; this.basePath = basePath; } public bool UseProductionScripts => HostingEnvironment.IsProduction() || Configuration.Security.ForceEnableObfuscatedScripts; public String ObfuscationPathRoot => Path.Combine(HostingEnvironment.ContentRootPath, Configuration.Initialization.ScriptCompilationOutputPath); public String GetFilePath(String relativePath) { if (String.IsNullOrWhiteSpace(relativePath)) return null; String rootPath = Path.Combine(HostingEnvironment.WebRootPath, basePath); String fullPath = Path.Combine(rootPath, relativePath); String absolutePath = Path.GetFullPath(fullPath); // Prevent directory traversal if (!absolutePath.StartsWith(rootPath)) return null; if (File.Exists(absolutePath)) return absolutePath; else return absolutePath; } public String GetObfuscatedPath(String fileName) => Path.Combine(ObfuscationPathRoot, fileName); } }
33.125
152
0.674843
[ "MIT-0" ]
gandalfleal/twvault
app/TW.Vault.Lib/ASPUtil.cs
1,592
C#
using Contracts.Commands.Bets; using GreenPipes; using MassTransit; using Microservice1.Buss; using Microservice1.Consumers.Bets; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using System; namespace Microservice1 { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(); } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddScoped<CreateBetConsumer>(); services.AddMassTransit(x => { x.AddConsumer<CreateBetConsumer>(); }); services.AddSingleton(provider => Bus.Factory.CreateUsingRabbitMq(cfg => { var host = cfg.Host(new Uri("rabbitmq://localhost/"), hostConfigurator => { hostConfigurator.Username("guest"); hostConfigurator.Password("guest"); }); cfg.ReceiveEndpoint(host, "create_bet", e => { e.PrefetchCount = 16; e.UseMessageRetry(mr => mr.Interval(2, 100)); // e.PurgeOnStartup = true; e.Consumer<CreateBetConsumer>(provider); }); })); services.AddSingleton<IBus>(provider => provider.GetRequiredService<IBusControl>()); services.AddScoped(provider => provider.GetRequiredService<IBus>().CreateRequestClient<ICreateBetCommand>()); services.AddSingleton<Microsoft.Extensions.Hosting.IHostedService, BusService>(); } } }
33.577465
121
0.604866
[ "MIT" ]
DiegoTavaresF/MicroserviceComunicationWithMassTransitAndRabbitMQ
Microservice1/Startup.cs
2,386
C#
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using MusicApp.DAL; using MusicApp.Models; namespace MusicApp.Controllers { public class ArtistsController : Controller { private MusicContext db = new MusicContext(); // GET: Artists public ActionResult Index() { return View(db.Artists.ToList()); } // GET: Artists/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Artist artist = db.Artists.Find(id); if (artist == null) { return HttpNotFound(); } return View(artist); } // GET: Artists/Create public ActionResult Create() { return View(); } // POST: Artists/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "ID,Href,Name,Popularity")] Artist artist) { if (ModelState.IsValid) { db.Artists.Add(artist); db.SaveChanges(); return RedirectToAction("Index"); } return View(artist); } // GET: Artists/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Artist artist = db.Artists.Find(id); if (artist == null) { return HttpNotFound(); } return View(artist); } // POST: Artists/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "ID,Href,Name,Popularity")] Artist artist) { if (ModelState.IsValid) { db.Entry(artist).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(artist); } // GET: Artists/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Artist artist = db.Artists.Find(id); if (artist == null) { return HttpNotFound(); } return View(artist); } // POST: Artists/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { Artist artist = db.Artists.Find(id); db.Artists.Remove(artist); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
28.093023
111
0.521523
[ "MIT" ]
meiordac/MusicApp
MusicApp/Controllers/ArtistsController.cs
3,626
C#
using System; using System.Collections.Generic; using System.Linq; using DeepMatch; using NUnit.Framework; namespace Tests { [TestFixture] public class GenericFixture { private readonly IEnumerable<int> _sequence1To50 = Enumerable.Range(1, 50); private readonly IEnumerable<int> _sequence1To10 = Enumerable.Range(1, 10); private readonly IEnumerable<int> _sequence1To2 = Enumerable.Range(1, 2); private readonly IEnumerable<int> _sequence1To1 = Enumerable.Range(1, 1); private readonly IEnumerable<int> _sequenceEmpty = Enumerable.Empty<int>(); private ListMatcher<int, int> _sumRecursiveMatcher; private ListMatcher<int, int> _sumRecursiveMatcherNoEmpty; [SetUp] public void SetUp() { ListMatcher<int, int> matcher = null; matcher = new ListMatcher<int, int>() .When((_, __) => true, (head, tail) => head[0] + matcher.Run(tail)) .WhenEmpty(() => 0); _sumRecursiveMatcher = matcher; ListMatcher<int, int> matcher2 = null; matcher2 = new ListMatcher<int, int>() .When((_, __) => true, (head, tail) => head[0] + matcher2.Run(tail)); _sumRecursiveMatcherNoEmpty = matcher2; } #region Deep matching /// <summary> /// Tests for matching more than one sequential elements /// </summary> [Test] public void DeepMatch_ManyMatchBlocks_MatchingBlockFirst_Test() { var result = new ListMatcher<int, int>() .When((i, _) => i == 1 && _((i1, __) => i1 == 2), (_, __) => 1) .When((i, _) => i == 0 && _((i1, __) => i1 == 1), (_, __) => 0) .Run(_sequence1To10.GetEnumerator()); Assert.That(result, Is.EqualTo(1)); } [Test] public void DeepMatch_ManyMatchBlocks_MatchingBlockLast_Test() { var result = new ListMatcher<int, int>() .When((i, _) => i == 0 && _((i1, __) => i1 == 1), (_, __) => 0) .When((i, _) => i == 1 && _((i1, __) => i1 == 2), (_, __) => 1) .Run(_sequence1To10.GetEnumerator()); Assert.That(result, Is.EqualTo(1)); } [Test] [TestCaseSource("DeepMatchTestCases")] public void DeepMatchTest(Tuple<MatchFunc<int>, IEnumerable<int>, IEnumerable<int>> input) { var heads = Enumerable.Empty<int>(); var tail = Enumerable.Empty<int>(); var result = new ListMatcher<int, int>() .When(input.Item1, (h, t) => { heads = h; tail = t.AsEnumerable(); return 0; }) .Run(_sequence1To50.GetEnumerator()); Assert.That(heads, Is.EqualTo(input.Item2)); Assert.That(tail, Is.EqualTo(input.Item3)); } public IEnumerable<Tuple<MatchFunc<int>, IEnumerable<int>, IEnumerable<int>>> DeepMatchTestCases { get { yield return GenerateDeepMatchTestCase<int>( 1, (i, t) => i == 1 ); yield return GenerateDeepMatchTestCase<int>( 5, (i1, t1) => i1 == 1 && t1((i2, t2) => i2 == 2 && t2((i3, t3) => i3 == 3 && t3((i4, t4) => i4 == 4 && t4((i5, _) => i5 == 5)))) ); } } private Tuple<MatchFunc<T>, IEnumerable<int>, IEnumerable<int>> GenerateDeepMatchTestCase<T>(int count, MatchFunc<T> matchFunc) { return new Tuple<MatchFunc<T>, IEnumerable<int>, IEnumerable<int>>( matchFunc, Enumerable.Range(1, count), _sequence1To50.Skip(count) ); } #endregion #region Usual cases [Test] public void SimpleMatchTest() { var result = new ListMatcher<int, int>() .When((i, _) => i == 1 , (_, __) => 42) .Run(_sequence1To10.GetEnumerator()); Assert.That(result, Is.EqualTo(42)); } [Test] public void EmptySequenceMatchTest() { var result = new ListMatcher<int, int>() .When((i, _) => i == 0, (_, __) => 42) .WhenEmpty(() => 11) .Run(_sequenceEmpty.GetEnumerator()); Assert.That(result, Is.EqualTo(11)); } [Test] public void ManyMatchBlocks_MatchingBlockFirst_Test() { var result = new ListMatcher<int, int>() .When((i, _) => i == 1, (_, __) => 1) .When((i, _) => i == 0, (_, __) => 0) .When((i, _) => i == 2, (_, __) => 2) .When((i, _) => i == 3, (_, __) => 3) .Run(_sequence1To10.GetEnumerator()); Assert.That(result, Is.EqualTo(1)); } [Test] public void ManyMatchBlocks_MatchingBlockLast_Test() { var result = new ListMatcher<int, int>() .When((i, _) => i == 3, (_, __) => 3) .When((i, _) => i == 2, (_, __) => 2) .When((i, _) => i == 1, (_, __) => 1) .Run(_sequence1To10.GetEnumerator()); Assert.That(result, Is.EqualTo(1)); } #endregion #region Heads and tails tests [Test] public void TwoCloseMatchBlocks_HeadsShouldNotBePolluted_Test() { var result = new ListMatcher<int, int[]>() .When((i, t1) => i == 1 && t1((j, t2) => j == 2 && t2((k, _) => k == 4)), (heads, __) => heads) .When((i, t1) => i == 1 && t1((j, t2) => j == 2 && t2((k, _) => k == 3)), (heads, __) => heads) .Run(_sequence1To10.GetEnumerator()); var expected = new[]{1, 2, 3}; Assert.That(result, Is.EqualTo(expected)); } #endregion #region No match tests [Test] [ExpectedException(typeof(MatchException))] public void MoMatchTest_Hardcore() { new ListMatcher<int, int>() .When((i, t) => false, (_, __) => 0) .Run(_sequence1To10.GetEnumerator()); } [Test] [ExpectedException(typeof(MatchException))] public void MoMatchTest_NoEmptyStub_NonEmptySequence() { _sumRecursiveMatcherNoEmpty.Run(_sequence1To10.GetEnumerator()); } [Test] [ExpectedException(typeof(MatchException))] public void MoMatchTest_NoEmptyStub_EmptySequence() { _sumRecursiveMatcherNoEmpty.Run(_sequenceEmpty.GetEnumerator()); } #endregion #region Recursion tests [Test] [TestCaseSource("RecursionTestsSum")] public void RecursionTest_Sum(Tuple<IEnumerable<int>, int> input) { var result = _sumRecursiveMatcher.Run(input.Item1.GetEnumerator()); Assert.That(result, Is.EqualTo(input.Item2)); } private IEnumerable<Tuple<IEnumerable<int>, int>> RecursionTestsSum { get { yield return new Tuple<IEnumerable<int>, int>(_sequence1To50, _sequence1To50.Sum()); yield return new Tuple<IEnumerable<int>, int>(_sequence1To10, _sequence1To10.Sum()); yield return new Tuple<IEnumerable<int>, int>(_sequence1To2, _sequence1To2.Sum()); yield return new Tuple<IEnumerable<int>, int>(_sequence1To1, _sequence1To1.Sum()); yield return new Tuple<IEnumerable<int>, int>(_sequenceEmpty, _sequenceEmpty.Sum()); } } #endregion } }
25.935223
105
0.626132
[ "MIT" ]
GrafGenerator/DeepMatch
test/GenericFixture.cs
6,408
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; namespace TaskManager.SystemRuntime { /// <summary> /// 任务配置信息,类似app.config中的配置,仅支持字典 /// 正式环境在任务调度平台中配置获取 /// 测试环境需要自己重新创建实例赋值 /// </summary> [Serializable] public class TaskAppConfigInfo:Dictionary<string,string> { public TaskAppConfigInfo():base() { } //父类实现了ISerializable接口的,子类也必须有序列化构造函数,否则反序列化时会出错。 protected TaskAppConfigInfo(SerializationInfo info, StreamingContext context) : base(info, context) { } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); } } }
24.875
92
0.66206
[ "Apache-2.0" ]
vongzh/TaskManager
TaskManager/SystemRuntime/TaskAppConfigInfo.cs
968
C#
// -------------------------------------------------------------------------------------------- // <copyright file="ResultSetComposerMock.cs" company="Effort Team"> // Copyright (C) Effort Team // // 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. // </copyright> // -------------------------------------------------------------------------------------------- namespace Effort.Test.Internal.Fakes { using System.Collections.Generic; using Effort.Test.Internal.ResultSets; internal class ResultSetComposerMock : IResultSetComposer { private int commitCounter; private int setValueCounter; private HashSet<string> currentItem; public ResultSetComposerMock() { this.currentItem = new HashSet<string>(); this.commitCounter = 0; this.setValueCounter = 0; } public IResultSet ResultSet { get { return null; } } public int CommitCount { get { return this.commitCounter; } } public int SetValueCount { get { return this.setValueCounter; } } public void SetValue<T>(string name, T value) { if (this.currentItem.Add(name)) { this.setValueCounter++; } } public void Commit() { this.commitCounter++; this.currentItem.Clear(); } } }
35.173333
97
0.566338
[ "MIT" ]
HydAu/EFeffort
Main/Source/Effort.Test/Internal/Fakes/ResultSetComposerMock.cs
2,640
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Diagnostics; using System.Linq; using System.Reactive.Disposables; using System.Text; using Avalonia.Controls; using Avalonia.Controls.Platform; using Avalonia.Controls.Primitives.PopupPositioning; using Avalonia.FreeDesktop; using Avalonia.Input; using Avalonia.Input.Raw; using Avalonia.OpenGL; using Avalonia.Platform; using Avalonia.Rendering; using Avalonia.Threading; using Avalonia.X11.Glx; using static Avalonia.X11.XLib; // ReSharper disable IdentifierTypo // ReSharper disable StringLiteralTypo namespace Avalonia.X11 { unsafe class X11Window : IWindowImpl, IPopupImpl, IXI2Client, ITopLevelImplWithNativeMenuExporter, ITopLevelImplWithNativeControlHost { private readonly AvaloniaX11Platform _platform; private readonly IWindowImpl _popupParent; private readonly bool _popup; private readonly X11Info _x11; private XConfigureEvent? _configure; private PixelPoint? _configurePoint; private bool _triggeredExpose; private IInputRoot _inputRoot; private readonly MouseDevice _mouse; private readonly TouchDevice _touch; private readonly IKeyboardDevice _keyboard; private PixelPoint? _position; private PixelSize _realSize; private IntPtr _handle; private IntPtr _xic; private IntPtr _renderHandle; private bool _mapped; private bool _wasMappedAtLeastOnce = false; private double? _scalingOverride; private bool _disabled; private TransparencyHelper _transparencyHelper; public object SyncRoot { get; } = new object(); class InputEventContainer { public RawInputEventArgs Event; } private readonly Queue<InputEventContainer> _inputQueue = new Queue<InputEventContainer>(); private InputEventContainer _lastEvent; private bool _useRenderWindow = false; public X11Window(AvaloniaX11Platform platform, IWindowImpl popupParent) { _platform = platform; _popup = popupParent != null; _x11 = platform.Info; _mouse = new MouseDevice(); _touch = new TouchDevice(); _keyboard = platform.KeyboardDevice; var glfeature = AvaloniaLocator.Current.GetService<IWindowingPlatformGlFeature>(); XSetWindowAttributes attr = new XSetWindowAttributes(); var valueMask = default(SetWindowValuemask); attr.backing_store = 1; attr.bit_gravity = Gravity.NorthWestGravity; attr.win_gravity = Gravity.NorthWestGravity; valueMask |= SetWindowValuemask.BackPixel | SetWindowValuemask.BorderPixel | SetWindowValuemask.BackPixmap | SetWindowValuemask.BackingStore | SetWindowValuemask.BitGravity | SetWindowValuemask.WinGravity; if (_popup) { attr.override_redirect = true; valueMask |= SetWindowValuemask.OverrideRedirect; } XVisualInfo? visualInfo = null; // OpenGL seems to be do weird things to it's current window which breaks resize sometimes _useRenderWindow = glfeature != null; var glx = glfeature as GlxGlPlatformFeature; if (glx != null) visualInfo = *glx.Display.VisualInfo; else if (glfeature == null) visualInfo = _x11.TransparentVisualInfo; var egl = glfeature as EglGlPlatformFeature; var visual = IntPtr.Zero; var depth = 24; if (visualInfo != null) { visual = visualInfo.Value.visual; depth = (int)visualInfo.Value.depth; attr.colormap = XCreateColormap(_x11.Display, _x11.RootWindow, visualInfo.Value.visual, 0); valueMask |= SetWindowValuemask.ColorMap; } int defaultWidth = 0, defaultHeight = 0; if (!_popup && Screen != null) { var monitor = Screen.AllScreens.OrderBy(x => x.PixelDensity) .FirstOrDefault(m => m.Bounds.Contains(Position)); if (monitor != null) { // Emulate Window 7+'s default window size behavior. defaultWidth = (int)(monitor.WorkingArea.Width * 0.75d); defaultHeight = (int)(monitor.WorkingArea.Height * 0.7d); } } // check if the calculated size is zero then compensate to hardcoded resolution defaultWidth = Math.Max(defaultWidth, 300); defaultHeight = Math.Max(defaultHeight, 200); _handle = XCreateWindow(_x11.Display, _x11.RootWindow, 10, 10, defaultWidth, defaultHeight, 0, depth, (int)CreateWindowArgs.InputOutput, visual, new UIntPtr((uint)valueMask), ref attr); if (_useRenderWindow) _renderHandle = XCreateWindow(_x11.Display, _handle, 0, 0, defaultWidth, defaultHeight, 0, depth, (int)CreateWindowArgs.InputOutput, visual, new UIntPtr((uint)(SetWindowValuemask.BorderPixel | SetWindowValuemask.BitGravity | SetWindowValuemask.WinGravity | SetWindowValuemask.BackingStore)), ref attr); else _renderHandle = _handle; Handle = new PlatformHandle(_handle, "XID"); _realSize = new PixelSize(defaultWidth, defaultHeight); platform.Windows[_handle] = OnEvent; XEventMask ignoredMask = XEventMask.SubstructureRedirectMask | XEventMask.ResizeRedirectMask | XEventMask.PointerMotionHintMask; if (platform.XI2 != null) ignoredMask |= platform.XI2.AddWindow(_handle, this); var mask = new IntPtr(0xffffff ^ (int)ignoredMask); XSelectInput(_x11.Display, _handle, mask); var protocols = new[] { _x11.Atoms.WM_DELETE_WINDOW }; XSetWMProtocols(_x11.Display, _handle, protocols, protocols.Length); XChangeProperty(_x11.Display, _handle, _x11.Atoms._NET_WM_WINDOW_TYPE, _x11.Atoms.XA_ATOM, 32, PropertyMode.Replace, new[] {_x11.Atoms._NET_WM_WINDOW_TYPE_NORMAL}, 1); if (platform.Options.WmClass != null) SetWmClass(platform.Options.WmClass); var surfaces = new List<object> { new X11FramebufferSurface(_x11.DeferredDisplay, _renderHandle, depth, () => Scaling) }; if (egl != null) surfaces.Insert(0, new EglGlPlatformSurface(egl.DeferredContext, new SurfaceInfo(this, _x11.DeferredDisplay, _handle, _renderHandle))); if (glx != null) surfaces.Insert(0, new GlxGlPlatformSurface(glx.Display, glx.DeferredContext, new SurfaceInfo(this, _x11.Display, _handle, _renderHandle))); Surfaces = surfaces.ToArray(); UpdateMotifHints(); UpdateSizeHints(null); _xic = XCreateIC(_x11.Xim, XNames.XNInputStyle, XIMProperties.XIMPreeditNothing | XIMProperties.XIMStatusNothing, XNames.XNClientWindow, _handle, IntPtr.Zero); _transparencyHelper = new TransparencyHelper(_x11, _handle, platform.Globals); _transparencyHelper.SetTransparencyRequest(WindowTransparencyLevel.None); XFlush(_x11.Display); if(_popup) PopupPositioner = new ManagedPopupPositioner(new ManagedPopupPositionerPopupImplHelper(popupParent, MoveResize)); if (platform.Options.UseDBusMenu) NativeMenuExporter = DBusMenuExporter.TryCreate(_handle); NativeControlHost = new X11NativeControlHost(_platform, this); } class SurfaceInfo : EglGlPlatformSurface.IEglWindowGlPlatformSurfaceInfo { private readonly X11Window _window; private readonly IntPtr _display; private readonly IntPtr _parent; public SurfaceInfo(X11Window window, IntPtr display, IntPtr parent, IntPtr xid) { _window = window; _display = display; _parent = parent; Handle = xid; } public IntPtr Handle { get; } public PixelSize Size { get { XLockDisplay(_display); XGetGeometry(_display, _parent, out var geo); XResizeWindow(_display, Handle, geo.width, geo.height); XUnlockDisplay(_display); return new PixelSize(geo.width, geo.height); } } public double Scaling => _window.Scaling; } void UpdateMotifHints() { var functions = MotifFunctions.Move | MotifFunctions.Close | MotifFunctions.Resize | MotifFunctions.Minimize | MotifFunctions.Maximize; var decorations = MotifDecorations.Menu | MotifDecorations.Title | MotifDecorations.Border | MotifDecorations.Maximize | MotifDecorations.Minimize | MotifDecorations.ResizeH; if (_popup || _systemDecorations == SystemDecorations.None) decorations = 0; if (!_canResize) { functions &= ~(MotifFunctions.Resize | MotifFunctions.Maximize); decorations &= ~(MotifDecorations.Maximize | MotifDecorations.ResizeH); } var hints = new MotifWmHints { flags = new IntPtr((int)(MotifFlags.Decorations | MotifFlags.Functions)), decorations = new IntPtr((int)decorations), functions = new IntPtr((int)functions) }; XChangeProperty(_x11.Display, _handle, _x11.Atoms._MOTIF_WM_HINTS, _x11.Atoms._MOTIF_WM_HINTS, 32, PropertyMode.Replace, ref hints, 5); } void UpdateSizeHints(PixelSize? preResize) { var min = _minMaxSize.minSize; var max = _minMaxSize.maxSize; if (!_canResize) max = min = _realSize; if (preResize.HasValue) { var desired = preResize.Value; max = new PixelSize(Math.Max(desired.Width, max.Width), Math.Max(desired.Height, max.Height)); min = new PixelSize(Math.Min(desired.Width, min.Width), Math.Min(desired.Height, min.Height)); } var hints = new XSizeHints { min_width = min.Width, min_height = min.Height }; hints.height_inc = hints.width_inc = 1; var flags = XSizeHintsFlags.PMinSize | XSizeHintsFlags.PResizeInc; // People might be passing double.MaxValue if (max.Width < 100000 && max.Height < 100000) { hints.max_width = max.Width; hints.max_height = max.Height; flags |= XSizeHintsFlags.PMaxSize; } hints.flags = (IntPtr)flags; XSetWMNormalHints(_x11.Display, _handle, ref hints); } public Size ClientSize => new Size(_realSize.Width / Scaling, _realSize.Height / Scaling); public double Scaling { get { lock (SyncRoot) return _scaling; } private set => _scaling = value; } public IEnumerable<object> Surfaces { get; } public Action<RawInputEventArgs> Input { get; set; } public Action<Rect> Paint { get; set; } public Action<Size> Resized { get; set; } //TODO public Action<double> ScalingChanged { get; set; } public Action Deactivated { get; set; } public Action Activated { get; set; } public Func<bool> Closing { get; set; } public Action<WindowState> WindowStateChanged { get; set; } public Action<WindowTransparencyLevel> TransparencyLevelChanged { get => _transparencyHelper.TransparencyLevelChanged; set => _transparencyHelper.TransparencyLevelChanged = value; } public Action Closed { get; set; } public Action<PixelPoint> PositionChanged { get; set; } public Action LostFocus { get; set; } public IRenderer CreateRenderer(IRenderRoot root) { var loop = AvaloniaLocator.Current.GetService<IRenderLoop>(); return _platform.Options.UseDeferredRendering ? new DeferredRenderer(root, loop) : (IRenderer)new X11ImmediateRendererProxy(root, loop); } void OnEvent(XEvent ev) { lock (SyncRoot) OnEventSync(ev); } void OnEventSync(XEvent ev) { if(XFilterEvent(ref ev, _handle)) return; if (ev.type == XEventName.MapNotify) { _mapped = true; if (_useRenderWindow) XMapWindow(_x11.Display, _renderHandle); } else if (ev.type == XEventName.UnmapNotify) _mapped = false; else if (ev.type == XEventName.Expose || (ev.type == XEventName.VisibilityNotify && ev.VisibilityEvent.state < 2)) { if (!_triggeredExpose) { _triggeredExpose = true; Dispatcher.UIThread.Post(() => { _triggeredExpose = false; DoPaint(); }, DispatcherPriority.Render); } } else if (ev.type == XEventName.FocusIn) { if (ActivateTransientChildIfNeeded()) return; Activated?.Invoke(); } else if (ev.type == XEventName.FocusOut) Deactivated?.Invoke(); else if (ev.type == XEventName.MotionNotify) MouseEvent(RawPointerEventType.Move, ref ev, ev.MotionEvent.state); else if (ev.type == XEventName.LeaveNotify) MouseEvent(RawPointerEventType.LeaveWindow, ref ev, ev.CrossingEvent.state); else if (ev.type == XEventName.PropertyNotify) { OnPropertyChange(ev.PropertyEvent.atom, ev.PropertyEvent.state == 0); } else if (ev.type == XEventName.ButtonPress) { if (ActivateTransientChildIfNeeded()) return; if (ev.ButtonEvent.button < 4 || ev.ButtonEvent.button == 8 || ev.ButtonEvent.button == 9) MouseEvent( ev.ButtonEvent.button switch { 1 => RawPointerEventType.LeftButtonDown, 2 => RawPointerEventType.MiddleButtonDown, 3 => RawPointerEventType.RightButtonDown, 8 => RawPointerEventType.XButton1Down, 9 => RawPointerEventType.XButton2Down }, ref ev, ev.ButtonEvent.state); else { var delta = ev.ButtonEvent.button == 4 ? new Vector(0, 1) : ev.ButtonEvent.button == 5 ? new Vector(0, -1) : ev.ButtonEvent.button == 6 ? new Vector(1, 0) : new Vector(-1, 0); ScheduleInput(new RawMouseWheelEventArgs(_mouse, (ulong)ev.ButtonEvent.time.ToInt64(), _inputRoot, new Point(ev.ButtonEvent.x, ev.ButtonEvent.y), delta, TranslateModifiers(ev.ButtonEvent.state)), ref ev); } } else if (ev.type == XEventName.ButtonRelease) { if (ev.ButtonEvent.button < 4 || ev.ButtonEvent.button == 8 || ev.ButtonEvent.button == 9) MouseEvent( ev.ButtonEvent.button switch { 1 => RawPointerEventType.LeftButtonUp, 2 => RawPointerEventType.MiddleButtonUp, 3 => RawPointerEventType.RightButtonUp, 8 => RawPointerEventType.XButton1Up, 9 => RawPointerEventType.XButton2Up }, ref ev, ev.ButtonEvent.state); } else if (ev.type == XEventName.ConfigureNotify) { if (ev.ConfigureEvent.window != _handle) return; var needEnqueue = (_configure == null); _configure = ev.ConfigureEvent; if (ev.ConfigureEvent.override_redirect || ev.ConfigureEvent.send_event) _configurePoint = new PixelPoint(ev.ConfigureEvent.x, ev.ConfigureEvent.y); else { XTranslateCoordinates(_x11.Display, _handle, _x11.RootWindow, 0, 0, out var tx, out var ty, out _); _configurePoint = new PixelPoint(tx, ty); } if (needEnqueue) Dispatcher.UIThread.Post(() => { if (_configure == null) return; var cev = _configure.Value; var npos = _configurePoint.Value; _configure = null; _configurePoint = null; var nsize = new PixelSize(cev.width, cev.height); var changedSize = _realSize != nsize; var changedPos = _position == null || npos != _position; _realSize = nsize; _position = npos; bool updatedSizeViaScaling = false; if (changedPos) { PositionChanged?.Invoke(npos); updatedSizeViaScaling = UpdateScaling(); } if (changedSize && !updatedSizeViaScaling && !_popup) Resized?.Invoke(ClientSize); Dispatcher.UIThread.RunJobs(DispatcherPriority.Layout); }, DispatcherPriority.Layout); if (_useRenderWindow) XConfigureResizeWindow(_x11.Display, _renderHandle, ev.ConfigureEvent.width, ev.ConfigureEvent.height); } else if (ev.type == XEventName.DestroyNotify && ev.AnyEvent.window == _handle) { Cleanup(); } else if (ev.type == XEventName.ClientMessage) { if (ev.ClientMessageEvent.message_type == _x11.Atoms.WM_PROTOCOLS) { if (ev.ClientMessageEvent.ptr1 == _x11.Atoms.WM_DELETE_WINDOW) { if (Closing?.Invoke() != true) Dispose(); } } } else if (ev.type == XEventName.KeyPress || ev.type == XEventName.KeyRelease) { if (ActivateTransientChildIfNeeded()) return; var buffer = stackalloc byte[40]; var index = ev.KeyEvent.state.HasFlag(XModifierMask.ShiftMask); // We need the latin key, since it's mainly used for hotkeys, we use a different API for text anyway var key = (X11Key)XKeycodeToKeysym(_x11.Display, ev.KeyEvent.keycode, index ? 1 : 0).ToInt32(); // Manually switch the Shift index for the keypad, // there should be a proper way to do this if (ev.KeyEvent.state.HasFlag(XModifierMask.Mod2Mask) && key > X11Key.Num_Lock && key <= X11Key.KP_9) key = (X11Key)XKeycodeToKeysym(_x11.Display, ev.KeyEvent.keycode, index ? 0 : 1).ToInt32(); ScheduleInput(new RawKeyEventArgs(_keyboard, (ulong)ev.KeyEvent.time.ToInt64(), _inputRoot, ev.type == XEventName.KeyPress ? RawKeyEventType.KeyDown : RawKeyEventType.KeyUp, X11KeyTransform.ConvertKey(key), TranslateModifiers(ev.KeyEvent.state)), ref ev); if (ev.type == XEventName.KeyPress) { var len = Xutf8LookupString(_xic, ref ev, buffer, 40, out _, out _); if (len != 0) { var text = Encoding.UTF8.GetString(buffer, len); if (text.Length == 1) { if (text[0] < ' ' || text[0] == 0x7f) //Control codes or DEL return; } ScheduleInput(new RawTextInputEventArgs(_keyboard, (ulong)ev.KeyEvent.time.ToInt64(), _inputRoot, text), ref ev); } } } } private bool UpdateScaling(bool skipResize = false) { lock (SyncRoot) { double newScaling; if (_scalingOverride.HasValue) newScaling = _scalingOverride.Value; else { var monitor = _platform.X11Screens.Screens.OrderBy(x => x.PixelDensity) .FirstOrDefault(m => m.Bounds.Contains(Position)); newScaling = monitor?.PixelDensity ?? Scaling; } if (Scaling != newScaling) { var oldScaledSize = ClientSize; Scaling = newScaling; ScalingChanged?.Invoke(Scaling); SetMinMaxSize(_scaledMinMaxSize.minSize, _scaledMinMaxSize.maxSize); if(!skipResize) Resize(oldScaledSize, true); return true; } return false; } } private WindowState _lastWindowState; public WindowState WindowState { get => _lastWindowState; set { if(_lastWindowState == value) return; _lastWindowState = value; if (value == WindowState.Minimized) { XIconifyWindow(_x11.Display, _handle, _x11.DefaultScreen); } else if (value == WindowState.Maximized) { ChangeWMAtoms(false, _x11.Atoms._NET_WM_STATE_HIDDEN); ChangeWMAtoms(false, _x11.Atoms._NET_WM_STATE_FULLSCREEN); ChangeWMAtoms(true, _x11.Atoms._NET_WM_STATE_MAXIMIZED_VERT, _x11.Atoms._NET_WM_STATE_MAXIMIZED_HORZ); } else if (value == WindowState.FullScreen) { ChangeWMAtoms(false, _x11.Atoms._NET_WM_STATE_HIDDEN); ChangeWMAtoms(true, _x11.Atoms._NET_WM_STATE_FULLSCREEN); ChangeWMAtoms(false, _x11.Atoms._NET_WM_STATE_MAXIMIZED_VERT, _x11.Atoms._NET_WM_STATE_MAXIMIZED_HORZ); } else { ChangeWMAtoms(false, _x11.Atoms._NET_WM_STATE_HIDDEN); ChangeWMAtoms(false, _x11.Atoms._NET_WM_STATE_FULLSCREEN); ChangeWMAtoms(false, _x11.Atoms._NET_WM_STATE_MAXIMIZED_VERT, _x11.Atoms._NET_WM_STATE_MAXIMIZED_HORZ); } } } private void OnPropertyChange(IntPtr atom, bool hasValue) { if (atom == _x11.Atoms._NET_WM_STATE) { WindowState state = WindowState.Normal; if(hasValue) { XGetWindowProperty(_x11.Display, _handle, _x11.Atoms._NET_WM_STATE, IntPtr.Zero, new IntPtr(256), false, (IntPtr)Atom.XA_ATOM, out _, out _, out var nitems, out _, out var prop); int maximized = 0; var pitems = (IntPtr*)prop.ToPointer(); for (var c = 0; c < nitems.ToInt32(); c++) { if (pitems[c] == _x11.Atoms._NET_WM_STATE_HIDDEN) { state = WindowState.Minimized; break; } if(pitems[c] == _x11.Atoms._NET_WM_STATE_FULLSCREEN) { state = WindowState.FullScreen; break; } if (pitems[c] == _x11.Atoms._NET_WM_STATE_MAXIMIZED_HORZ || pitems[c] == _x11.Atoms._NET_WM_STATE_MAXIMIZED_VERT) { maximized++; if (maximized == 2) { state = WindowState.Maximized; break; } } } XFree(prop); } if (_lastWindowState != state) { _lastWindowState = state; WindowStateChanged?.Invoke(state); } } } RawInputModifiers TranslateModifiers(XModifierMask state) { var rv = default(RawInputModifiers); if (state.HasFlag(XModifierMask.Button1Mask)) rv |= RawInputModifiers.LeftMouseButton; if (state.HasFlag(XModifierMask.Button2Mask)) rv |= RawInputModifiers.RightMouseButton; if (state.HasFlag(XModifierMask.Button3Mask)) rv |= RawInputModifiers.MiddleMouseButton; if (state.HasFlag(XModifierMask.Button4Mask)) rv |= RawInputModifiers.XButton1MouseButton; if (state.HasFlag(XModifierMask.Button5Mask)) rv |= RawInputModifiers.XButton2MouseButton; if (state.HasFlag(XModifierMask.ShiftMask)) rv |= RawInputModifiers.Shift; if (state.HasFlag(XModifierMask.ControlMask)) rv |= RawInputModifiers.Control; if (state.HasFlag(XModifierMask.Mod1Mask)) rv |= RawInputModifiers.Alt; if (state.HasFlag(XModifierMask.Mod4Mask)) rv |= RawInputModifiers.Meta; return rv; } private SystemDecorations _systemDecorations = SystemDecorations.Full; private bool _canResize = true; private const int MaxWindowDimension = 100000; private (Size minSize, Size maxSize) _scaledMinMaxSize = (new Size(1, 1), new Size(double.PositiveInfinity, double.PositiveInfinity)); private (PixelSize minSize, PixelSize maxSize) _minMaxSize = (new PixelSize(1, 1), new PixelSize(MaxWindowDimension, MaxWindowDimension)); private double _scaling = 1; void ScheduleInput(RawInputEventArgs args, ref XEvent xev) { _x11.LastActivityTimestamp = xev.ButtonEvent.time; ScheduleInput(args); } public void ScheduleXI2Input(RawInputEventArgs args) { if (args is RawPointerEventArgs pargs) { if ((pargs.Type == RawPointerEventType.TouchBegin || pargs.Type == RawPointerEventType.TouchUpdate || pargs.Type == RawPointerEventType.LeftButtonDown || pargs.Type == RawPointerEventType.RightButtonDown || pargs.Type == RawPointerEventType.MiddleButtonDown || pargs.Type == RawPointerEventType.NonClientLeftButtonDown) && ActivateTransientChildIfNeeded()) return; if (pargs.Type == RawPointerEventType.TouchEnd && ActivateTransientChildIfNeeded()) pargs.Type = RawPointerEventType.TouchCancel; } ScheduleInput(args); } private void ScheduleInput(RawInputEventArgs args) { if (args is RawPointerEventArgs mouse) mouse.Position = mouse.Position / Scaling; if (args is RawDragEvent drag) drag.Location = drag.Location / Scaling; _lastEvent = new InputEventContainer() {Event = args}; _inputQueue.Enqueue(_lastEvent); if (_inputQueue.Count == 1) { Dispatcher.UIThread.Post(() => { while (_inputQueue.Count > 0) { Dispatcher.UIThread.RunJobs(DispatcherPriority.Input + 1); var ev = _inputQueue.Dequeue(); Input?.Invoke(ev.Event); } }, DispatcherPriority.Input); } } void MouseEvent(RawPointerEventType type, ref XEvent ev, XModifierMask mods) { var mev = new RawPointerEventArgs( _mouse, (ulong)ev.ButtonEvent.time.ToInt64(), _inputRoot, type, new Point(ev.ButtonEvent.x, ev.ButtonEvent.y), TranslateModifiers(mods)); if(type == RawPointerEventType.Move && _inputQueue.Count>0 && _lastEvent.Event is RawPointerEventArgs ma) if (ma.Type == RawPointerEventType.Move) { _lastEvent.Event = mev; return; } ScheduleInput(mev, ref ev); } void DoPaint() { Paint?.Invoke(new Rect()); } public void Invalidate(Rect rect) { } public IInputRoot InputRoot => _inputRoot; public void SetInputRoot(IInputRoot inputRoot) { _inputRoot = inputRoot; } public void Dispose() { if (_handle != IntPtr.Zero) { XDestroyWindow(_x11.Display, _handle); Cleanup(); } } void Cleanup() { if (_xic != IntPtr.Zero) { XDestroyIC(_xic); _xic = IntPtr.Zero; } if (_handle != IntPtr.Zero) { XDestroyWindow(_x11.Display, _handle); _platform.Windows.Remove(_handle); _platform.XI2?.OnWindowDestroyed(_handle); _handle = IntPtr.Zero; Closed?.Invoke(); _mouse.Dispose(); _touch.Dispose(); } if (_useRenderWindow && _renderHandle != IntPtr.Zero) { XDestroyWindow(_x11.Display, _renderHandle); _renderHandle = IntPtr.Zero; } } bool ActivateTransientChildIfNeeded() { if (_disabled) { GotInputWhenDisabled?.Invoke(); return true; } return false; } public void SetParent(IWindowImpl parent) { if (parent == null || parent.Handle == null || parent.Handle.Handle == IntPtr.Zero) XDeleteProperty(_x11.Display, _handle, _x11.Atoms.XA_WM_TRANSIENT_FOR); else XSetTransientForHint(_x11.Display, _handle, parent.Handle.Handle); } public void Show() { _wasMappedAtLeastOnce = true; XMapWindow(_x11.Display, _handle); XFlush(_x11.Display); } public void Hide() => XUnmapWindow(_x11.Display, _handle); public Point PointToClient(PixelPoint point) => new Point((point.X - Position.X) / Scaling, (point.Y - Position.Y) / Scaling); public PixelPoint PointToScreen(Point point) => new PixelPoint( (int)(point.X * Scaling + Position.X), (int)(point.Y * Scaling + Position.Y)); public void SetSystemDecorations(SystemDecorations enabled) { _systemDecorations = enabled == SystemDecorations.Full ? SystemDecorations.Full : SystemDecorations.None; UpdateMotifHints(); UpdateSizeHints(null); } public void Resize(Size clientSize) => Resize(clientSize, false); public void Move(PixelPoint point) => Position = point; private void MoveResize(PixelPoint position, Size size, double scaling) { Move(position); _scalingOverride = scaling; UpdateScaling(true); Resize(size, true); } PixelSize ToPixelSize(Size size) => new PixelSize((int)(size.Width * Scaling), (int)(size.Height * Scaling)); void Resize(Size clientSize, bool force) { if (!force && clientSize == ClientSize) return; var needImmediatePopupResize = clientSize != ClientSize; var pixelSize = ToPixelSize(clientSize); UpdateSizeHints(pixelSize); XConfigureResizeWindow(_x11.Display, _handle, pixelSize); if (_useRenderWindow) XConfigureResizeWindow(_x11.Display, _renderHandle, pixelSize); XFlush(_x11.Display); if (force || !_wasMappedAtLeastOnce || (_popup && needImmediatePopupResize)) { _realSize = pixelSize; Resized?.Invoke(ClientSize); } } public void CanResize(bool value) { _canResize = value; UpdateMotifHints(); UpdateSizeHints(null); } public void SetCursor(IPlatformHandle cursor) { if (cursor == null) XDefineCursor(_x11.Display, _handle, _x11.DefaultCursor); else { if (cursor.HandleDescriptor != "XCURSOR") throw new ArgumentException("Expected XCURSOR handle type"); XDefineCursor(_x11.Display, _handle, cursor.Handle); } } public IPlatformHandle Handle { get; } public PixelPoint Position { get => _position ?? default; set { var changes = new XWindowChanges { x = (int)value.X, y = (int)value.Y }; XConfigureWindow(_x11.Display, _handle, ChangeWindowFlags.CWX | ChangeWindowFlags.CWY, ref changes); XFlush(_x11.Display); if (!_wasMappedAtLeastOnce) { _position = value; PositionChanged?.Invoke(value); } } } public IMouseDevice MouseDevice => _mouse; public TouchDevice TouchDevice => _touch; public IPopupImpl CreatePopup() => _platform.Options.OverlayPopups ? null : new X11Window(_platform, this); public void Activate() { if (_x11.Atoms._NET_ACTIVE_WINDOW != IntPtr.Zero) { SendNetWMMessage(_x11.Atoms._NET_ACTIVE_WINDOW, (IntPtr)1, _x11.LastActivityTimestamp, IntPtr.Zero); } else { XRaiseWindow(_x11.Display, _handle); XSetInputFocus(_x11.Display, _handle, 0, IntPtr.Zero); } } public IScreenImpl Screen => _platform.Screens; public Size MaxAutoSizeHint => _platform.X11Screens.Screens.Select(s => s.Bounds.Size.ToSize(s.PixelDensity)) .OrderByDescending(x => x.Width + x.Height).FirstOrDefault(); void SendNetWMMessage(IntPtr message_type, IntPtr l0, IntPtr? l1 = null, IntPtr? l2 = null, IntPtr? l3 = null, IntPtr? l4 = null) { var xev = new XEvent { ClientMessageEvent = { type = XEventName.ClientMessage, send_event = true, window = _handle, message_type = message_type, format = 32, ptr1 = l0, ptr2 = l1 ?? IntPtr.Zero, ptr3 = l2 ?? IntPtr.Zero, ptr4 = l3 ?? IntPtr.Zero } }; xev.ClientMessageEvent.ptr4 = l4 ?? IntPtr.Zero; XSendEvent(_x11.Display, _x11.RootWindow, false, new IntPtr((int)(EventMask.SubstructureRedirectMask | EventMask.SubstructureNotifyMask)), ref xev); } void BeginMoveResize(NetWmMoveResize side, PointerPressedEventArgs e) { var pos = GetCursorPos(_x11); XUngrabPointer(_x11.Display, new IntPtr(0)); SendNetWMMessage (_x11.Atoms._NET_WM_MOVERESIZE, (IntPtr) pos.x, (IntPtr) pos.y, (IntPtr) side, (IntPtr) 1, (IntPtr)1); // left button e.Pointer.Capture(null); } public void BeginMoveDrag(PointerPressedEventArgs e) { BeginMoveResize(NetWmMoveResize._NET_WM_MOVERESIZE_MOVE, e); } public void BeginResizeDrag(WindowEdge edge, PointerPressedEventArgs e) { var side = NetWmMoveResize._NET_WM_MOVERESIZE_CANCEL; if (edge == WindowEdge.East) side = NetWmMoveResize._NET_WM_MOVERESIZE_SIZE_RIGHT; if (edge == WindowEdge.North) side = NetWmMoveResize._NET_WM_MOVERESIZE_SIZE_TOP; if (edge == WindowEdge.South) side = NetWmMoveResize._NET_WM_MOVERESIZE_SIZE_BOTTOM; if (edge == WindowEdge.West) side = NetWmMoveResize._NET_WM_MOVERESIZE_SIZE_LEFT; if (edge == WindowEdge.NorthEast) side = NetWmMoveResize._NET_WM_MOVERESIZE_SIZE_TOPRIGHT; if (edge == WindowEdge.NorthWest) side = NetWmMoveResize._NET_WM_MOVERESIZE_SIZE_TOPLEFT; if (edge == WindowEdge.SouthEast) side = NetWmMoveResize._NET_WM_MOVERESIZE_SIZE_BOTTOMRIGHT; if (edge == WindowEdge.SouthWest) side = NetWmMoveResize._NET_WM_MOVERESIZE_SIZE_BOTTOMLEFT; BeginMoveResize(side, e); } public void SetTitle(string title) { var data = Encoding.UTF8.GetBytes(title); fixed (void* pdata = data) { XChangeProperty(_x11.Display, _handle, _x11.Atoms._NET_WM_NAME, _x11.Atoms.UTF8_STRING, 8, PropertyMode.Replace, pdata, data.Length); XStoreName(_x11.Display, _handle, title); } } public void SetWmClass(string wmClass) { var data = Encoding.ASCII.GetBytes(wmClass); fixed (void* pdata = data) { XChangeProperty(_x11.Display, _handle, _x11.Atoms.XA_WM_CLASS, _x11.Atoms.XA_STRING, 8, PropertyMode.Replace, pdata, data.Length); } } public void SetMinMaxSize(Size minSize, Size maxSize) { _scaledMinMaxSize = (minSize, maxSize); var min = new PixelSize( (int)(minSize.Width < 1 ? 1 : minSize.Width * Scaling), (int)(minSize.Height < 1 ? 1 : minSize.Height * Scaling)); const int maxDim = MaxWindowDimension; var max = new PixelSize( (int)(maxSize.Width > maxDim ? maxDim : Math.Max(min.Width, maxSize.Width * Scaling)), (int)(maxSize.Height > maxDim ? maxDim : Math.Max(min.Height, maxSize.Height * Scaling))); _minMaxSize = (min, max); UpdateSizeHints(null); } public void SetTopmost(bool value) { ChangeWMAtoms(value, _x11.Atoms._NET_WM_STATE_ABOVE); } public void SetEnabled(bool enable) { _disabled = !enable; } public Action GotInputWhenDisabled { get; set; } public void SetIcon(IWindowIconImpl icon) { if (icon != null) { var data = ((X11IconData)icon).Data; fixed (void* pdata = data) XChangeProperty(_x11.Display, _handle, _x11.Atoms._NET_WM_ICON, new IntPtr((int)Atom.XA_CARDINAL), 32, PropertyMode.Replace, pdata, data.Length); } else { XDeleteProperty(_x11.Display, _handle, _x11.Atoms._NET_WM_ICON); } } public void ShowTaskbarIcon(bool value) { ChangeWMAtoms(!value, _x11.Atoms._NET_WM_STATE_SKIP_TASKBAR); } void ChangeWMAtoms(bool enable, params IntPtr[] atoms) { if (atoms.Length != 1 && atoms.Length != 2) throw new ArgumentException(); if (!_mapped) { XGetWindowProperty(_x11.Display, _handle, _x11.Atoms._NET_WM_STATE, IntPtr.Zero, new IntPtr(256), false, (IntPtr)Atom.XA_ATOM, out _, out _, out var nitems, out _, out var prop); var ptr = (IntPtr*)prop.ToPointer(); var newAtoms = new HashSet<IntPtr>(); for (var c = 0; c < nitems.ToInt64(); c++) newAtoms.Add(*ptr); XFree(prop); foreach(var atom in atoms) if (enable) newAtoms.Add(atom); else newAtoms.Remove(atom); XChangeProperty(_x11.Display, _handle, _x11.Atoms._NET_WM_STATE, (IntPtr)Atom.XA_ATOM, 32, PropertyMode.Replace, newAtoms.ToArray(), newAtoms.Count); } SendNetWMMessage(_x11.Atoms._NET_WM_STATE, (IntPtr)(enable ? 1 : 0), atoms[0], atoms.Length > 1 ? atoms[1] : IntPtr.Zero, atoms.Length > 2 ? atoms[2] : IntPtr.Zero, atoms.Length > 3 ? atoms[3] : IntPtr.Zero ); } public IPopupPositioner PopupPositioner { get; } public ITopLevelNativeMenuExporter NativeMenuExporter { get; } public INativeControlHostImpl NativeControlHost { get; } public void SetTransparencyLevelHint(WindowTransparencyLevel transparencyLevel) => _transparencyHelper.SetTransparencyRequest(transparencyLevel); public void SetWindowManagerAddShadowHint(bool enabled) { } public WindowTransparencyLevel TransparencyLevel => _transparencyHelper.CurrentLevel; } }
39.882194
134
0.526551
[ "MIT" ]
Mehigh17/Avalonia
src/Avalonia.X11/X11Window.cs
44,349
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.Cognito.Outputs { [OutputType] public sealed class UserPoolEmailConfiguration { /// <summary> /// Email configuration set name from SES. /// </summary> public readonly string? ConfigurationSet; /// <summary> /// Email delivery method to use. `COGNITO_DEFAULT` for the default email functionality built into Cognito or `DEVELOPER` to use your Amazon SES configuration. /// </summary> public readonly string? EmailSendingAccount; /// <summary> /// Sender’s email address or sender’s display name with their email address (e.g., `john@example.com`, `John Smith &lt;john@example.com&gt;` or `\"John Smith Ph.D.\" &lt;john@example.com&gt;`). Escaped double quotes are required around display names that contain certain characters as specified in [RFC 5322](https://tools.ietf.org/html/rfc5322). /// </summary> public readonly string? FromEmailAddress; /// <summary> /// REPLY-TO email address. /// </summary> public readonly string? ReplyToEmailAddress; /// <summary> /// ARN of the SES verified email identity to to use. Required if `email_sending_account` is set to `DEVELOPER`. /// </summary> public readonly string? SourceArn; [OutputConstructor] private UserPoolEmailConfiguration( string? configurationSet, string? emailSendingAccount, string? fromEmailAddress, string? replyToEmailAddress, string? sourceArn) { ConfigurationSet = configurationSet; EmailSendingAccount = emailSendingAccount; FromEmailAddress = fromEmailAddress; ReplyToEmailAddress = replyToEmailAddress; SourceArn = sourceArn; } } }
38.105263
355
0.650092
[ "ECL-2.0", "Apache-2.0" ]
RafalSumislawski/pulumi-aws
sdk/dotnet/Cognito/Outputs/UserPoolEmailConfiguration.cs
2,176
C#
/* * Copyright 2013 NEHTA * * Licensed under the NEHTA Open Source (Apache) License; you may not use this * file except in compliance with the License. A copy of the License is in the * 'license.txt' file, which should be provided with this work. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using JetBrains.Annotations; using Nehta.VendorLibrary.Common; using System.Runtime.Serialization; using Nehta.VendorLibrary.CDA.Common; using Nehta.VendorLibrary.CDA.Common.Enums; namespace Nehta.VendorLibrary.CDA.SCSModel { /// <summary> /// This interface defines and constrains the person object down to those properties that are applicable for a Person With Organisation /// </summary> public interface IPersonWithOrganisation : IPerson { /// <summary> /// Organisation /// </summary> [CanBeNull] [DataMember] IEmploymentOrganisation Organisation { get; set; } /// <summary> /// Validates this Person With Organisation /// </summary> /// <param name="path">The path to this object as a string</param> /// <param name="messages">the validation messages to date, these may be added to within this method</param> new void Validate(string path, List<ValidationMessage> messages); } }
37.113636
139
0.701776
[ "Apache-2.0" ]
AuDigitalHealth/clinical-document-library-dotnet
src/CDA.Generator.Common/Common/Interfaces/PersonOrganisation/IPersonWithOrganisation.cs
1,635
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using System.Threading.Tasks; using Moq; using osu.Game.Online; using osu.Game.Online.Multiplayer; using osu.Game.Online.Rooms; using Xunit; namespace osu.Server.Spectator.Tests.Multiplayer { public class BeatmapAvailabilityTests : MultiplayerTest { [Fact] public async Task ClientCantChangeAvailabilityWhenNotJoinedRoom() { await Assert.ThrowsAsync<NotJoinedRoomException>(() => Hub.ChangeBeatmapAvailability(BeatmapAvailability.Importing())); } [Fact] public async Task AvailabilityChangeBroadcastedOnlyOnChange() { await Hub.JoinRoom(ROOM_ID); await Hub.ChangeBeatmapAvailability(BeatmapAvailability.Importing()); Receiver.Verify(b => b.UserBeatmapAvailabilityChanged(USER_ID, It.Is<BeatmapAvailability>(b2 => b2.State == DownloadState.Importing)), Times.Once); // should not fire a second time. await Hub.ChangeBeatmapAvailability(BeatmapAvailability.Importing()); Receiver.Verify(b => b.UserBeatmapAvailabilityChanged(USER_ID, It.Is<BeatmapAvailability>(b2 => b2.State == DownloadState.Importing)), Times.Once); } [Fact] public async Task OnlyClientsInSameRoomReceiveAvailabilityChange() { await Hub.JoinRoom(ROOM_ID); SetUserContext(ContextUser2); await Hub.JoinRoom(ROOM_ID_2); var user1Availability = BeatmapAvailability.Importing(); var user2Availability = BeatmapAvailability.Downloading(0.5f); SetUserContext(ContextUser); await Hub.ChangeBeatmapAvailability(user1Availability); using (var room = await Rooms.GetForUse(ROOM_ID)) Assert.True(room.Item?.Users.Single().BeatmapAvailability.Equals(user1Availability)); SetUserContext(ContextUser2); await Hub.ChangeBeatmapAvailability(user2Availability); using (var room2 = await Rooms.GetForUse(ROOM_ID_2)) Assert.True(room2.Item?.Users.Single().BeatmapAvailability.Equals(user2Availability)); Receiver.Verify(c1 => c1.UserBeatmapAvailabilityChanged(USER_ID, It.Is<BeatmapAvailability>(b => b.Equals(user1Availability))), Times.Once); Receiver.Verify(c1 => c1.UserBeatmapAvailabilityChanged(USER_ID_2, It.Is<BeatmapAvailability>(b => b.Equals(user2Availability))), Times.Never); } } }
42.655738
159
0.690623
[ "MIT" ]
ppy/osu-serer-spectator
osu.Server.Spectator.Tests/Multiplayer/BeatmapAvailabilityTests.cs
2,602
C#
using System; using System.Threading.Tasks; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Primitives; using OrchardCore.Data; using OrchardCore.Environment.Cache; using OrchardCore.Environment.Shell.Scope; using OrchardCore.Modules; using YesSql; namespace OrchardCore.Settings.Services { /// <summary> /// Implements <see cref="ISiteService"/> by storing the site as a Content Item. /// </summary> public class SiteService : ISiteService { private const string SiteCacheKey = "SiteService"; private readonly ISignal _signal; private readonly IMemoryCache _memoryCache; private readonly IClock _clock; public SiteService( ISignal signal, IMemoryCache memoryCache, IClock clock) { _signal = signal; _memoryCache = memoryCache; _clock = clock; } /// <inheritdoc/> public IChangeToken ChangeToken => _signal.GetToken(SiteCacheKey); /// <summary> /// Returns the document from the database to be updated. /// </summary> public async Task<ISite> LoadSiteSettingsAsync() { return await SessionHelper.LoadForUpdateAsync(GetDefaultSettings); } /// <summary> /// Returns the document from the cache or creates a new one. The result should not be updated. /// </summary> public async Task<ISite> GetSiteSettingsAsync() { if (!_memoryCache.TryGetValue<SiteSettings>(SiteCacheKey, out var site)) { var sessionHelper = SessionHelper; // First get a new token. var changeToken = ChangeToken; // The cache is always updated with the actual persisted data. site = await sessionHelper.GetForCachingAsync(GetDefaultSettings); // Prevent data from being updated. site.IsReadonly = true; _memoryCache.Set(SiteCacheKey, site, changeToken); } return site; } private SiteSettings GetDefaultSettings() { return new SiteSettings { SiteSalt = Guid.NewGuid().ToString("N"), SiteName = "My Orchard Project Application", PageTitleFormat = "{% page_title Site.SiteName, position: \"after\", separator: \" - \" %}", TimeZoneId = _clock.GetSystemTimeZone().TimeZoneId, PageSize = 10, MaxPageSize = 100, MaxPagedCount = 0 }; } /// <inheritdoc/> public Task UpdateSiteSettingsAsync(ISite site) { if (site.IsReadonly) { throw new ArgumentException("The object is read-only"); } // Persists new data. Session.Save(site); // Invalidates the cache after the session is committed. _signal.DeferredSignalToken(SiteCacheKey); return Task.CompletedTask; } private ISession Session => ShellScope.Services.GetRequiredService<ISession>(); private ISessionHelper SessionHelper => ShellScope.Services.GetRequiredService<ISessionHelper>(); } }
32.085714
108
0.596023
[ "BSD-3-Clause" ]
BenPool/OrchardCore
src/OrchardCore.Modules/OrchardCore.Settings/Services/SiteService.cs
3,369
C#
using System; using System.Text; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using System.ComponentModel; using System.Threading; using System.Collections; using PubnubApi; using MockServer; using System.Diagnostics; using System.Threading.Tasks; namespace PubNubMessaging.Tests { [TestFixture] public class WhenAClientIsPresented : TestHarness { private static int manualResetEventWaitTimeout = 310 * 1000; private static Pubnub pubnub; private static Server server; private static string authKey = "myauth"; public class TestLog : IPubnubLog { void IPubnubLog.WriteToLog(string logText) { System.Diagnostics.Debug.WriteLine(logText); } } [SetUp] public static void Init() { UnitTestLog unitLog = new Tests.UnitTestLog(); unitLog.LogLevel = MockServer.LoggingMethod.Level.Verbose; server = Server.Instance(); MockServer.LoggingMethod.MockServerLog = unitLog; server.Start(); if (!PubnubCommon.PAMServerSideGrant) { return; } bool receivedGrantMessage = false; string channel = "hello_my_channel"; PNConfiguration config = new PNConfiguration { PublishKey = PubnubCommon.PublishKey, SubscribeKey = PubnubCommon.SubscribeKey, SecretKey = PubnubCommon.SecretKey, Uuid = "mytestuuid", Secure = false }; server.RunOnHttps(false); pubnub = createPubNubInstance(config); string expected = "{\"message\":\"Success\",\"payload\":{\"level\":\"user\",\"subscribe_key\":\"demo-36\",\"ttl\":20,\"channel\":\"hello_my_channel\",\"auths\":{\"myAuth\":{\"r\":1,\"w\":1,\"m\":1}}},\"service\":\"Access Manager\",\"status\":200}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(string.Format("/v2/auth/grant/sub-key/{0}", PubnubCommon.SubscribeKey)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); ManualResetEvent grantManualEvent = new ManualResetEvent(false); pubnub.Grant().Channels(new [] { channel, channel+"-pnpres" }).AuthKeys(new [] { authKey }).Read(true).Write(true).Manage(true).TTL(20) .Execute(new PNAccessManagerGrantResultExt( (r, s) => { try { Debug.WriteLine("PNStatus={0}", pubnub.JsonPluggableLibrary.SerializeToJsonString(s)); if (r != null) { Debug.WriteLine("PNAccessManagerGrantResult={0}", pubnub.JsonPluggableLibrary.SerializeToJsonString(r)); if (r.Channels != null && r.Channels.Count > 0) { var read = r.Channels[channel][authKey].ReadEnabled; var write = r.Channels[channel][authKey].WriteEnabled; if (read && write) { receivedGrantMessage = true; } } } } catch { /* ignore */ } finally { grantManualEvent.Set(); } })); Thread.Sleep(100); grantManualEvent.WaitOne(manualResetEventWaitTimeout); pubnub.Destroy(); pubnub.PubnubUnitTest = null; pubnub = null; Assert.IsTrue(receivedGrantMessage, "WhenAClientIsPresent Grant access failed."); } [TearDown] public static void Exit() { server.Stop(); } #if (USE_JSONFX) [Test] #else [Ignore("Ignore this for non-JsonFX")] #endif public void UsingJsonFx() { Debug.Write("UsingJsonFx"); Assert.True(true, "UsingJsonFx"); } #if (USE_JSONFX) [Ignore] #else [Test] #endif public void UsingNewtonSoft() { Debug.Write("UsingNewtonSoft"); Assert.True(true, "UsingNewtonSoft"); } [Test] public static void ThenPresenceShouldReturnReceivedMessage() { server.ClearRequests(); bool receivedPresenceMessage = false; PNConfiguration config = new PNConfiguration { PublishKey = PubnubCommon.PublishKey, SubscribeKey = PubnubCommon.SubscribeKey, Uuid = "mytestuuid", Secure = false }; if (PubnubCommon.PAMServerSideRun) { config.SecretKey = PubnubCommon.SecretKey; } else if (!string.IsNullOrEmpty(authKey) && !PubnubCommon.SuppressAuthKey) { config.AuthKey = authKey; } server.RunOnHttps(false); ManualResetEvent presenceManualEvent = new ManualResetEvent(false); SubscribeCallback listenerSubCallack = new SubscribeCallbackExt( (o, m) => { Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(m)); }, (o, p) => { Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(p)); if (p.Event == "join") { receivedPresenceMessage = true; } presenceManualEvent.Set(); }, (o, s) => { Debug.WriteLine(string.Format("{0} {1} {2}", s.Operation, s.Category, s.StatusCode)); if (s.StatusCode != 200 || s.Error) { if (s.ErrorData != null) { Debug.WriteLine(s.ErrorData.Information); } presenceManualEvent.Set(); } }); pubnub = createPubNubInstance(config); if (!pubnub.AddListener(listenerSubCallack)) { System.Diagnostics.Debug.WriteLine("ATTENTION: AddListener failed"); } string channel = "hello_my_channel"; manualResetEventWaitTimeout = 310 * 1000; string expected = "{\"t\":{\"t\":\"14833694874957031\",\"r\":7},\"m\":[{\"a\":\"4\",\"f\":512,\"p\":{\"t\":\"14833694873794045\",\"r\":2},\"k\":\"demo-36\",\"c\":\"hello_my_channel-pnpres\",\"d\":{\"action\": \"join\", \"timestamp\": 1483369487, \"uuid\": \"mylocalmachine.mydomain.com\", \"occupancy\": 1},\"b\":\"hello_my_channel-pnpres\"}]}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/subscribe/{0}/{1},{2}/0", PubnubCommon.SubscribeKey, channel, channel + "-pnpres")) .WithParameter("heartbeat", "300") .WithParameter("pnsdk", PubnubCommon.EncodedSDK) .WithParameter("requestid", "myRequestId") .WithParameter("timestamp", "1356998400") .WithParameter("tt", "0") .WithParameter("uuid", config.Uuid) .WithParameter("signature", "_JVs4gooSMhdgxRO6FNkk6HwlkyxqcRATHU5j3vkJ9s=") .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); expected = "{}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); pubnub.Subscribe<string>().Channels(new [] { channel }).WithPresence().Execute(); presenceManualEvent.WaitOne(manualResetEventWaitTimeout); if (!PubnubCommon.EnableStubTest) Thread.Sleep(1000); else Thread.Sleep(100); pubnub.Unsubscribe<string>().Channels(new [] { channel }).Execute(); if (!PubnubCommon.EnableStubTest) { Thread.Sleep(1000); } else { Thread.Sleep(100); } if (!pubnub.RemoveListener(listenerSubCallack)) { System.Diagnostics.Debug.WriteLine("ATTENTION: RemoveListener failed"); } pubnub.Destroy(); pubnub.PubnubUnitTest = null; pubnub = null; Assert.IsTrue(receivedPresenceMessage, "Presence message not received"); } [Test] public static void ThenPresenceShouldReturnReceivedMessageSSL() { server.ClearRequests(); bool receivedPresenceMessage = false; PNConfiguration config = new PNConfiguration { PublishKey = PubnubCommon.PublishKey, SubscribeKey = PubnubCommon.SubscribeKey, Uuid = "mytestuuid", Secure = true, LogVerbosity = PNLogVerbosity.BODY, PubnubLog = new TestLog() }; if (PubnubCommon.PAMServerSideRun) { config.SecretKey = PubnubCommon.SecretKey; } else if (!string.IsNullOrEmpty(authKey) && !PubnubCommon.SuppressAuthKey) { config.AuthKey = authKey; } server.RunOnHttps(true); ManualResetEvent presenceManualEvent = new ManualResetEvent(false); SubscribeCallback listenerSubCallack = new SubscribeCallbackExt( (o, m) => { Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(m)); }, (o, p) => { Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(p)); if (p.Event == "join") { receivedPresenceMessage = true; } presenceManualEvent.Set(); }, (o, s) => { Debug.WriteLine(string.Format("{0} {1} {2}", s.Operation, s.Category, s.StatusCode)); if (s.StatusCode != 200 || s.Error) { if (s.ErrorData != null) { Debug.WriteLine(s.ErrorData.Information); } presenceManualEvent.Set(); } }); pubnub = createPubNubInstance(config); if (!pubnub.AddListener(listenerSubCallack)) { System.Diagnostics.Debug.WriteLine("ATTENTION: AddListener failed"); } string channel = "hello_my_channel"; manualResetEventWaitTimeout = 310 * 1000; string expected = "{\"t\":{\"t\":\"14833694874957031\",\"r\":7},\"m\":[{\"a\":\"4\",\"f\":512,\"p\":{\"t\":\"14833694873794045\",\"r\":2},\"k\":\"demo-36\",\"c\":\"hello_my_channel-pnpres\",\"d\":{\"action\": \"join\", \"timestamp\": 1483369487, \"uuid\": \"mylocalmachine.mydomain.com\", \"occupancy\": 1},\"b\":\"hello_my_channel-pnpres\"}]}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/subscribe/{0}/{1},{2}/0", PubnubCommon.SubscribeKey, channel, channel + "-pnpres")) .WithParameter("heartbeat", "300") .WithParameter("pnsdk", PubnubCommon.EncodedSDK) .WithParameter("requestid", "myRequestId") .WithParameter("timestamp", "1356998400") .WithParameter("tt", "0") .WithParameter("uuid", config.Uuid) .WithParameter("signature", "_JVs4gooSMhdgxRO6FNkk6HwlkyxqcRATHU5j3vkJ9s=") .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); expected = "{}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); pubnub.Subscribe<string>().Channels(new [] { channel }).WithPresence().Execute(); presenceManualEvent.WaitOne(manualResetEventWaitTimeout); if (!PubnubCommon.EnableStubTest) { Thread.Sleep(1000); } else { Thread.Sleep(100); } pubnub.Unsubscribe<string>().Channels(new [] { channel }).Execute(); Thread.Sleep(100); if (!pubnub.RemoveListener(listenerSubCallack)) { System.Diagnostics.Debug.WriteLine("ATTENTION: RemoveListener failed"); } pubnub.Destroy(); pubnub.PubnubUnitTest = null; pubnub = null; Assert.IsTrue(receivedPresenceMessage, "Presence message not received"); } [Test] public static void ThenPresenceShouldReturnCustomUUID() { server.ClearRequests(); string customUUID = "mylocalmachine.mydomain.com"; bool receivedCustomUUID = false; PNConfiguration config = new PNConfiguration { PublishKey = PubnubCommon.PublishKey, SubscribeKey = PubnubCommon.SubscribeKey, Uuid = "mytestuuid", Secure = false }; if (PubnubCommon.PAMServerSideRun) { config.SecretKey = PubnubCommon.SecretKey; } else if (!string.IsNullOrEmpty(authKey) && !PubnubCommon.SuppressAuthKey) { config.AuthKey = authKey; } server.RunOnHttps(false); ManualResetEvent presenceManualEvent = new ManualResetEvent(false); SubscribeCallback listenerSubCallack = new SubscribeCallbackExt( (o, m) => { Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(m)); }, (o, p) => { Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(p)); receivedCustomUUID = true; presenceManualEvent.Set(); }, (o, s) => { Debug.WriteLine(string.Format("{0} {1} {2}", s.Operation, s.Category, s.StatusCode)); if (s.StatusCode != 200 || s.Error) { if (s.ErrorData != null) { Debug.WriteLine(s.ErrorData.Information); } presenceManualEvent.Set(); } }); pubnub = createPubNubInstance(config); if (!pubnub.AddListener(listenerSubCallack)) { System.Diagnostics.Debug.WriteLine("ATTENTION: AddListener failed"); } string channel = "hello_my_channel"; manualResetEventWaitTimeout = 310 * 1000; pubnub.ChangeUUID(customUUID); string expected = "{\"t\":{\"t\":\"14833694874957031\",\"r\":7},\"m\":[{\"a\":\"4\",\"f\":512,\"p\":{\"t\":\"14833694873794045\",\"r\":2},\"k\":\"demo-36\",\"c\":\"hello_my_channel-pnpres\",\"d\":{\"action\": \"join\", \"timestamp\": 1483369487, \"uuid\": \"mylocalmachine.mydomain.com\", \"occupancy\": 1},\"b\":\"hello_my_channel-pnpres\"}]}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/subscribe/{0}/{1},{2}/0", PubnubCommon.SubscribeKey, channel, channel + "-pnpres")) .WithParameter("heartbeat", "300") .WithParameter("pnsdk", PubnubCommon.EncodedSDK) .WithParameter("requestid", "myRequestId") .WithParameter("timestamp", "1356998400") .WithParameter("tt", "0") .WithParameter("uuid", customUUID) .WithParameter("signature", "D7lw9Np5UU_xUTUAe0Sc0L0eSP9aTQljeith_M_rXzI=") .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); expected = "{}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); pubnub.Subscribe<string>().Channels(new [] { channel }).WithPresence().Execute(); presenceManualEvent.WaitOne(manualResetEventWaitTimeout); if (!PubnubCommon.EnableStubTest) { Thread.Sleep(1000); } else { Thread.Sleep(100); } pubnub.Unsubscribe<string>().Channels(new [] { channel }).Execute(); if (!PubnubCommon.EnableStubTest) { Thread.Sleep(1000); } else { Thread.Sleep(100); } if (!pubnub.RemoveListener(listenerSubCallack)) { System.Diagnostics.Debug.WriteLine("ATTENTION: RemoveListener failed"); } pubnub.Destroy(); pubnub.PubnubUnitTest = null; pubnub = null; Assert.IsTrue(receivedCustomUUID, "Custom UUID not received"); } [Test] public static void IfHereNowIsCalledThenItShouldReturnInfo() { server.ClearRequests(); bool receivedHereNowMessage = false; bool receivedErrorMessage = false; PNConfiguration config = new PNConfiguration { PublishKey = PubnubCommon.PublishKey, SubscribeKey = PubnubCommon.SubscribeKey, Uuid = "mytestuuid", Secure = false }; if (PubnubCommon.PAMServerSideRun) { config.SecretKey = PubnubCommon.SecretKey; } else if (!string.IsNullOrEmpty(authKey) && !PubnubCommon.SuppressAuthKey) { config.AuthKey = authKey; } server.RunOnHttps(false); ManualResetEvent subscribeManualEvent = new ManualResetEvent(false); SubscribeCallback listenerSubCallack = new SubscribeCallbackExt( (o, m) => { Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(m)); }, (o, p) => { subscribeManualEvent.Set(); }, (o, s) => { Debug.WriteLine(string.Format("{0} {1} {2}", s.Operation, s.Category, s.StatusCode)); if (s.StatusCode != 200 || s.Error) { receivedErrorMessage = true; if (s.ErrorData != null) { Debug.WriteLine(s.ErrorData.Information); } } subscribeManualEvent.Set(); }); pubnub = createPubNubInstance(config); if (!pubnub.AddListener(listenerSubCallack)) { System.Diagnostics.Debug.WriteLine("ATTENTION: AddListener failed"); } string channel = "hello_my_channel"; manualResetEventWaitTimeout = 310 * 1000; string expected = "{\"t\":{\"t\":\"14828455563482572\",\"r\":7},\"m\":[]}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel)) .WithParameter("heartbeat", "300") .WithParameter("pnsdk", PubnubCommon.EncodedSDK) .WithParameter("requestid", "myRequestId") .WithParameter("tt", "0") .WithParameter("uuid", config.Uuid) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); expected = "{}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); pubnub.Subscribe<string>().Channels(new [] { channel }).Execute(); subscribeManualEvent.WaitOne(manualResetEventWaitTimeout); if (!receivedErrorMessage) { if (!PubnubCommon.EnableStubTest) { Thread.Sleep(2000); } else Thread.Sleep(200); expected = "{\"status\": 200, \"message\": \"OK\", \"service\": \"Presence\", \"uuids\": [\"mytestuuid\"], \"occupancy\": 1}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/presence/sub_key/{0}/channel/{1}", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); ManualResetEvent hereNowManualEvent = new ManualResetEvent(false); pubnub.HereNow().Channels(new[] { channel }).Execute(new PNHereNowResultEx( (r, s) => { if (r == null) { return; } Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(r)); receivedHereNowMessage = true; hereNowManualEvent.Set(); })); hereNowManualEvent.WaitOne(manualResetEventWaitTimeout); expected = "{\"status\": 200, \"action\": \"leave\", \"message\": \"OK\", \"service\": \"Presence\"}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/presence/sub_key/{0}/channel/{1}/leave", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); pubnub.Unsubscribe<string>().Channels(new[] { channel }).Execute(); if (!PubnubCommon.EnableStubTest) Thread.Sleep(1000); else Thread.Sleep(100); } if (!pubnub.RemoveListener(listenerSubCallack)) { System.Diagnostics.Debug.WriteLine("ATTENTION: RemoveListener failed"); } pubnub.Destroy(); pubnub.PubnubUnitTest = null; pubnub = null; Assert.IsTrue(receivedHereNowMessage, "here_now message not received"); } [Test] #if NET40 public static void IfWithAsyncHereNowIsCalledThenItShouldReturnInfo() #else public static async Task IfWithAsyncHereNowIsCalledThenItShouldReturnInfo() #endif { server.ClearRequests(); bool receivedHereNowMessage = false; bool receivedErrorMessage = false; PNConfiguration config = new PNConfiguration { PublishKey = PubnubCommon.PublishKey, SubscribeKey = PubnubCommon.SubscribeKey, Uuid = "mytestuuid", Secure = false }; if (PubnubCommon.PAMServerSideRun) { config.SecretKey = PubnubCommon.SecretKey; } else if (!string.IsNullOrEmpty(authKey) && !PubnubCommon.SuppressAuthKey) { config.AuthKey = authKey; } server.RunOnHttps(false); ManualResetEvent subscribeManualEvent = new ManualResetEvent(false); SubscribeCallback listenerSubCallack = new SubscribeCallbackExt( (o, m) => { Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(m)); }, (o, p) => { subscribeManualEvent.Set(); }, (o, s) => { Debug.WriteLine(string.Format("{0} {1} {2}", s.Operation, s.Category, s.StatusCode)); if (s.StatusCode != 200 || s.Error) { receivedErrorMessage = true; if (s.ErrorData != null) { Debug.WriteLine(s.ErrorData.Information); } } subscribeManualEvent.Set(); }); pubnub = createPubNubInstance(config); if (!pubnub.AddListener(listenerSubCallack)) { System.Diagnostics.Debug.WriteLine("ATTENTION: AddListener failed"); } string channel = "hello_my_channel"; manualResetEventWaitTimeout = 310 * 1000; string expected = "{\"t\":{\"t\":\"14828455563482572\",\"r\":7},\"m\":[]}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel)) .WithParameter("heartbeat", "300") .WithParameter("pnsdk", PubnubCommon.EncodedSDK) .WithParameter("requestid", "myRequestId") .WithParameter("tt", "0") .WithParameter("uuid", config.Uuid) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); expected = "{}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); pubnub.Subscribe<string>().Channels(new[] { channel }).Execute(); subscribeManualEvent.WaitOne(manualResetEventWaitTimeout); if (!receivedErrorMessage) { if (!PubnubCommon.EnableStubTest) { Thread.Sleep(2000); } else Thread.Sleep(200); expected = "{\"status\": 200, \"message\": \"OK\", \"service\": \"Presence\", \"uuids\": [\"mytestuuid\"], \"occupancy\": 1}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/presence/sub_key/{0}/channel/{1}", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); #if NET40 PNResult<PNHereNowResult> r = Task.Factory.StartNew(async () => await pubnub.HereNow().Channels(new[] { channel }).ExecuteAsync()).Result.Result; #else PNResult<PNHereNowResult> r = await pubnub.HereNow().Channels(new[] { channel }).ExecuteAsync(); #endif if (r.Result != null) { Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(r)); receivedHereNowMessage = true; } expected = "{\"status\": 200, \"action\": \"leave\", \"message\": \"OK\", \"service\": \"Presence\"}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/presence/sub_key/{0}/channel/{1}/leave", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); pubnub.Unsubscribe<string>().Channels(new[] { channel }).Execute(); if (!PubnubCommon.EnableStubTest) Thread.Sleep(1000); else Thread.Sleep(100); } if (!pubnub.RemoveListener(listenerSubCallack)) { System.Diagnostics.Debug.WriteLine("ATTENTION: RemoveListener failed"); } pubnub.Destroy(); pubnub.PubnubUnitTest = null; pubnub = null; Assert.IsTrue(receivedHereNowMessage, "here_now message not received"); } [Test] public static void IfHereNowIsCalledThenItShouldReturnInfoCipher() { server.ClearRequests(); bool receivedHereNowMessage = false; bool receivedErrorMessage = false; PNConfiguration config = new PNConfiguration { PublishKey = PubnubCommon.PublishKey, SubscribeKey = PubnubCommon.SubscribeKey, CipherKey = "enigma", Uuid = "mytestuuid", Secure = false }; if (PubnubCommon.PAMServerSideRun) { config.SecretKey = PubnubCommon.SecretKey; } else if (!string.IsNullOrEmpty(authKey) && !PubnubCommon.SuppressAuthKey) { config.AuthKey = authKey; } server.RunOnHttps(false); ManualResetEvent subscribeManualEvent = new ManualResetEvent(false); SubscribeCallback listenerSubCallack = new SubscribeCallbackExt( (o, m) => { Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(m)); }, (o, p) => { subscribeManualEvent.Set(); }, (o, s) => { Debug.WriteLine(string.Format("{0} {1} {2}", s.Operation, s.Category, s.StatusCode)); if (s.StatusCode != 200 || s.Error) { receivedErrorMessage = true; if (s.ErrorData != null) { Debug.WriteLine(s.ErrorData.Information); } } subscribeManualEvent.Set(); }); pubnub = createPubNubInstance(config); if (!pubnub.AddListener(listenerSubCallack)) { System.Diagnostics.Debug.WriteLine("ATTENTION: AddListener failed"); } string channel = "hello_my_channel"; manualResetEventWaitTimeout = 310 * 1000; string expected = "{\"t\":{\"t\":\"14828455563482572\",\"r\":7},\"m\":[]}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel)) .WithParameter("heartbeat", "300") .WithParameter("pnsdk", PubnubCommon.EncodedSDK) .WithParameter("requestid", "myRequestId") .WithParameter("tt", "0") .WithParameter("uuid", config.Uuid) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); expected = "{}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); pubnub.Subscribe<string>().Channels(new [] { channel }).Execute(); subscribeManualEvent.WaitOne(manualResetEventWaitTimeout); if (!receivedErrorMessage) { if (!PubnubCommon.EnableStubTest) Thread.Sleep(2000); else Thread.Sleep(200); expected = "{\"TotalChannels\":1,\"TotalOccupancy\":1,\"Channels\":{\"hello_my_channel\":{\"ChannelName\":\"hello_my_channel\",\"Occupancy\":1,\"Occupants\":[{\"Uuid\":\"mytestuuid\",\"State\":null}]}}}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/presence/sub_key/{0}/channel/{1}", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); ManualResetEvent hereNowManualEvent = new ManualResetEvent(false); pubnub.HereNow().Channels(new[] { channel }).Execute(new PNHereNowResultEx( (r, s) => { if (r == null) { return; } Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(r)); receivedHereNowMessage = true; hereNowManualEvent.Set(); })); hereNowManualEvent.WaitOne(manualResetEventWaitTimeout); expected = "{\"status\": 200, \"action\": \"leave\", \"message\": \"OK\", \"service\": \"Presence\"}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/presence/sub_key/{0}/channel/{1}/leave", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); pubnub.Unsubscribe<string>().Channels(new[] { channel }).Execute(); if (!PubnubCommon.EnableStubTest) Thread.Sleep(1000); else Thread.Sleep(100); } if (!pubnub.RemoveListener(listenerSubCallack)) { System.Diagnostics.Debug.WriteLine("ATTENTION: RemoveListener failed"); } pubnub.Destroy(); pubnub.PubnubUnitTest = null; pubnub = null; Assert.IsTrue(receivedHereNowMessage, "here_now message not received with cipher"); } [Test] public static void IfHereNowIsCalledThenItShouldReturnInfoCipherSecret() { server.ClearRequests(); bool receivedHereNowMessage = false; PNConfiguration config = new PNConfiguration { PublishKey = PubnubCommon.PublishKey, SubscribeKey = PubnubCommon.SubscribeKey, Secure = false, CipherKey = "enigma", Uuid = "mytestuuid" }; if (PubnubCommon.PAMServerSideRun) { config.SecretKey = PubnubCommon.SecretKey; } else if (!string.IsNullOrEmpty(authKey) && !PubnubCommon.SuppressAuthKey) { config.AuthKey = authKey; } server.RunOnHttps(true); ManualResetEvent subscribeManualEvent = new ManualResetEvent(false); SubscribeCallback listenerSubCallack = new SubscribeCallbackExt( (o, m) => { Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(m)); }, (o, p) => { subscribeManualEvent.Set(); }, (o, s) => { Debug.WriteLine(string.Format("{0} {1} {2}", s.Operation, s.Category, s.StatusCode)); if (s.StatusCode != 200 || s.Error) { if (s.ErrorData != null) { Debug.WriteLine(s.ErrorData.Information); } } subscribeManualEvent.Set(); }); pubnub = createPubNubInstance(config); if (!pubnub.AddListener(listenerSubCallack)) { System.Diagnostics.Debug.WriteLine("ATTENTION: AddListener failed"); } string channel = "hello_my_channel"; manualResetEventWaitTimeout = 310 * 1000; string expected = "{\"t\":{\"t\":\"14828455563482572\",\"r\":7},\"m\":[]}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel)) .WithParameter("heartbeat", "300") .WithParameter("pnsdk", PubnubCommon.EncodedSDK) .WithParameter("requestid", "myRequestId") .WithParameter("timestamp", "1356998400") .WithParameter("tt", "0") .WithParameter("uuid", config.Uuid) .WithParameter("signature", "o3VANfuhvrxfff1jsBMOc6EQ4LCe8LXHGaDh58QBZFA=") .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); expected = "{}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); pubnub.Subscribe<string>().Channels(new [] { channel }).Execute(); subscribeManualEvent.WaitOne(manualResetEventWaitTimeout); if (!PubnubCommon.EnableStubTest) Thread.Sleep(2000); else Thread.Sleep(200); expected = "{\"TotalChannels\":1,\"TotalOccupancy\":1,\"Channels\":{\"hello_my_channel\":{\"ChannelName\":\"hello_my_channel\",\"Occupancy\":1,\"Occupants\":[{\"Uuid\":\"mytestuuid\",\"State\":null}]}}}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/presence/sub_key/{0}/channel/{1}", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); ManualResetEvent hereNowManualEvent = new ManualResetEvent(false); pubnub.HereNow().Channels(new [] { channel }).Execute(new PNHereNowResultEx( (r, s) => { if (r == null) { return; } Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(r)); receivedHereNowMessage = true; hereNowManualEvent.Set(); })); hereNowManualEvent.WaitOne(manualResetEventWaitTimeout); expected = "{\"status\": 200, \"action\": \"leave\", \"message\": \"OK\", \"service\": \"Presence\"}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/presence/sub_key/{0}/channel/{1}/leave", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); pubnub.Unsubscribe<string>().Channels(new [] { channel }).Execute(); if (!PubnubCommon.EnableStubTest) Thread.Sleep(1000); else Thread.Sleep(100); if (!pubnub.RemoveListener(listenerSubCallack)) { System.Diagnostics.Debug.WriteLine("ATTENTION: RemoveListener failed"); } pubnub.Destroy(); pubnub.PubnubUnitTest = null; pubnub = null; Assert.IsTrue(receivedHereNowMessage, "here_now message not received with cipher and secret"); } [Test] public static void IfHereNowIsCalledThenItShouldReturnInfoCipherSecretSSL() { server.ClearRequests(); bool receivedHereNowMessage = false; PNConfiguration config = new PNConfiguration { PublishKey = PubnubCommon.PublishKey, SubscribeKey = PubnubCommon.SubscribeKey, CipherKey = "enigma", Uuid = "mytestuuid", Secure = true }; if (PubnubCommon.PAMServerSideRun) { config.SecretKey = PubnubCommon.SecretKey; } else if (!string.IsNullOrEmpty(authKey) && !PubnubCommon.SuppressAuthKey) { config.AuthKey = authKey; } server.RunOnHttps(true); ManualResetEvent subscribeManualEvent = new ManualResetEvent(false); SubscribeCallback listenerSubCallack = new SubscribeCallbackExt( (o, m) => { Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(m)); }, (o, p) => { subscribeManualEvent.Set(); }, (o, s) => { Debug.WriteLine(string.Format("{0} {1} {2}", s.Operation, s.Category, s.StatusCode)); if (s.StatusCode != 200 || s.Error) { if (s.ErrorData != null) { Debug.WriteLine(s.ErrorData.Information); } } subscribeManualEvent.Set(); }); pubnub = createPubNubInstance(config); if (!pubnub.AddListener(listenerSubCallack)) { System.Diagnostics.Debug.WriteLine("ATTENTION: AddListener failed"); } string channel = "hello_my_channel"; manualResetEventWaitTimeout = 310 * 1000; string expected = "{\"t\":{\"t\":\"14828455563482572\",\"r\":7},\"m\":[]}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel)) .WithParameter("heartbeat", "300") .WithParameter("pnsdk", PubnubCommon.EncodedSDK) .WithParameter("requestid", "myRequestId") .WithParameter("timestamp", "1356998400") .WithParameter("tt", "0") .WithParameter("uuid", config.Uuid) .WithParameter("signature", "o3VANfuhvrxfff1jsBMOc6EQ4LCe8LXHGaDh58QBZFA=") .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); expected = "{}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); pubnub.Subscribe<string>().Channels(new [] { channel }).Execute(); subscribeManualEvent.WaitOne(manualResetEventWaitTimeout); if (!PubnubCommon.EnableStubTest) Thread.Sleep(2000); else Thread.Sleep(200); expected = "{\"TotalChannels\":1,\"TotalOccupancy\":1,\"Channels\":{\"hello_my_channel\":{\"ChannelName\":\"hello_my_channel\",\"Occupancy\":1,\"Occupants\":[{\"Uuid\":\"mytestuuid\",\"State\":null}]}}}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/presence/sub_key/{0}/channel/{1}", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); ManualResetEvent hereNowManualEvent = new ManualResetEvent(false); pubnub.HereNow().Channels(new [] { channel }).Execute(new PNHereNowResultEx( (r, s) => { if (r == null) { return; } Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(r)); receivedHereNowMessage = true; hereNowManualEvent.Set(); })); hereNowManualEvent.WaitOne(manualResetEventWaitTimeout); expected = "{\"status\": 200, \"action\": \"leave\", \"message\": \"OK\", \"service\": \"Presence\"}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/presence/sub_key/{0}/channel/{1}/leave", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); pubnub.Unsubscribe<string>().Channels(new [] { channel }).Execute(); if (!PubnubCommon.EnableStubTest) Thread.Sleep(1000); else Thread.Sleep(100); if (!pubnub.RemoveListener(listenerSubCallack)) { System.Diagnostics.Debug.WriteLine("ATTENTION: RemoveListener failed"); } pubnub.Destroy(); pubnub.PubnubUnitTest = null; pubnub = null; Assert.IsTrue(receivedHereNowMessage, "here_now message not received with cipher, secret, ssl"); } [Test] public static void IfHereNowIsCalledThenItShouldReturnInfoCipherSSL() { server.ClearRequests(); bool receivedHereNowMessage = false; bool receivedErrorMessage = false; PNConfiguration config = new PNConfiguration { PublishKey = PubnubCommon.PublishKey, SubscribeKey = PubnubCommon.SubscribeKey, CipherKey = "enigma", Uuid = "mytestuuid", Secure = true }; if (PubnubCommon.PAMServerSideRun) { config.SecretKey = PubnubCommon.SecretKey; } else if (!string.IsNullOrEmpty(authKey) && !PubnubCommon.SuppressAuthKey) { config.AuthKey = authKey; } server.RunOnHttps(true); ManualResetEvent subscribeManualEvent = new ManualResetEvent(false); SubscribeCallback listenerSubCallack = new SubscribeCallbackExt( (o, m) => { Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(m)); }, (o, p) => { subscribeManualEvent.Set(); }, (o, s) => { Debug.WriteLine(string.Format("{0} {1} {2}", s.Operation, s.Category, s.StatusCode)); if (s.StatusCode != 200 || s.Error) { receivedErrorMessage = true; if (s.ErrorData != null) { Debug.WriteLine(s.ErrorData.Information); } } subscribeManualEvent.Set(); }); pubnub = createPubNubInstance(config); if (!pubnub.AddListener(listenerSubCallack)) { System.Diagnostics.Debug.WriteLine("ATTENTION: AddListener failed"); } string channel = "hello_my_channel"; manualResetEventWaitTimeout = 310 * 1000; string expected = "{\"t\":{\"t\":\"14828455563482572\",\"r\":7},\"m\":[]}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel)) .WithParameter("heartbeat", "300") .WithParameter("pnsdk", PubnubCommon.EncodedSDK) .WithParameter("requestid", "myRequestId") .WithParameter("tt", "0") .WithParameter("uuid", config.Uuid) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); expected = "{}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); pubnub.Subscribe<string>().Channels(new [] { channel }).Execute(); subscribeManualEvent.WaitOne(manualResetEventWaitTimeout); if (!receivedErrorMessage) { if (!PubnubCommon.EnableStubTest) Thread.Sleep(2000); else Thread.Sleep(200); expected = "{\"TotalChannels\":1,\"TotalOccupancy\":1,\"Channels\":{\"hello_my_channel\":{\"ChannelName\":\"hello_my_channel\",\"Occupancy\":1,\"Occupants\":[{\"Uuid\":\"mytestuuid\",\"State\":null}]}}}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/presence/sub_key/{0}/channel/{1}", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); ManualResetEvent hereNowManualEvent = new ManualResetEvent(false); pubnub.HereNow().Channels(new[] { channel }).Execute(new PNHereNowResultEx( (r, s) => { if (r == null) { return; } Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(r)); receivedHereNowMessage = true; hereNowManualEvent.Set(); })); hereNowManualEvent.WaitOne(manualResetEventWaitTimeout); expected = "{\"status\": 200, \"action\": \"leave\", \"message\": \"OK\", \"service\": \"Presence\"}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/presence/sub_key/{0}/channel/{1}/leave", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); pubnub.Unsubscribe<string>().Channels(new[] { channel }).Execute(); if (!PubnubCommon.EnableStubTest) Thread.Sleep(1000); else Thread.Sleep(100); } if (!pubnub.RemoveListener(listenerSubCallack)) { System.Diagnostics.Debug.WriteLine("ATTENTION: RemoveListener failed"); } pubnub.Destroy(); pubnub.PubnubUnitTest = null; pubnub = null; Assert.IsTrue(receivedHereNowMessage, "here_now message not received with cipher, ssl"); } [Test] public static void IfHereNowIsCalledThenItShouldReturnInfoSecret() { server.ClearRequests(); bool receivedHereNowMessage = false; PNConfiguration config = new PNConfiguration { PublishKey = PubnubCommon.PublishKey, SubscribeKey = PubnubCommon.SubscribeKey, Uuid = "mytestuuid", Secure = false }; if (PubnubCommon.PAMServerSideRun) { config.SecretKey = PubnubCommon.SecretKey; } else if (!string.IsNullOrEmpty(authKey) && !PubnubCommon.SuppressAuthKey) { config.AuthKey = authKey; } server.RunOnHttps(false); ManualResetEvent subscribeManualEvent = new ManualResetEvent(false); SubscribeCallback listenerSubCallack = new SubscribeCallbackExt( (o, m) => { Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(m)); }, (o, p) => { subscribeManualEvent.Set(); }, (o, s) => { Debug.WriteLine(string.Format("{0} {1} {2}", s.Operation, s.Category, s.StatusCode)); if (s.StatusCode != 200 || s.Error) { if (s.ErrorData != null) { Debug.WriteLine(s.ErrorData.Information); } } subscribeManualEvent.Set(); }); pubnub = createPubNubInstance(config); if (!pubnub.AddListener(listenerSubCallack)) { System.Diagnostics.Debug.WriteLine("ATTENTION: AddListener failed"); } string channel = "hello_my_channel"; manualResetEventWaitTimeout = 310 * 1000; string expected = "{\"t\":{\"t\":\"14828455563482572\",\"r\":7},\"m\":[]}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel)) .WithParameter("heartbeat", "300") .WithParameter("pnsdk", PubnubCommon.EncodedSDK) .WithParameter("requestid", "myRequestId") .WithParameter("timestamp", "1356998400") .WithParameter("tt", "0") .WithParameter("uuid", config.Uuid) .WithParameter("signature", "o3VANfuhvrxfff1jsBMOc6EQ4LCe8LXHGaDh58QBZFA=") .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); expected = "{}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); pubnub.Subscribe<string>().Channels(new [] { channel }).Execute(); subscribeManualEvent.WaitOne(manualResetEventWaitTimeout); if (!PubnubCommon.EnableStubTest) Thread.Sleep(2000); else Thread.Sleep(200); expected = "{\"TotalChannels\":1,\"TotalOccupancy\":1,\"Channels\":{\"hello_my_channel\":{\"ChannelName\":\"hello_my_channel\",\"Occupancy\":1,\"Occupants\":[{\"Uuid\":\"mytestuuid\",\"State\":null}]}}}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/presence/sub_key/{0}/channel/{1}", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); ManualResetEvent hereNowManualEvent = new ManualResetEvent(false); pubnub.HereNow().Channels(new [] { channel }).Execute(new PNHereNowResultEx( (r, s) => { if (r == null) { return; } Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(r)); receivedHereNowMessage = true; hereNowManualEvent.Set(); })); hereNowManualEvent.WaitOne(manualResetEventWaitTimeout); expected = "{\"status\": 200, \"action\": \"leave\", \"message\": \"OK\", \"service\": \"Presence\"}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/presence/sub_key/{0}/channel/{1}/leave", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); pubnub.Unsubscribe<string>().Channels(new [] { channel }).Execute(); if (!PubnubCommon.EnableStubTest) Thread.Sleep(1000); else Thread.Sleep(100); if (!pubnub.RemoveListener(listenerSubCallack)) { System.Diagnostics.Debug.WriteLine("ATTENTION: RemoveListener failed"); } pubnub.Destroy(); pubnub.PubnubUnitTest = null; pubnub = null; Assert.IsTrue(receivedHereNowMessage, "here_now message not received with secret key"); } [Test] public static void IfHereNowIsCalledThenItShouldReturnInfoSecretSSL() { server.ClearRequests(); bool receivedHereNowMessage = false; PNConfiguration config = new PNConfiguration { PublishKey = PubnubCommon.PublishKey, SubscribeKey = PubnubCommon.SubscribeKey, Uuid = "mytestuuid", Secure = true }; if (PubnubCommon.PAMServerSideRun) { config.SecretKey = PubnubCommon.SecretKey; } else if (!string.IsNullOrEmpty(authKey) && !PubnubCommon.SuppressAuthKey) { config.AuthKey = authKey; } server.RunOnHttps(true); ManualResetEvent subscribeManualEvent = new ManualResetEvent(false); SubscribeCallback listenerSubCallack = new SubscribeCallbackExt( (o, m) => { Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(m)); }, (o, p) => { subscribeManualEvent.Set(); }, (o, s) => { Debug.WriteLine(string.Format("{0} {1} {2}", s.Operation, s.Category, s.StatusCode)); if (s.StatusCode != 200 || s.Error) { if (s.ErrorData != null) { Debug.WriteLine(s.ErrorData.Information); } } subscribeManualEvent.Set(); }); pubnub = createPubNubInstance(config); if (!pubnub.AddListener(listenerSubCallack)) { System.Diagnostics.Debug.WriteLine("ATTENTION: AddListener failed"); } string channel = "hello_my_channel"; manualResetEventWaitTimeout = 310 * 1000; string expected = "{\"t\":{\"t\":\"14828455563482572\",\"r\":7},\"m\":[]}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel)) .WithParameter("heartbeat", "300") .WithParameter("pnsdk", PubnubCommon.EncodedSDK) .WithParameter("requestid", "myRequestId") .WithParameter("timestamp", "1356998400") .WithParameter("tt", "0") .WithParameter("uuid", config.Uuid) .WithParameter("signature", "o3VANfuhvrxfff1jsBMOc6EQ4LCe8LXHGaDh58QBZFA=") .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); expected = "{}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); pubnub.Subscribe<string>().Channels(new [] { channel }).Execute(); subscribeManualEvent.WaitOne(manualResetEventWaitTimeout); if (!PubnubCommon.EnableStubTest) Thread.Sleep(2000); else Thread.Sleep(200); expected = "{\"TotalChannels\":1,\"TotalOccupancy\":1,\"Channels\":{\"hello_my_channel\":{\"ChannelName\":\"hello_my_channel\",\"Occupancy\":1,\"Occupants\":[{\"Uuid\":\"mytestuuid\",\"State\":null}]}}}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/presence/sub_key/{0}/channel/{1}", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); ManualResetEvent hereNowManualEvent = new ManualResetEvent(false); pubnub.HereNow().Channels(new [] { channel }).Execute(new PNHereNowResultEx( (r, s) => { if (r == null) { return; } Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(r)); receivedHereNowMessage = true; hereNowManualEvent.Set(); })); hereNowManualEvent.WaitOne(manualResetEventWaitTimeout); expected = "{\"status\": 200, \"action\": \"leave\", \"message\": \"OK\", \"service\": \"Presence\"}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/presence/sub_key/{0}/channel/{1}/leave", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); pubnub.Unsubscribe<string>().Channels(new [] { channel }).Execute(); if (!PubnubCommon.EnableStubTest) Thread.Sleep(1000); else Thread.Sleep(100); if (!pubnub.RemoveListener(listenerSubCallack)) { System.Diagnostics.Debug.WriteLine("ATTENTION: RemoveListener failed"); } pubnub.Destroy(); pubnub.PubnubUnitTest = null; pubnub = null; Assert.IsTrue(receivedHereNowMessage, "here_now message not received ,with secret key, ssl"); } [Test] public static void IfHereNowIsCalledThenItShouldReturnInfoSSL() { server.ClearRequests(); bool receivedHereNowMessage = false; bool receivedErrorMessage = false; PNConfiguration config = new PNConfiguration { PublishKey = PubnubCommon.PublishKey, SubscribeKey = PubnubCommon.SubscribeKey, Uuid = "mytestuuid", Secure = true }; if (PubnubCommon.PAMServerSideRun) { config.SecretKey = PubnubCommon.SecretKey; } else if (!string.IsNullOrEmpty(authKey) && !PubnubCommon.SuppressAuthKey) { config.AuthKey = authKey; } server.RunOnHttps(true); ManualResetEvent subscribeManualEvent = new ManualResetEvent(false); SubscribeCallback listenerSubCallack = new SubscribeCallbackExt( (o, m) => { Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(m)); }, (o, p) => { subscribeManualEvent.Set(); }, (o, s) => { Debug.WriteLine(string.Format("{0} {1} {2}", s.Operation, s.Category, s.StatusCode)); if (s.StatusCode != 200 || s.Error) { receivedErrorMessage = true; if (s.ErrorData != null) { Debug.WriteLine(s.ErrorData.Information); } } subscribeManualEvent.Set(); }); pubnub = createPubNubInstance(config); if (!pubnub.AddListener(listenerSubCallack)) { System.Diagnostics.Debug.WriteLine("ATTENTION: AddListener failed"); } string channel = "hello_my_channel"; manualResetEventWaitTimeout = 310 * 1000; string expected = "{\"t\":{\"t\":\"14828455563482572\",\"r\":7},\"m\":[]}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel)) .WithParameter("heartbeat", "300") .WithParameter("pnsdk", PubnubCommon.EncodedSDK) .WithParameter("requestid", "myRequestId") .WithParameter("tt", "0") .WithParameter("uuid", config.Uuid) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); expected = "{}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); pubnub.Subscribe<string>().Channels(new [] { channel }).Execute(); subscribeManualEvent.WaitOne(manualResetEventWaitTimeout); if (!receivedErrorMessage) { if (!PubnubCommon.EnableStubTest) Thread.Sleep(2000); else Thread.Sleep(200); expected = "{\"TotalChannels\":1,\"TotalOccupancy\":1,\"Channels\":{\"hello_my_channel\":{\"ChannelName\":\"hello_my_channel\",\"Occupancy\":1,\"Occupants\":[{\"Uuid\":\"mytestuuid\",\"State\":null}]}}}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/presence/sub_key/{0}/channel/{1}", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); ManualResetEvent hereNowManualEvent = new ManualResetEvent(false); pubnub.HereNow().Channels(new[] { channel }).Execute(new PNHereNowResultEx( (r, s) => { if (r == null) { return; } Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(r)); receivedHereNowMessage = true; hereNowManualEvent.Set(); })); hereNowManualEvent.WaitOne(manualResetEventWaitTimeout); expected = "{\"status\": 200, \"action\": \"leave\", \"message\": \"OK\", \"service\": \"Presence\"}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/presence/sub_key/{0}/channel/{1}/leave", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); pubnub.Unsubscribe<string>().Channels(new[] { channel }).Execute(); if (!PubnubCommon.EnableStubTest) Thread.Sleep(1000); else Thread.Sleep(100); } if (!pubnub.RemoveListener(listenerSubCallack)) { System.Diagnostics.Debug.WriteLine("ATTENTION: RemoveListener failed"); } pubnub.Destroy(); pubnub.PubnubUnitTest = null; pubnub = null; Assert.IsTrue(receivedHereNowMessage, "here_now message not received with ssl"); } [Test] public static void IfHereNowIsCalledThenItShouldReturnInfoWithUserState() { server.ClearRequests(); bool receivedHereNowMessage = false; bool receivedErrorMessage = false; PNConfiguration config = new PNConfiguration { PublishKey = PubnubCommon.PublishKey, SubscribeKey = PubnubCommon.SubscribeKey, Uuid = "mytestuuid", Secure = false }; if (PubnubCommon.PAMServerSideRun) { config.SecretKey = PubnubCommon.SecretKey; } else if (!string.IsNullOrEmpty(authKey) && !PubnubCommon.SuppressAuthKey) { config.AuthKey = authKey; } server.RunOnHttps(false); ManualResetEvent subscribeManualEvent = new ManualResetEvent(false); SubscribeCallback listenerSubCallack = new SubscribeCallbackExt( (o, m) => { Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(m)); }, (o, p) => { subscribeManualEvent.Set(); }, (o, s) => { Debug.WriteLine(string.Format("{0} {1} {2}", s.Operation, s.Category, s.StatusCode)); if (s.StatusCode != 200 || s.Error) { receivedErrorMessage = true; if (s.ErrorData != null) { Debug.WriteLine(s.ErrorData.Information); } } subscribeManualEvent.Set(); }); pubnub = createPubNubInstance(config); if (!pubnub.AddListener(listenerSubCallack)) { System.Diagnostics.Debug.WriteLine("ATTENTION: AddListener failed"); } string channel = "hello_my_channel"; manualResetEventWaitTimeout = 310 * 1000; string expected = "{\"t\":{\"t\":\"14828455563482572\",\"r\":7},\"m\":[]}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel)) .WithParameter("heartbeat", "300") .WithParameter("pnsdk", PubnubCommon.EncodedSDK) .WithParameter("requestid", "myRequestId") .WithParameter("tt", "0") .WithParameter("uuid", config.Uuid) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); expected = "{}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); pubnub.Subscribe<string>().Channels(new [] { channel }).Execute(); subscribeManualEvent.WaitOne(manualResetEventWaitTimeout); if (!receivedErrorMessage) { if (!PubnubCommon.EnableStubTest) Thread.Sleep(2000); else Thread.Sleep(200); Dictionary<string, object> dicState = new Dictionary<string, object>(); dicState.Add("testkey", "testval"); expected = "{\"status\": 200, \"message\": \"OK\", \"payload\": {\"testkey\": \"testval\"}, \"service\": \"Presence\"}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/presence/sub_key/{0}/channel/{1}/uuid/{2}/data", PubnubCommon.SubscribeKey, channel, config.Uuid)) .WithParameter("pnsdk", PubnubCommon.EncodedSDK) .WithParameter("requestid", "myRequestId") .WithParameter("state", "%7B%22testkey%22%3A%22testval%22%7D") .WithParameter("timestamp", "1356998400") .WithParameter("uuid", config.Uuid) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); ManualResetEvent userStateManualEvent = new ManualResetEvent(false); pubnub.SetPresenceState() .Channels(new[] { channel }) .State(dicState) .Execute(new PNSetStateResultExt( (r, s) => { Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(r)); userStateManualEvent.Set(); })); userStateManualEvent.WaitOne(manualResetEventWaitTimeout); expected = "{\"status\": 200, \"message\": \"OK\", \"service\": \"Presence\", \"uuids\": [{\"state\": {\"testkey\": \"testval\"}, \"uuid\": \"mytestuuid\"}], \"occupancy\": 1}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/presence/sub_key/{0}/channel/{1}", PubnubCommon.SubscribeKey, channel)) .WithParameter("disable_uuids", "0") .WithParameter("pnsdk", PubnubCommon.EncodedSDK) .WithParameter("requestid", "myRequestId") .WithParameter("state", "1") .WithParameter("timestamp", "1356998400") .WithParameter("uuid", config.Uuid) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); ManualResetEvent hereNowManualEvent = new ManualResetEvent(false); pubnub.HereNow().Channels(new[] { channel }) .IncludeState(true) .IncludeUUIDs(true) .Execute(new PNHereNowResultEx( (r, s) => { if (r == null) { return; } Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(r)); receivedHereNowMessage = true; hereNowManualEvent.Set(); })); hereNowManualEvent.WaitOne(manualResetEventWaitTimeout); expected = "{\"status\": 200, \"action\": \"leave\", \"message\": \"OK\", \"service\": \"Presence\"}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/presence/sub_key/{0}/channel/{1}/leave", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); pubnub.Unsubscribe<string>().Channels(new[] { channel }).Execute(); if (!PubnubCommon.EnableStubTest) Thread.Sleep(1000); else Thread.Sleep(100); } if (!pubnub.RemoveListener(listenerSubCallack)) { System.Diagnostics.Debug.WriteLine("ATTENTION: RemoveListener failed"); } pubnub.Destroy(); pubnub.PubnubUnitTest = null; pubnub = null; Assert.IsTrue(receivedHereNowMessage, "here_now message not received with user state"); } [Test] public static void IfGlobalHereNowIsCalledThenItShouldReturnInfo() { server.ClearRequests(); bool receivedHereNowMessage = false; PNConfiguration config = new PNConfiguration { PublishKey = PubnubCommon.PublishKey, SubscribeKey = PubnubCommon.SubscribeKey, Uuid = "mytestuuid", Secure = false }; if (PubnubCommon.PAMServerSideRun) { config.SecretKey = PubnubCommon.SecretKey; } else if (!string.IsNullOrEmpty(authKey) && !PubnubCommon.SuppressAuthKey) { config.AuthKey = authKey; } server.RunOnHttps(false); ManualResetEvent subscribeManualEvent = new ManualResetEvent(false); SubscribeCallback listenerSubCallack = new SubscribeCallbackExt( (o, m) => { Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(m)); }, (o, p) => { subscribeManualEvent.Set(); }, (o, s) => { Debug.WriteLine(string.Format("{0} {1} {2}", s.Operation, s.Category, s.StatusCode)); if (s.StatusCode != 200 || s.Error) { if (s.ErrorData != null) { Debug.WriteLine(s.ErrorData.Information); } } subscribeManualEvent.Set(); }); pubnub = createPubNubInstance(config); if (!pubnub.AddListener(listenerSubCallack)) { System.Diagnostics.Debug.WriteLine("ATTENTION: AddListener failed"); } string channel = "hello_my_channel"; manualResetEventWaitTimeout = 310 * 1000; string expected = "{\"t\":{\"t\":\"14827658395446362\",\"r\":7},\"m\":[]}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel)) .WithParameter("heartbeat", "300") .WithParameter("pnsdk", PubnubCommon.EncodedSDK) .WithParameter("requestid", "myRequestId") .WithParameter("timestamp", "1356998400") .WithParameter("tt", "0") .WithParameter("uuid", config.Uuid) .WithParameter("signature", "o3VANfuhvrxfff1jsBMOc6EQ4LCe8LXHGaDh58QBZFA=") .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel)) .WithParameter("heartbeat", "300") .WithParameter("pnsdk", PubnubCommon.EncodedSDK) .WithParameter("requestid", "myRequestId") .WithParameter("tt", "0") .WithParameter("uuid", config.Uuid) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); expected = "{}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); pubnub.Subscribe<string>().Channels(new [] { channel }).Execute(); subscribeManualEvent.WaitOne(manualResetEventWaitTimeout); if (!PubnubCommon.EnableStubTest) Thread.Sleep(2000); else Thread.Sleep(200); expected = "{\"status\": 200, \"message\": \"OK\", \"payload\": {\"channels\": {}, \"total_channels\": 0, \"total_occupancy\": 0}, \"service\": \"Presence\"}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/presence/sub_key/{0}", PubnubCommon.SubscribeKey)) .WithParameter("disable_uuids", "0") .WithParameter("pnsdk", PubnubCommon.EncodedSDK) .WithParameter("requestid", "myRequestId") .WithParameter("state", "0") .WithParameter("timestamp", "1356998400") .WithParameter("uuid", config.Uuid) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); ManualResetEvent hereNowManualEvent = new ManualResetEvent(false); pubnub.HereNow().Execute(new PNHereNowResultEx( (r, s) => { if (r == null) { return; } Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(r)); receivedHereNowMessage = true; hereNowManualEvent.Set(); })); hereNowManualEvent.WaitOne(manualResetEventWaitTimeout); expected = "{\"status\": 200, \"action\": \"leave\", \"message\": \"OK\", \"service\": \"Presence\"}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/presence/sub_key/{0}/channel/{1}/leave", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); pubnub.Unsubscribe<string>().Channels(new [] { channel }).Execute(); if (!PubnubCommon.EnableStubTest) Thread.Sleep(1000); else Thread.Sleep(100); if (!pubnub.RemoveListener(listenerSubCallack)) { System.Diagnostics.Debug.WriteLine("ATTENTION: RemoveListener failed"); } pubnub.Destroy(); pubnub.PubnubUnitTest = null; pubnub = null; Assert.IsTrue(receivedHereNowMessage, "global_here_now message not received"); } [Test] public static void IfGlobalHereNowIsCalledThenItShouldReturnInfoWithUserState() { server.ClearRequests(); bool receivedHereNowMessage = false; PNConfiguration config = new PNConfiguration { PublishKey = PubnubCommon.PublishKey, SubscribeKey = PubnubCommon.SubscribeKey, Uuid = "mytestuuid", Secure = false }; if (PubnubCommon.PAMServerSideRun) { config.SecretKey = PubnubCommon.SecretKey; } else if (!string.IsNullOrEmpty(authKey) && !PubnubCommon.SuppressAuthKey) { config.AuthKey = authKey; } server.RunOnHttps(false); ManualResetEvent subscribeManualEvent = new ManualResetEvent(false); SubscribeCallback listenerSubCallack = new SubscribeCallbackExt( (o, m) => { Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(m)); }, (o, p) => { subscribeManualEvent.Set(); }, (o, s) => { Debug.WriteLine(string.Format("{0} {1} {2}", s.Operation, s.Category, s.StatusCode)); if (s.StatusCode != 200 || s.Error) { if (s.ErrorData != null) { Debug.WriteLine(s.ErrorData.Information); } } subscribeManualEvent.Set(); }); pubnub = createPubNubInstance(config); if (!pubnub.AddListener(listenerSubCallack)) { System.Diagnostics.Debug.WriteLine("ATTENTION: AddListener failed"); } string channel = "hello_my_channel"; string expected = "{\"t\":{\"t\":\"14827658395446362\",\"r\":7},\"m\":[]}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel)) .WithParameter("heartbeat", "300") .WithParameter("pnsdk", PubnubCommon.EncodedSDK) .WithParameter("requestid", "myRequestId") .WithParameter("tt", "0") .WithParameter("uuid", config.Uuid) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); expected = "{}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); manualResetEventWaitTimeout = (PubnubCommon.EnableStubTest ? 2000 : 310 * 1000); pubnub.Subscribe<string>().Channels(new [] { channel }).Execute(); subscribeManualEvent.WaitOne(manualResetEventWaitTimeout); Dictionary<string, object> dicState = new Dictionary<string, object>(); dicState.Add("testkey", "testval"); expected = "[[],\"14740704540745015\"]"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/presence/sub_key/{0}/channel/{1}/uuid/{2}/data", PubnubCommon.SubscribeKey, channel, config.Uuid)) .WithParameter("pnsdk", PubnubCommon.EncodedSDK) .WithParameter("requestid", "myRequestId") .WithParameter("state", "%7B%22testkey%22%3A%22testval%22%7D") .WithParameter("timestamp", "1356998400") .WithParameter("uuid", config.Uuid) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); ManualResetEvent userStateManualEvent = new ManualResetEvent(false); pubnub.SetPresenceState() .Channels(new [] { channel }) .State(dicState) .Execute(new PNSetStateResultExt( (r, s) => { Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(r)); userStateManualEvent.Set(); })); userStateManualEvent.WaitOne(manualResetEventWaitTimeout); expected = "{\"status\": 200, \"message\": \"OK\", \"payload\": {\"channels\": {\"bot_object\": {\"uuids\": [{\"uuid\": \"0ccff0c1-aa81-421b-8c2b-08a59bd5138c\"}], \"occupancy\": 1}, \"hello_my_channel\": {\"uuids\": [{\"state\": {\"testkey\": \"testval\"}, \"uuid\": \"mytestuuid\"}], \"occupancy\": 1}}, \"total_channels\": 2, \"total_occupancy\": 2}, \"service\": \"Presence\"}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/presence/sub_key/{0}", PubnubCommon.SubscribeKey)) .WithParameter("disable_uuids", "0") .WithParameter("pnsdk", PubnubCommon.EncodedSDK) .WithParameter("requestid", "myRequestId") .WithParameter("state", "1") .WithParameter("timestamp", "1356998400") .WithParameter("uuid", config.Uuid) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); ManualResetEvent hereNowManualEvent = new ManualResetEvent(false); pubnub.HereNow() .IncludeState(true) .IncludeUUIDs(true) .Execute(new PNHereNowResultEx( (r, s) => { if (r == null) { return; } Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(r)); receivedHereNowMessage = true; hereNowManualEvent.Set(); })); hereNowManualEvent.WaitOne(manualResetEventWaitTimeout); expected = "[[],\"14740704540745015\"]"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/presence/sub_key/{0}/channel/{1}/leave", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); pubnub.Unsubscribe<string>().Channels(new [] { channel }).Execute(); if (!PubnubCommon.EnableStubTest) Thread.Sleep(1000); else Thread.Sleep(100); if (!pubnub.RemoveListener(listenerSubCallack)) { System.Diagnostics.Debug.WriteLine("ATTENTION: RemoveListener failed"); } pubnub.Destroy(); pubnub.PubnubUnitTest = null; pubnub = null; Assert.IsTrue(receivedHereNowMessage, "global_here_now message not received for user state"); } [Test] public static void IfWhereNowIsCalledThenItShouldReturnInfo() { server.ClearRequests(); bool receivedWhereNowMessage = false; PNConfiguration config = new PNConfiguration { PublishKey = PubnubCommon.PublishKey, SubscribeKey = PubnubCommon.SubscribeKey, Uuid = "mytestuuid", Secure = false }; if (PubnubCommon.PAMServerSideRun) { config.SecretKey = PubnubCommon.SecretKey; } else if (!string.IsNullOrEmpty(authKey) && !PubnubCommon.SuppressAuthKey) { config.AuthKey = authKey; } server.RunOnHttps(false); ManualResetEvent subscribeManualEvent = new ManualResetEvent(false); SubscribeCallback listenerSubCallack = new SubscribeCallbackExt( (o, m) => { Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(m)); }, (o, p) => { subscribeManualEvent.Set(); }, (o, s) => { Debug.WriteLine(string.Format("{0} {1} {2}", s.Operation, s.Category, s.StatusCode)); if (s.StatusCode != 200 || s.Error) { if (s.ErrorData != null) { Debug.WriteLine(s.ErrorData.Information); } } subscribeManualEvent.Set(); }); pubnub = createPubNubInstance(config); if (!pubnub.AddListener(listenerSubCallack)) { System.Diagnostics.Debug.WriteLine("ATTENTION: AddListener failed"); } string channel = "hello_my_channel"; manualResetEventWaitTimeout = 310 * 1000; string expected = "{\"t\":{\"t\":\"14827658395446362\",\"r\":7},\"m\":[]}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel)) .WithParameter("heartbeat", "300") .WithParameter("pnsdk", PubnubCommon.EncodedSDK) .WithParameter("requestid", "myRequestId") .WithParameter("tt", "0") .WithParameter("uuid", config.Uuid) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); expected = "{}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); pubnub.Subscribe<string>().Channels(new [] { channel }).Execute(); subscribeManualEvent.WaitOne(manualResetEventWaitTimeout); if (!PubnubCommon.EnableStubTest) Thread.Sleep(2000); else Thread.Sleep(200); expected = "{\"status\": 200, \"message\": \"OK\", \"payload\": {\"channels\": {}, \"total_channels\": 0, \"total_occupancy\": 0}, \"service\": \"Presence\"}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/presence/sub_key/{0}/uuid/{1}", PubnubCommon.SubscribeKey, config.Uuid)) .WithParameter("pnsdk", PubnubCommon.EncodedSDK) .WithParameter("requestid", "myRequestId") .WithParameter("timestamp", "1356998400") .WithParameter("uuid", config.Uuid) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); ManualResetEvent whereNowManualEvent = new ManualResetEvent(false); pubnub.WhereNow().Uuid(config.Uuid).Execute(new PNWhereNowResultExt( (r, s) => { Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(r)); receivedWhereNowMessage = true; whereNowManualEvent.Set(); })); whereNowManualEvent.WaitOne(); expected = "[[],\"14740704540745015\"]"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/presence/sub_key/{0}/channel/{1}/leave", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); pubnub.Unsubscribe<string>().Channels(new [] { channel }).Execute(); if (!PubnubCommon.EnableStubTest) Thread.Sleep(1000); else Thread.Sleep(100); if (!pubnub.RemoveListener(listenerSubCallack)) { System.Diagnostics.Debug.WriteLine("ATTENTION: RemoveListener failed"); } pubnub.Destroy(); pubnub.PubnubUnitTest = null; pubnub = null; Assert.IsTrue(receivedWhereNowMessage, "where_now message not received"); } [Test] #if NET40 public static void IfWithAsyncWhereNowIsCalledThenItShouldReturnInfo() #else public static async Task IfWithAsyncWhereNowIsCalledThenItShouldReturnInfo() #endif { server.ClearRequests(); bool receivedWhereNowMessage = false; PNConfiguration config = new PNConfiguration { PublishKey = PubnubCommon.PublishKey, SubscribeKey = PubnubCommon.SubscribeKey, Uuid = "mytestuuid", Secure = false }; if (PubnubCommon.PAMServerSideRun) { config.SecretKey = PubnubCommon.SecretKey; } else if (!string.IsNullOrEmpty(authKey) && !PubnubCommon.SuppressAuthKey) { config.AuthKey = authKey; } server.RunOnHttps(false); ManualResetEvent subscribeManualEvent = new ManualResetEvent(false); SubscribeCallback listenerSubCallack = new SubscribeCallbackExt( (o, m) => { Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(m)); }, (o, p) => { subscribeManualEvent.Set(); }, (o, s) => { Debug.WriteLine(string.Format("{0} {1} {2}", s.Operation, s.Category, s.StatusCode)); if (s.StatusCode != 200 || s.Error) { if (s.ErrorData != null) { Debug.WriteLine(s.ErrorData.Information); } } subscribeManualEvent.Set(); }); pubnub = createPubNubInstance(config); if (!pubnub.AddListener(listenerSubCallack)) { System.Diagnostics.Debug.WriteLine("ATTENTION: AddListener failed"); } string channel = "hello_my_channel"; manualResetEventWaitTimeout = 310 * 1000; string expected = "{\"t\":{\"t\":\"14827658395446362\",\"r\":7},\"m\":[]}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel)) .WithParameter("heartbeat", "300") .WithParameter("pnsdk", PubnubCommon.EncodedSDK) .WithParameter("requestid", "myRequestId") .WithParameter("tt", "0") .WithParameter("uuid", config.Uuid) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); expected = "{}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); pubnub.Subscribe<string>().Channels(new[] { channel }).Execute(); subscribeManualEvent.WaitOne(manualResetEventWaitTimeout); if (!PubnubCommon.EnableStubTest) Thread.Sleep(2000); else Thread.Sleep(200); expected = "{\"status\": 200, \"message\": \"OK\", \"payload\": {\"channels\": {}, \"total_channels\": 0, \"total_occupancy\": 0}, \"service\": \"Presence\"}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/presence/sub_key/{0}/uuid/{1}", PubnubCommon.SubscribeKey, config.Uuid)) .WithParameter("pnsdk", PubnubCommon.EncodedSDK) .WithParameter("requestid", "myRequestId") .WithParameter("timestamp", "1356998400") .WithParameter("uuid", config.Uuid) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); #if NET40 PNResult<PNWhereNowResult> r = Task.Factory.StartNew(async () => await pubnub.WhereNow().Uuid(config.Uuid).ExecuteAsync()).Result.Result; #else PNResult<PNWhereNowResult> r = await pubnub.WhereNow().Uuid(config.Uuid).ExecuteAsync(); #endif if (r.Result != null) { Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(r)); receivedWhereNowMessage = true; } expected = "[[],\"14740704540745015\"]"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/presence/sub_key/{0}/channel/{1}/leave", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); pubnub.Unsubscribe<string>().Channels(new[] { channel }).Execute(); if (!PubnubCommon.EnableStubTest) Thread.Sleep(1000); else Thread.Sleep(100); if (!pubnub.RemoveListener(listenerSubCallack)) { System.Diagnostics.Debug.WriteLine("ATTENTION: RemoveListener failed"); } pubnub.Destroy(); pubnub.PubnubUnitTest = null; pubnub = null; Assert.IsTrue(receivedWhereNowMessage, "where_now message not received"); } [Test] public static void IfSetAndGetUserStateThenItShouldReturnInfo() { server.ClearRequests(); string customUUID = "mylocalmachine.mydomain.com"; bool receivedUserStateMessage = false; PNConfiguration config = new PNConfiguration { PublishKey = PubnubCommon.PublishKey, SubscribeKey = PubnubCommon.SubscribeKey, Uuid = "mytestuuid", Secure = false }; if (PubnubCommon.PAMServerSideRun) { config.SecretKey = PubnubCommon.SecretKey; } else if (!string.IsNullOrEmpty(authKey) && !PubnubCommon.SuppressAuthKey) { config.AuthKey = authKey; } server.RunOnHttps(false); pubnub = createPubNubInstance(config); pubnub.ChangeUUID(customUUID); manualResetEventWaitTimeout = 310 * 1000; string channel = "hello_my_channel"; Dictionary<string, object> dicState = new Dictionary<string, object>(); dicState.Add("testkey", "testval"); string expected = "{\"status\": 200, \"message\": \"OK\", \"payload\": {\"testkey\": \"testval\"}, \"service\": \"Presence\"}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/presence/sub_key/{0}/channel/{1}/uuid/{2}/data", PubnubCommon.SubscribeKey, channel, customUUID)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); ManualResetEvent userStateManualEvent = new ManualResetEvent(false); pubnub.SetPresenceState() .Channels(new [] { channel }) .State(dicState) .Execute(new PNSetStateResultExt( (r, s) => { Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(r)); receivedUserStateMessage = true; userStateManualEvent.Set(); })); userStateManualEvent.WaitOne(manualResetEventWaitTimeout); if (receivedUserStateMessage) { if (!PubnubCommon.EnableStubTest) Thread.Sleep(2000); else Thread.Sleep(200); receivedUserStateMessage = false; userStateManualEvent = new ManualResetEvent(false); expected = "{\"status\": 200, \"uuid\": \"mylocalmachine.mydomain.com\", \"service\": \"Presence\", \"message\": \"OK\", \"payload\": {\"testkey\": \"testval\"}, \"channel\": \"hello_my_channel\"}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/presence/sub_key/{0}/channel/{1}/uuid/{2}", PubnubCommon.SubscribeKey, channel, customUUID)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); pubnub.GetPresenceState() .Channels(new [] { channel }) .Execute(new PNGetStateResultExt( (r, s) => { Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(r)); receivedUserStateMessage = true; userStateManualEvent.Set(); })); userStateManualEvent.WaitOne(manualResetEventWaitTimeout); } pubnub.Destroy(); pubnub.PubnubUnitTest = null; pubnub = null; Assert.IsTrue(receivedUserStateMessage, "IfSetAndGetUserStateThenItShouldReturnInfo failed"); } [Test] public static void IfSetAndDeleteUserStateThenItShouldReturnInfo() { server.ClearRequests(); Request getRequest = new Request(); bool receivedUserStateMessage = false; PNConfiguration config = new PNConfiguration { PublishKey = PubnubCommon.PublishKey, SubscribeKey = PubnubCommon.SubscribeKey, Uuid = "mytestuuid", Secure = false }; if (PubnubCommon.PAMServerSideRun) { config.SecretKey = PubnubCommon.SecretKey; } else if (!string.IsNullOrEmpty(authKey) && !PubnubCommon.SuppressAuthKey) { config.AuthKey = authKey; } server.RunOnHttps(false); pubnub = createPubNubInstance(config); manualResetEventWaitTimeout = 310 * 1000; string channel = "hello_my_channel"; Dictionary<string, object> dicState = new Dictionary<string, object>(); dicState.Add("k", "v"); string expected = "{\"status\": 200, \"message\": \"OK\", \"payload\": {\"k\": \"v\"}, \"service\": \"Presence\"}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/presence/sub_key/{0}/channel/{1}/uuid/{2}/data", PubnubCommon.SubscribeKey, channel, config.Uuid)) .WithParameter("pnsdk", PubnubCommon.EncodedSDK) .WithParameter("requestid", "myRequestId") .WithParameter("state", "%7B%22k%22%3A%22v%22%7D") .WithParameter("timestamp", "1356998400") .WithParameter("uuid", config.Uuid) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); ManualResetEvent userStateManualEvent = new ManualResetEvent(false); pubnub.SetPresenceState() .Channels(new [] { channel }) .State(dicState) .Execute(new PNSetStateResultExt( (r, s) => { Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(r)); receivedUserStateMessage = true; userStateManualEvent.Set(); })); userStateManualEvent.WaitOne(manualResetEventWaitTimeout); if (!PubnubCommon.EnableStubTest) Thread.Sleep(2000); else Thread.Sleep(200); if (receivedUserStateMessage) { expected = "{\"status\": 200, \"uuid\": \"mytestuuid\", \"service\": \"Presence\", \"message\": \"OK\", \"payload\": {\"k\": \"v\"}, \"channel\": \"hello_my_channel\"}"; getRequest = new Request() .WithMethod("GET") .WithPath(String.Format("/v2/presence/sub_key/{0}/channel/{1}/uuid/{2}", PubnubCommon.SubscribeKey, channel, config.Uuid)) .WithParameter("pnsdk", PubnubCommon.EncodedSDK) .WithParameter("requestid", "myRequestId") .WithParameter("timestamp", "1356998400") .WithParameter("uuid", config.Uuid) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK); server.AddRequest(getRequest); receivedUserStateMessage = false; userStateManualEvent = new ManualResetEvent(false); pubnub.GetPresenceState() .Channels(new [] { channel }) .Execute(new PNGetStateResultExt( (r, s) => { Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(r)); receivedUserStateMessage = true; userStateManualEvent.Set(); })); userStateManualEvent.WaitOne(manualResetEventWaitTimeout); if (!PubnubCommon.EnableStubTest) Thread.Sleep(2000); else Thread.Sleep(200); } if (receivedUserStateMessage) { receivedUserStateMessage = false; userStateManualEvent = new ManualResetEvent(false); dicState = new Dictionary<string, object>(); dicState.Add("k", null); expected = "{\"status\": 200, \"message\": \"OK\", \"payload\": {\"k\": null}, \"service\": \"Presence\"}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/presence/sub_key/{0}/channel/{1}/uuid/{2}/data", PubnubCommon.SubscribeKey, channel, config.Uuid)) .WithParameter("pnsdk", PubnubCommon.EncodedSDK) .WithParameter("requestid", "myRequestId") .WithParameter("state", "%7B%22k%22%3Anull%7D") .WithParameter("timestamp", "1356998400") .WithParameter("uuid", config.Uuid) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); pubnub.SetPresenceState() .Channels(new [] { channel }) .State(dicState) .Execute(new PNSetStateResultExt( (r, s) => { Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(r)); receivedUserStateMessage = true; userStateManualEvent.Set(); })); userStateManualEvent.WaitOne(manualResetEventWaitTimeout); if (!PubnubCommon.EnableStubTest) Thread.Sleep(2000); else Thread.Sleep(200); } if (receivedUserStateMessage) { receivedUserStateMessage = false; expected = "{\"status\": 200, \"uuid\": \"mytestuuid\", \"service\": \"Presence\", \"message\": \"OK\", \"payload\": {\"k\": null}, \"channel\": \"hello_my_channel\"}"; getRequest.WithResponse(expected); server.AddRequest(getRequest); userStateManualEvent = new ManualResetEvent(false); pubnub.GetPresenceState() .Channels(new [] { channel }) .Execute(new PNGetStateResultExt( (r, s) => { Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(r)); receivedUserStateMessage = true; userStateManualEvent.Set(); })); userStateManualEvent.WaitOne(manualResetEventWaitTimeout); } pubnub.Destroy(); pubnub.PubnubUnitTest = null; pubnub = null; Assert.IsTrue(receivedUserStateMessage, "IfSetAndDeleteUserStateThenItShouldReturnInfo message not received"); } [Test] public static void ThenPresenceHeartbeatShouldReturnMessage() { server.ClearRequests(); bool receivedPresenceMessage = false; PNConfiguration config = new PNConfiguration { PublishKey = PubnubCommon.PublishKey, SubscribeKey = PubnubCommon.SubscribeKey, Uuid = "mytestuuid", Secure = false }; if (PubnubCommon.PAMServerSideRun) { config.SecretKey = PubnubCommon.SecretKey; } else if (!string.IsNullOrEmpty(authKey) && !PubnubCommon.SuppressAuthKey) { config.AuthKey = authKey; } server.RunOnHttps(false); ManualResetEvent presenceManualEvent = new ManualResetEvent(false); SubscribeCallback listenerSubCallack = new SubscribeCallbackExt( (o, m) => { Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(m)); }, (o, p) => { Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(p)); if (p.Event == "join") { receivedPresenceMessage = true; } presenceManualEvent.Set(); }, (o, s) => { Debug.WriteLine(string.Format("{0} {1} {2}", s.Operation, s.Category, s.StatusCode)); if (s.StatusCode != 200 || s.Error) { if (s.ErrorData != null) { Debug.WriteLine(s.ErrorData.Information); } presenceManualEvent.Set(); } }); pubnub = createPubNubInstance(config); if (!pubnub.AddListener(listenerSubCallack)) { System.Diagnostics.Debug.WriteLine("ATTENTION: AddListener failed"); } string channel = "hello_my_channel"; manualResetEventWaitTimeout = 310 * 1000; string expected = "{\"t\":{\"t\":\"14828440156769626\",\"r\":7},\"m\":[{\"a\":\"4\",\"f\":512,\"p\":{\"t\":\"14828440155770431\",\"r\":2},\"k\":\"demo-36\",\"c\":\"hello_my_channel-pnpres\",\"d\":{\"action\": \"join\", \"timestamp\": 1482844015, \"uuid\": \"mytestuuid\", \"occupancy\": 1},\"b\":\"hello_my_channel-pnpres\"}]}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel + "," + channel + "-pnpres")) .WithParameter("heartbeat", "300") .WithParameter("pnsdk", PubnubCommon.EncodedSDK) .WithParameter("requestid", "myRequestId") .WithParameter("timestamp", "1356998400") .WithParameter("tt", "0") .WithParameter("uuid", config.Uuid) .WithParameter("signature", "_JVs4gooSMhdgxRO6FNkk6HwlkyxqcRATHU5j3vkJ9s=") .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); expected = "{}"; server.AddRequest(new Request() .WithMethod("GET") .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel)) .WithResponse(expected) .WithStatusCode(System.Net.HttpStatusCode.OK)); pubnub.Subscribe<string>().Channels(new [] { channel }).WithPresence().Execute(); presenceManualEvent.WaitOne(manualResetEventWaitTimeout); if (!PubnubCommon.EnableStubTest) { Thread.Sleep(pubnub.PNConfig.PresenceTimeout + (3 * 1000)); } pubnub.Unsubscribe<string>().Channels(new [] { channel }).Execute(); if (!PubnubCommon.EnableStubTest) { Thread.Sleep(1000); } else { Thread.Sleep(100); } if (!pubnub.RemoveListener(listenerSubCallack)) { System.Diagnostics.Debug.WriteLine("ATTENTION: RemoveListener failed"); } pubnub.Destroy(); pubnub.PubnubUnitTest = null; pubnub = null; Assert.IsTrue(receivedPresenceMessage, "ThenPresenceHeartbeatShouldReturnMessage not received"); } } }
45.406926
394
0.520407
[ "MIT" ]
StockDrops/c-sharp
src/UnitTests/PubnubApi.Tests/WhenAClientIsPresented.cs
115,381
C#
// This file contains auto-generated code. namespace System { // Generated from `System.LocalDataStoreSlot` in `System.Threading.Thread, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a` public class LocalDataStoreSlot { // ERR: Stub generator didn't handle member: ~LocalDataStoreSlot } namespace Threading { // Generated from `System.Threading.ApartmentState` in `System.Threading.Thread, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a` public enum ApartmentState { MTA, STA, Unknown, } // Generated from `System.Threading.CompressedStack` in `System.Threading.Thread, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a` public class CompressedStack : System.Runtime.Serialization.ISerializable { public static System.Threading.CompressedStack Capture() => throw null; public System.Threading.CompressedStack CreateCopy() => throw null; public static System.Threading.CompressedStack GetCompressedStack() => throw null; public void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) => throw null; public static void Run(System.Threading.CompressedStack compressedStack, System.Threading.ContextCallback callback, object state) => throw null; } // Generated from `System.Threading.ParameterizedThreadStart` in `System.Threading.Thread, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a` public delegate void ParameterizedThreadStart(object obj); // Generated from `System.Threading.Thread` in `System.Threading.Thread, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a` public class Thread : System.Runtime.ConstrainedExecution.CriticalFinalizerObject { public void Abort(object stateInfo) => throw null; public void Abort() => throw null; public static System.LocalDataStoreSlot AllocateDataSlot() => throw null; public static System.LocalDataStoreSlot AllocateNamedDataSlot(string name) => throw null; public System.Threading.ApartmentState ApartmentState { get => throw null; set => throw null; } public static void BeginCriticalRegion() => throw null; public static void BeginThreadAffinity() => throw null; public System.Globalization.CultureInfo CurrentCulture { get => throw null; set => throw null; } public static System.Security.Principal.IPrincipal CurrentPrincipal { get => throw null; set => throw null; } public static System.Threading.Thread CurrentThread { get => throw null; } public System.Globalization.CultureInfo CurrentUICulture { get => throw null; set => throw null; } public void DisableComObjectEagerCleanup() => throw null; public static void EndCriticalRegion() => throw null; public static void EndThreadAffinity() => throw null; public System.Threading.ExecutionContext ExecutionContext { get => throw null; } public static void FreeNamedDataSlot(string name) => throw null; public System.Threading.ApartmentState GetApartmentState() => throw null; public System.Threading.CompressedStack GetCompressedStack() => throw null; public static int GetCurrentProcessorId() => throw null; public static object GetData(System.LocalDataStoreSlot slot) => throw null; public static System.AppDomain GetDomain() => throw null; public static int GetDomainID() => throw null; public override int GetHashCode() => throw null; public static System.LocalDataStoreSlot GetNamedDataSlot(string name) => throw null; public void Interrupt() => throw null; public bool IsAlive { get => throw null; } public bool IsBackground { get => throw null; set => throw null; } public bool IsThreadPoolThread { get => throw null; } public void Join() => throw null; public bool Join(int millisecondsTimeout) => throw null; public bool Join(System.TimeSpan timeout) => throw null; public int ManagedThreadId { get => throw null; } public static void MemoryBarrier() => throw null; public string Name { get => throw null; set => throw null; } public System.Threading.ThreadPriority Priority { get => throw null; set => throw null; } public static void ResetAbort() => throw null; public void Resume() => throw null; public void SetApartmentState(System.Threading.ApartmentState state) => throw null; public void SetCompressedStack(System.Threading.CompressedStack stack) => throw null; public static void SetData(System.LocalDataStoreSlot slot, object data) => throw null; public static void Sleep(int millisecondsTimeout) => throw null; public static void Sleep(System.TimeSpan timeout) => throw null; public static void SpinWait(int iterations) => throw null; public void Start(object parameter) => throw null; public void Start() => throw null; public void Suspend() => throw null; public Thread(System.Threading.ThreadStart start, int maxStackSize) => throw null; public Thread(System.Threading.ThreadStart start) => throw null; public Thread(System.Threading.ParameterizedThreadStart start, int maxStackSize) => throw null; public Thread(System.Threading.ParameterizedThreadStart start) => throw null; public System.Threading.ThreadState ThreadState { get => throw null; } public bool TrySetApartmentState(System.Threading.ApartmentState state) => throw null; public static object VolatileRead(ref object address) => throw null; public static int VolatileRead(ref int address) => throw null; public static float VolatileRead(ref float address) => throw null; public static double VolatileRead(ref double address) => throw null; public static System.UIntPtr VolatileRead(ref System.UIntPtr address) => throw null; public static System.UInt64 VolatileRead(ref System.UInt64 address) => throw null; public static System.UInt32 VolatileRead(ref System.UInt32 address) => throw null; public static System.UInt16 VolatileRead(ref System.UInt16 address) => throw null; public static System.SByte VolatileRead(ref System.SByte address) => throw null; public static System.IntPtr VolatileRead(ref System.IntPtr address) => throw null; public static System.Int64 VolatileRead(ref System.Int64 address) => throw null; public static System.Int16 VolatileRead(ref System.Int16 address) => throw null; public static System.Byte VolatileRead(ref System.Byte address) => throw null; public static void VolatileWrite(ref object address, object value) => throw null; public static void VolatileWrite(ref int address, int value) => throw null; public static void VolatileWrite(ref float address, float value) => throw null; public static void VolatileWrite(ref double address, double value) => throw null; public static void VolatileWrite(ref System.UIntPtr address, System.UIntPtr value) => throw null; public static void VolatileWrite(ref System.UInt64 address, System.UInt64 value) => throw null; public static void VolatileWrite(ref System.UInt32 address, System.UInt32 value) => throw null; public static void VolatileWrite(ref System.UInt16 address, System.UInt16 value) => throw null; public static void VolatileWrite(ref System.SByte address, System.SByte value) => throw null; public static void VolatileWrite(ref System.IntPtr address, System.IntPtr value) => throw null; public static void VolatileWrite(ref System.Int64 address, System.Int64 value) => throw null; public static void VolatileWrite(ref System.Int16 address, System.Int16 value) => throw null; public static void VolatileWrite(ref System.Byte address, System.Byte value) => throw null; public static bool Yield() => throw null; // ERR: Stub generator didn't handle member: ~Thread } // Generated from `System.Threading.ThreadAbortException` in `System.Threading.Thread, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a` public class ThreadAbortException : System.SystemException { public object ExceptionState { get => throw null; } } // Generated from `System.Threading.ThreadExceptionEventArgs` in `System.Threading.Thread, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a` public class ThreadExceptionEventArgs : System.EventArgs { public System.Exception Exception { get => throw null; } public ThreadExceptionEventArgs(System.Exception t) => throw null; } // Generated from `System.Threading.ThreadExceptionEventHandler` in `System.Threading.Thread, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a` public delegate void ThreadExceptionEventHandler(object sender, System.Threading.ThreadExceptionEventArgs e); // Generated from `System.Threading.ThreadInterruptedException` in `System.Threading.Thread, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a` public class ThreadInterruptedException : System.SystemException { public ThreadInterruptedException(string message, System.Exception innerException) => throw null; public ThreadInterruptedException(string message) => throw null; public ThreadInterruptedException() => throw null; protected ThreadInterruptedException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) => throw null; } // Generated from `System.Threading.ThreadPriority` in `System.Threading.Thread, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a` public enum ThreadPriority { AboveNormal, BelowNormal, Highest, Lowest, Normal, } // Generated from `System.Threading.ThreadStart` in `System.Threading.Thread, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a` public delegate void ThreadStart(); // Generated from `System.Threading.ThreadStartException` in `System.Threading.Thread, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a` public class ThreadStartException : System.SystemException { } // Generated from `System.Threading.ThreadState` in `System.Threading.Thread, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a` [System.Flags] public enum ThreadState { AbortRequested, Aborted, Background, Running, StopRequested, Stopped, SuspendRequested, Suspended, Unstarted, WaitSleepJoin, } // Generated from `System.Threading.ThreadStateException` in `System.Threading.Thread, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a` public class ThreadStateException : System.SystemException { public ThreadStateException(string message, System.Exception innerException) => throw null; public ThreadStateException(string message) => throw null; public ThreadStateException() => throw null; protected ThreadStateException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) => throw null; } } }
64.497354
171
0.684167
[ "MIT" ]
Bhagyanekraje/codeql
csharp/ql/test/resources/stubs/_frameworks/Microsoft.NETCore.App/System.Threading.Thread.cs
12,190
C#
 namespace Microsoft.PowerTools.MiddleClickScroll { using System.ComponentModel.Composition; using VisualStudio.TelemetryForPPT; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; [Export(typeof(IMouseProcessorProvider))] [Name("MiddleClickScroll")] [Order(Before = "UrlClickMouseProcessor")] [ContentType("text")] [TextViewRole(PredefinedTextViewRoles.Document)] internal sealed class MiddleClickScrollFactory : IMouseProcessorProvider { #pragma warning disable 649 [Export] [Name("MiddleClickScrollLayer")] [Order(Before = PredefinedAdornmentLayers.Selection)] internal AdornmentLayerDefinition viewLayerDefinition; #pragma warning restore 649 private ITelemetrySession _telemetrySession; public IMouseProcessor GetAssociatedProcessor(IWpfTextView textView) { if (_telemetrySession == null) { _telemetrySession = TelemetrySessionForPPT.Create(this.GetType().Assembly); } return MiddleClickScroll.Create(textView, _telemetrySession); } } }
32.027778
91
0.707719
[ "MIT" ]
HydAu/VS-PPT
src/MiddleClickScroll/MiddleClickScrollFactory.cs
1,155
C#
using System.Text; using MetX.Standard.IO; namespace MetX.Standard.Data.Factory { public class PowerShellGatherer : GatherProvider { public override int GatherNow(StringBuilder sb, string[] args) { switch (args.Length) { case 1: sb.Append(FileSystem.GatherOutput(args[0], null, null, -1)); return 0; case 2: sb.Append(FileSystem.GatherOutput(args[0], args[1], null, -1)); return 0; case 3: sb.Append(FileSystem.GatherOutput(args[0], args[1], args[2], int.Parse(args[3]))); return 0; } return -1; } } }
29.038462
102
0.484768
[ "ISC" ]
wrawlsqw/xlg
MetX/MetX.Standard/Data/Factory/PowerShellGatherer.cs
755
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using NuGet.Frameworks; using NuGet.Packaging; using NuGet.Test.Utility; using Xunit; namespace NuGet.Commands.Test { public class TestUtilityTests { [Fact] public async Task TestUtility_Solution() { using (var pathContext = new SimpleTestPathContext()) { // Arrange && Act var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot); var projectA = SimpleTestProjectContext.CreateNETCore( "a", pathContext.SolutionRoot, NuGetFramework.Parse("net45")); var packageX = new SimpleTestPackageContext() { Id = "x", Version = "1.0.0" }; var projectJson = JObject.Parse(@"{ 'dependencies': { }, 'frameworks': { 'net45': { } } }"); var projectB = SimpleTestProjectContext.CreateUAP( "b", pathContext.SolutionRoot, NuGetFramework.Parse("net45"), projectJson); projectA.AddPackageToAllFrameworks(packageX); solution.Projects.Add(projectA); solution.Projects.Add(projectB); solution.Create(pathContext.SolutionRoot); await SimpleTestPackageUtility.CreateFolderFeedV3Async( pathContext.PackageSource, PackageSaveMode.Defaultv3, packageX); // Assert Assert.True(File.Exists(Path.Combine(pathContext.SolutionRoot, "solution.sln"))); Assert.True(File.Exists(Path.Combine(pathContext.SolutionRoot, "a", "a.csproj"))); Assert.True(File.Exists(Path.Combine(pathContext.WorkingDirectory, "NuGet.Config"))); Assert.True(File.Exists(Path.Combine(pathContext.SolutionRoot, "b", "b.csproj"))); Assert.True(File.Exists(Path.Combine(pathContext.SolutionRoot, "b", "project.json"))); } } } }
37.39726
111
0.510623
[ "Apache-2.0" ]
0xced/NuGet.Client
test/NuGet.Core.Tests/NuGet.Commands.Test/TestUtilityTests.cs
2,730
C#
using System; using Subgurim.Maps.Core.Helpers; namespace Subgurim.Maps.Core.Google.Events { [Serializable] internal sealed class PolylineEvents : StringEnum { /// <summary> /// This event is fired when the DOM click event is fired on the Polyline. /// </summary> public static readonly PolylineEvents Click = new PolylineEvents(1, "click"); /// <summary> /// This event is fired when the DOM dblclick event is fired on the Polyline. /// </summary> public static readonly PolylineEvents DblClick = new PolylineEvents(2, "dblclick"); /// <summary> /// This event is fired when the DOM mousedown event is fired on the Polyline. /// </summary> public static readonly PolylineEvents MouseDown = new PolylineEvents(3, "mousedown"); /// <summary> /// This event is fired when the DOM mousemove event is fired on the Polyline. /// </summary> public static readonly PolylineEvents MouseMove = new PolylineEvents(4, "mousemove"); /// <summary> /// This event is fired on Polyline mouseout. /// </summary> public static readonly PolylineEvents MouseOut = new PolylineEvents(5, "mouseout"); /// <summary> /// This event is fired on Polyline mouseover. /// </summary> public static readonly PolylineEvents MouseOver = new PolylineEvents(6, "mouseover"); /// <summary> /// This event is fired when the DOM mouseup event is fired on the Polyline. /// </summary> public static readonly PolylineEvents MouseUp = new PolylineEvents(7, "mouseup"); /// <summary> /// This event is fired when the Polyline is right-clicked on. /// </summary> public static readonly PolylineEvents RightClick = new PolylineEvents(8, "rightclick"); private PolylineEvents(int value, string name) : base(value, name) { } } }
37.849057
95
0.623131
[ "Apache-2.0" ]
subgurim/subgurim-maps-core
Subgurim.Maps.Core/Google/Events/PolylineEvents.cs
2,008
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Assets.Scripts { public class AnimationManager : Singleton<AnimationManager> { private string currentAnimation; private string currentAnimator; private Dictionary<string, Animator> animatorLookup = new Dictionary<string, Animator>(); public void addAnimator(string animatorName, Animator animator) { if (animatorLookup.ContainsKey(animatorName)) { animatorLookup[animatorName] = animator; return; } animatorLookup.Add(animatorName, animator); } public void changeAnimation(string animatorName, string animationString) { if (currentAnimation == animationString && currentAnimator == animatorName) return; animatorLookup[animatorName].Play(animationString); currentAnimation = animationString; currentAnimator = animatorName; } } }
30.941176
97
0.640684
[ "MIT" ]
HemanthRj96/Repos-GMTK_Connections
GMTK-Connections/Assets/Scripts/AnimationManager.cs
1,054
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.S3 { /// <summary> /// Manages S3 bucket-level Public Access Block configuration. For more information about these settings, see the [AWS S3 Block Public Access documentation](https://docs.aws.amazon.com/AmazonS3/latest/dev/access-control-block-public-access.html). /// /// ## Example Usage /// /// ```csharp /// using Pulumi; /// using Aws = Pulumi.Aws; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var exampleBucket = new Aws.S3.Bucket("exampleBucket", new Aws.S3.BucketArgs /// { /// }); /// var exampleBucketPublicAccessBlock = new Aws.S3.BucketPublicAccessBlock("exampleBucketPublicAccessBlock", new Aws.S3.BucketPublicAccessBlockArgs /// { /// BlockPublicAcls = true, /// BlockPublicPolicy = true, /// Bucket = exampleBucket.Id, /// }); /// } /// /// } /// ``` /// </summary> public partial class BucketPublicAccessBlock : Pulumi.CustomResource { /// <summary> /// Whether Amazon S3 should block public ACLs for this bucket. Defaults to `false`. Enabling this setting does not affect existing policies or ACLs. When set to `true` causes the following behavior: /// * PUT Bucket acl and PUT Object acl calls will fail if the specified ACL allows public access. /// * PUT Object calls will fail if the request includes an object ACL. /// </summary> [Output("blockPublicAcls")] public Output<bool?> BlockPublicAcls { get; private set; } = null!; /// <summary> /// Whether Amazon S3 should block public bucket policies for this bucket. Defaults to `false`. Enabling this setting does not affect the existing bucket policy. When set to `true` causes Amazon S3 to: /// * Reject calls to PUT Bucket policy if the specified bucket policy allows public access. /// </summary> [Output("blockPublicPolicy")] public Output<bool?> BlockPublicPolicy { get; private set; } = null!; /// <summary> /// S3 Bucket to which this Public Access Block configuration should be applied. /// </summary> [Output("bucket")] public Output<string> Bucket { get; private set; } = null!; /// <summary> /// Whether Amazon S3 should ignore public ACLs for this bucket. Defaults to `false`. Enabling this setting does not affect the persistence of any existing ACLs and doesn't prevent new public ACLs from being set. When set to `true` causes Amazon S3 to: /// * Ignore public ACLs on this bucket and any objects that it contains. /// </summary> [Output("ignorePublicAcls")] public Output<bool?> IgnorePublicAcls { get; private set; } = null!; /// <summary> /// Whether Amazon S3 should restrict public bucket policies for this bucket. Defaults to `false`. Enabling this setting does not affect the previously stored bucket policy, except that public and cross-account access within the public bucket policy, including non-public delegation to specific accounts, is blocked. When set to `true`: /// * Only the bucket owner and AWS Services can access this buckets if it has a public policy. /// </summary> [Output("restrictPublicBuckets")] public Output<bool?> RestrictPublicBuckets { get; private set; } = null!; /// <summary> /// Create a BucketPublicAccessBlock 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 BucketPublicAccessBlock(string name, BucketPublicAccessBlockArgs args, CustomResourceOptions? options = null) : base("aws:s3/bucketPublicAccessBlock:BucketPublicAccessBlock", name, args ?? new BucketPublicAccessBlockArgs(), MakeResourceOptions(options, "")) { } private BucketPublicAccessBlock(string name, Input<string> id, BucketPublicAccessBlockState? state = null, CustomResourceOptions? options = null) : base("aws:s3/bucketPublicAccessBlock:BucketPublicAccessBlock", name, state, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing BucketPublicAccessBlock resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="state">Any extra arguments used during the lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static BucketPublicAccessBlock Get(string name, Input<string> id, BucketPublicAccessBlockState? state = null, CustomResourceOptions? options = null) { return new BucketPublicAccessBlock(name, id, state, options); } } public sealed class BucketPublicAccessBlockArgs : Pulumi.ResourceArgs { /// <summary> /// Whether Amazon S3 should block public ACLs for this bucket. Defaults to `false`. Enabling this setting does not affect existing policies or ACLs. When set to `true` causes the following behavior: /// * PUT Bucket acl and PUT Object acl calls will fail if the specified ACL allows public access. /// * PUT Object calls will fail if the request includes an object ACL. /// </summary> [Input("blockPublicAcls")] public Input<bool>? BlockPublicAcls { get; set; } /// <summary> /// Whether Amazon S3 should block public bucket policies for this bucket. Defaults to `false`. Enabling this setting does not affect the existing bucket policy. When set to `true` causes Amazon S3 to: /// * Reject calls to PUT Bucket policy if the specified bucket policy allows public access. /// </summary> [Input("blockPublicPolicy")] public Input<bool>? BlockPublicPolicy { get; set; } /// <summary> /// S3 Bucket to which this Public Access Block configuration should be applied. /// </summary> [Input("bucket", required: true)] public Input<string> Bucket { get; set; } = null!; /// <summary> /// Whether Amazon S3 should ignore public ACLs for this bucket. Defaults to `false`. Enabling this setting does not affect the persistence of any existing ACLs and doesn't prevent new public ACLs from being set. When set to `true` causes Amazon S3 to: /// * Ignore public ACLs on this bucket and any objects that it contains. /// </summary> [Input("ignorePublicAcls")] public Input<bool>? IgnorePublicAcls { get; set; } /// <summary> /// Whether Amazon S3 should restrict public bucket policies for this bucket. Defaults to `false`. Enabling this setting does not affect the previously stored bucket policy, except that public and cross-account access within the public bucket policy, including non-public delegation to specific accounts, is blocked. When set to `true`: /// * Only the bucket owner and AWS Services can access this buckets if it has a public policy. /// </summary> [Input("restrictPublicBuckets")] public Input<bool>? RestrictPublicBuckets { get; set; } public BucketPublicAccessBlockArgs() { } } public sealed class BucketPublicAccessBlockState : Pulumi.ResourceArgs { /// <summary> /// Whether Amazon S3 should block public ACLs for this bucket. Defaults to `false`. Enabling this setting does not affect existing policies or ACLs. When set to `true` causes the following behavior: /// * PUT Bucket acl and PUT Object acl calls will fail if the specified ACL allows public access. /// * PUT Object calls will fail if the request includes an object ACL. /// </summary> [Input("blockPublicAcls")] public Input<bool>? BlockPublicAcls { get; set; } /// <summary> /// Whether Amazon S3 should block public bucket policies for this bucket. Defaults to `false`. Enabling this setting does not affect the existing bucket policy. When set to `true` causes Amazon S3 to: /// * Reject calls to PUT Bucket policy if the specified bucket policy allows public access. /// </summary> [Input("blockPublicPolicy")] public Input<bool>? BlockPublicPolicy { get; set; } /// <summary> /// S3 Bucket to which this Public Access Block configuration should be applied. /// </summary> [Input("bucket")] public Input<string>? Bucket { get; set; } /// <summary> /// Whether Amazon S3 should ignore public ACLs for this bucket. Defaults to `false`. Enabling this setting does not affect the persistence of any existing ACLs and doesn't prevent new public ACLs from being set. When set to `true` causes Amazon S3 to: /// * Ignore public ACLs on this bucket and any objects that it contains. /// </summary> [Input("ignorePublicAcls")] public Input<bool>? IgnorePublicAcls { get; set; } /// <summary> /// Whether Amazon S3 should restrict public bucket policies for this bucket. Defaults to `false`. Enabling this setting does not affect the previously stored bucket policy, except that public and cross-account access within the public bucket policy, including non-public delegation to specific accounts, is blocked. When set to `true`: /// * Only the bucket owner and AWS Services can access this buckets if it has a public policy. /// </summary> [Input("restrictPublicBuckets")] public Input<bool>? RestrictPublicBuckets { get; set; } public BucketPublicAccessBlockState() { } } }
54.333333
344
0.65581
[ "ECL-2.0", "Apache-2.0" ]
michael-golden/pulumi-aws
sdk/dotnet/S3/BucketPublicAccessBlock.cs
11,084
C#
using System; using System.IO; namespace qbusSRL.Utility.Helpers.Encoding { /// <summary> /// http://anubis.dkuug.dk/JTC1/SC2/WG2/docs/n1335 /// /// http://www.cl.cam.ac.uk/~mgk25/ucs/ISO-10646-UTF-8.html /// /// http://www.unicode.org/versions/corrigendum1.html /// /// http://www.ietf.org/rfc/rfc2279.txt /// /// </summary> public class Utf8Checker : IUtf8Checker { /// <summary> /// /// </summary> /// <param name="fileName"></param> /// <returns></returns> public bool Check(string fileName) { using (BufferedStream fstream = new BufferedStream(File.OpenRead(fileName))) { return this.IsUtf8(fstream); } } /// <summary> /// Check if stream is utf8 encoded. /// Notice: stream is read completely in memory! /// </summary> /// <param name="stream">Stream to read from.</param> /// <returns>True if the whole stream is utf8 encoded.</returns> public bool IsUtf8(Stream stream) { int count = 4 * 1024; byte[] buffer; int read; while (true) { buffer = new byte[count]; stream.Seek(0, SeekOrigin.Begin); read = stream.Read(buffer, 0, count); if (read < count) { break; } buffer = null; count *= 2; } return IsUtf8(buffer, read); } /// <summary> /// /// </summary> /// <param name="buffer"></param> /// <param name="length"></param> /// <returns></returns> public static bool IsUtf8(byte[] buffer, int length) { int position = 0; int bytes = 0; while (position < length) { if (!IsValid(buffer, position, length, ref bytes)) { return false; } position += bytes; } return true; } /// <summary> /// /// </summary> /// <param name="buffer"></param> /// <param name="position"></param> /// <param name="length"></param> /// <param name="bytes"></param> /// <returns></returns> public static bool IsValid(byte[] buffer, int position, int length, ref int bytes) { if (length > buffer.Length) { throw new ArgumentException("Invalid length"); } if (position > length - 1) { bytes = 0; return true; } byte ch = buffer[position]; if (ch <= 0x7F) { bytes = 1; return true; } if (ch >= 0xc2 && ch <= 0xdf) { if (position >= length - 2) { bytes = 0; return false; } if (buffer[position + 1] < 0x80 || buffer[position + 1] > 0xbf) { bytes = 0; return false; } bytes = 2; return true; } if (ch == 0xe0) { if (position >= length - 3) { bytes = 0; return false; } if (buffer[position + 1] < 0xa0 || buffer[position + 1] > 0xbf || buffer[position + 2] < 0x80 || buffer[position + 2] > 0xbf) { bytes = 0; return false; } bytes = 3; return true; } if (ch >= 0xe1 && ch <= 0xef) { if (position >= length - 3) { bytes = 0; return false; } if (buffer[position + 1] < 0x80 || buffer[position + 1] > 0xbf || buffer[position + 2] < 0x80 || buffer[position + 2] > 0xbf) { bytes = 0; return false; } bytes = 3; return true; } if (ch == 0xf0) { if (position >= length - 4) { bytes = 0; return false; } if (buffer[position + 1] < 0x90 || buffer[position + 1] > 0xbf || buffer[position + 2] < 0x80 || buffer[position + 2] > 0xbf || buffer[position + 3] < 0x80 || buffer[position + 3] > 0xbf) { bytes = 0; return false; } bytes = 4; return true; } if (ch == 0xf4) { if (position >= length - 4) { bytes = 0; return false; } if (buffer[position + 1] < 0x80 || buffer[position + 1] > 0x8f || buffer[position + 2] < 0x80 || buffer[position + 2] > 0xbf || buffer[position + 3] < 0x80 || buffer[position + 3] > 0xbf) { bytes = 0; return false; } bytes = 4; return true; } if (ch >= 0xf1 && ch <= 0xf3) { if (position >= length - 4) { bytes = 0; return false; } if (buffer[position + 1] < 0x80 || buffer[position + 1] > 0xbf || buffer[position + 2] < 0x80 || buffer[position + 2] > 0xbf || buffer[position + 3] < 0x80 || buffer[position + 3] > 0xbf) { bytes = 0; return false; } bytes = 4; return true; } return false; } } }
28.290179
90
0.366104
[ "BSD-3-Clause" ]
seyfiyumlu/vMerge2019
Utility/Helpers/Encoding/Utf8Checker.cs
6,339
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; public struct ValX0 {} public struct ValY0 {} public struct ValX1<T> {} public struct ValY1<T> {} public struct ValX2<T,U> {} public struct ValY2<T,U>{} public struct ValX3<T,U,V>{} public struct ValY3<T,U,V>{} public class RefX0 {} public class RefY0 {} public class RefX1<T> {} public class RefY1<T> {} public class RefX2<T,U> {} public class RefY2<T,U>{} public class RefX3<T,U,V>{} public class RefY3<T,U,V>{} public class GenException<T> : Exception {} public class Gen { public void InternalExceptionTest<U>(bool throwException) { try { if (throwException) { throw new GenException<U>(); } if (throwException) { Test.Eval(false); } } catch(Exception E) { Test.Eval(E is GenException<U>); } } public void ExceptionTest<U>(bool throwException) { InternalExceptionTest<U>(throwException); } } public class Test { public static int counter = 0; public static bool result = true; public static void Eval(bool exp) { counter++; if (!exp) { result = exp; Console.WriteLine("Test Failed at location: " + counter); } } public static int Main() { new Gen().ExceptionTest<int>(true); new Gen().ExceptionTest<double>(true); new Gen().ExceptionTest<string>(true); new Gen().ExceptionTest<object>(true); new Gen().ExceptionTest<Guid>(true); new Gen().ExceptionTest<int[]>(true); new Gen().ExceptionTest<double[,]>(true); new Gen().ExceptionTest<string[][][]>(true); new Gen().ExceptionTest<object[,,,]>(true); new Gen().ExceptionTest<Guid[][,,,][]>(true); new Gen().ExceptionTest<RefX1<int>[]>(true); new Gen().ExceptionTest<RefX1<double>[,]>(true); new Gen().ExceptionTest<RefX1<string>[][][]>(true); new Gen().ExceptionTest<RefX1<object>[,,,]>(true); new Gen().ExceptionTest<RefX1<Guid>[][,,,][]>(true); new Gen().ExceptionTest<RefX2<int,int>[]>(true); new Gen().ExceptionTest<RefX2<double,double>[,]>(true); new Gen().ExceptionTest<RefX2<string,string>[][][]>(true); new Gen().ExceptionTest<RefX2<object,object>[,,,]>(true); new Gen().ExceptionTest<RefX2<Guid,Guid>[][,,,][]>(true); new Gen().ExceptionTest<ValX1<int>[]>(true); new Gen().ExceptionTest<ValX1<double>[,]>(true); new Gen().ExceptionTest<ValX1<string>[][][]>(true); new Gen().ExceptionTest<ValX1<object>[,,,]>(true); new Gen().ExceptionTest<ValX1<Guid>[][,,,][]>(true); new Gen().ExceptionTest<ValX2<int,int>[]>(true); new Gen().ExceptionTest<ValX2<double,double>[,]>(true); new Gen().ExceptionTest<ValX2<string,string>[][][]>(true); new Gen().ExceptionTest<ValX2<object,object>[,,,]>(true); new Gen().ExceptionTest<ValX2<Guid,Guid>[][,,,][]>(true); new Gen().ExceptionTest<RefX1<int>>(true); new Gen().ExceptionTest<RefX1<ValX1<int>>>(true); new Gen().ExceptionTest<RefX2<int,string>>(true); new Gen().ExceptionTest<RefX3<int,string,Guid>>(true); new Gen().ExceptionTest<RefX1<RefX1<int>>>(true); new Gen().ExceptionTest<RefX1<RefX1<RefX1<string>>>>(true); new Gen().ExceptionTest<RefX1<RefX1<RefX1<RefX1<Guid>>>>>(true); new Gen().ExceptionTest<RefX1<RefX2<int,string>>>(true); new Gen().ExceptionTest<RefX2<RefX2<RefX1<int>,RefX3<int,string, RefX1<RefX2<int,string>>>>,RefX2<RefX1<int>,RefX3<int,string, RefX1<RefX2<int,string>>>>>>(true); new Gen().ExceptionTest<RefX3<RefX1<int[][,,,]>,RefX2<object[,,,][][],Guid[][][]>,RefX3<double[,,,,,,,,,,],Guid[][][][,,,,][,,,,][][][],string[][][][][][][][][][][]>>>(true); new Gen().ExceptionTest<ValX1<int>>(true); new Gen().ExceptionTest<ValX1<RefX1<int>>>(true); new Gen().ExceptionTest<ValX2<int,string>>(true); new Gen().ExceptionTest<ValX3<int,string,Guid>>(true); new Gen().ExceptionTest<ValX1<ValX1<int>>>(true); new Gen().ExceptionTest<ValX1<ValX1<ValX1<string>>>>(true); new Gen().ExceptionTest<ValX1<ValX1<ValX1<ValX1<Guid>>>>>(true); new Gen().ExceptionTest<ValX1<ValX2<int,string>>>(true); new Gen().ExceptionTest<ValX2<ValX2<ValX1<int>,ValX3<int,string, ValX1<ValX2<int,string>>>>,ValX2<ValX1<int>,ValX3<int,string, ValX1<ValX2<int,string>>>>>>(true); new Gen().ExceptionTest<ValX3<ValX1<int[][,,,]>,ValX2<object[,,,][][],Guid[][][]>,ValX3<double[,,,,,,,,,,],Guid[][][][,,,,][,,,,][][][],string[][][][][][][][][][][]>>>(true); if (result) { Console.WriteLine("Test Passed"); return 100; } else { Console.WriteLine("Test Failed"); return 1; } } }
31.89726
177
0.642903
[ "MIT" ]
06needhamt/runtime
src/coreclr/tests/src/baseservices/exceptions/generics/try-catch06.cs
4,657
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using Hyak.Common; namespace Microsoft.Azure.Management.Automation.Models { /// <summary> /// Definition of job base properties. /// </summary> public partial class JobPropertiesBase { private DateTimeOffset _creationTime; /// <summary> /// Optional. Gets or sets the creation time of the job. /// </summary> public DateTimeOffset CreationTime { get { return this._creationTime; } set { this._creationTime = value; } } private System.DateTimeOffset? _endTime; /// <summary> /// Optional. Gets or sets the end time of the job. /// </summary> public System.DateTimeOffset? EndTime { get { return this._endTime; } set { this._endTime = value; } } private string _exception; /// <summary> /// Optional. Gets or sets the exception of the job. /// </summary> public string Exception { get { return this._exception; } set { this._exception = value; } } private Guid _jobId; /// <summary> /// Optional. Gets or sets the id of the job. /// </summary> public Guid JobId { get { return this._jobId; } set { this._jobId = value; } } private DateTimeOffset _lastModifiedTime; /// <summary> /// Optional. Gets or sets the last modified time of the job. /// </summary> public DateTimeOffset LastModifiedTime { get { return this._lastModifiedTime; } set { this._lastModifiedTime = value; } } private DateTimeOffset _lastStatusModifiedTime; /// <summary> /// Optional. Gets or sets the last status modified time of the job. /// </summary> public DateTimeOffset LastStatusModifiedTime { get { return this._lastStatusModifiedTime; } set { this._lastStatusModifiedTime = value; } } private IDictionary<string, string> _parameters; /// <summary> /// Optional. Gets or sets the parameters of the job. /// </summary> public IDictionary<string, string> Parameters { get { return this._parameters; } set { this._parameters = value; } } private System.DateTimeOffset? _startTime; /// <summary> /// Optional. Gets or sets the start time of the job. /// </summary> public System.DateTimeOffset? StartTime { get { return this._startTime; } set { this._startTime = value; } } private string _status; /// <summary> /// Optional. Gets or sets the status of the job. /// </summary> public string Status { get { return this._status; } set { this._status = value; } } private string _statusDetails; /// <summary> /// Optional. Gets or sets the status details of the job. /// </summary> public string StatusDetails { get { return this._statusDetails; } set { this._statusDetails = value; } } /// <summary> /// Initializes a new instance of the JobPropertiesBase class. /// </summary> public JobPropertiesBase() { this.Parameters = new LazyDictionary<string, string>(); } } }
29.157143
95
0.538217
[ "MIT" ]
DiogenesPolanco/azure-sdk-for-net
src/ResourceManagement/Automation/AutomationManagement/Generated/Models/JobPropertiesBase.cs
4,082
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using RecipeManager.Models; using RecipeManager.Models.Interfaces; namespace RecipeManager.Controllers { public class HomeController : Controller { private readonly IRecipe _Recipe; private readonly IInstruction _Instruction; private readonly IIngredient _Ingredient; private readonly IComment _Comment; private readonly ISavedRecipe _SavedRecipe; public HomeController(IRecipe recipe, IInstruction instructions, IIngredient ingredient, IComment comment, ISavedRecipe savedRecipe) { _Recipe = recipe; _Instruction = instructions; _Ingredient = ingredient; _Comment = comment; _SavedRecipe = savedRecipe; } [HttpGet] public async Task<IActionResult> Index() { IEnumerable<Recipe> recipes = await _Recipe.GetRecipes(); foreach (Recipe recipe in recipes) { recipe.Ingredients = await _Ingredient.GetIngredients(recipe.ID); recipe.Instructions = await _Instruction.GetInstructions(recipe.ID); } return View(recipes); } } }
33.589744
140
0.659542
[ "MIT" ]
c-costello/RecipeManagement
RecipeManager/RecipeManager/Controllers/HomeController.cs
1,312
C#
using System.ComponentModel; using System.Data.Entity; namespace BL.Fashion { public class CategoriasBL { contexto _contexto; public BindingList<Categoria> ListaCategorias { get; set; } public CategoriasBL() { _contexto = new contexto(); ListaCategorias = new BindingList<Categoria>(); } public BindingList<Categoria> ObtenerCategorias() { _contexto.Categorias.Load(); ListaCategorias = _contexto.Categorias.Local.ToBindingList(); return ListaCategorias; } } public class Categoria { public int Id { get; set; } public string Descripcion { get; set; } } }
24.28125
74
0.555985
[ "MIT" ]
KenetMejiaMartinez/Fashion-Station.
BL.Fashion/CategoriaBL.cs
779
C#
using SnapsLibrary; using System; using System.Collections.Generic; public class Ch14_03_Starfield { public class MovingSprite { public ImageSprite spriteValue; public double xSpeedValue, ySpeedValue; public MovingSprite(ImageSprite sprite, double xSpeed, double ySpeed) { spriteValue = sprite; xSpeedValue = xSpeed; ySpeedValue = ySpeed; } public virtual void Update() { spriteValue.X = spriteValue.X + xSpeedValue; spriteValue.Y = spriteValue.Y + ySpeedValue; } } public class FallingSprite : MovingSprite { static Random spriteRand = new Random(); public FallingSprite(ImageSprite sprite, double ySpeed) : base(sprite: sprite, xSpeed: 0, ySpeed: ySpeed) { spriteValue.Left = (SnapsEngine.GameViewportHeight - spriteValue.Width) * spriteRand.NextDouble(); spriteValue.Bottom = SnapsEngine.GameViewportHeight * spriteRand.NextDouble(); } public override void Update() { base.Update(); if (spriteValue.Top > SnapsEngine.GameViewportHeight) { spriteValue.Left = (SnapsEngine.GameViewportWidth - spriteValue.Width) * spriteRand.NextDouble(); spriteValue.Bottom = 0; } } } public void StartProgram() { SnapsEngine.SetBackgroundColor(SnapsColor.Black); SnapsEngine.StartGameEngine(fullScreen: false, framesPerSecond: 60); List<MovingSprite> sprites = new List<MovingSprite>(); for (int i = 0; i < 100; i++) { ImageSprite starImage = new ImageSprite(imageURL: "ms-appx:///Images/star.png"); SnapsEngine.AddSpriteToGame(starImage); starImage.ScaleSpriteWidth(SnapsEngine.GameViewportWidth / 75); FallingSprite star = new FallingSprite(sprite: starImage, ySpeed: 15); sprites.Add(star); } while (true) { foreach (MovingSprite sprite in sprites) { sprite.Update(); } SnapsEngine.DrawGamePage(); } } }
28.556962
113
0.586436
[ "MIT" ]
BeginToCodeSnaps/DemoCode
BeginToCodeWithCSharp/BeginToCodeWithCSharp/Chapters/Chapter 14/Ch14_03_Starfield.cs
2,258
C#
using System; namespace NodeChains { class Program { static void Main(string[] args) { // +----+------+ // | 3 | null + // +----+------+ Node first = new Node {value = 3}; // +----+------+ +-------+------+ // | 3 | null + | 5 | null + // +----+------+ +--------------+ Node middle = new Node {value = 5}; // +----+------+ +-------+------+ // | 3 | *--- +---->| 5 | null + // +----+------+ +--------------+ first.Next = middle; // +----+------+ +-------+------+ +-----+------+ // | 3 | *--- +---->| 5 | null + | 7 | null + // +----+------+ +--------------+ +------------+ Node last = new Node{value = 7}; // +----+------+ +-------+------+ +-----+------+ // | 3 | *--- +---->| 5 | *----+--->| 7 | null + // +----+------+ +--------------+ +------------+ middle.Next = last; //now itarete over each node and print the value PrintList(first); } private static void PrintList(Node node) { while (node != null) { Console.WriteLine(node.value); node = node.Next; } } } }
29.365385
73
0.220039
[ "MIT" ]
josenildolins/Algorithms-And-Data-Structures-part-1
DataStructures/NodeChains/Program.cs
1,529
C#
using System.Collections.Generic; using NUnit.Framework; using Lumpn.Utils; namespace Lumpn.Mooga.Test { [TestFixture] public sealed class DominationComparerTest { [Test] public void SortsAscending() { var individuals = new List<Individual>(); individuals.Add(new SimpleIndividual(3)); individuals.Add(new SimpleIndividual(1)); individuals.Add(new SimpleIndividual(4)); individuals.Add(new SimpleIndividual(1)); individuals.Add(new SimpleIndividual(5)); individuals.Add(new SimpleIndividual(9)); // NOTE Jonas: Generally speaking passing a domination comparer // to standard sort is not going to work, because the comparer // violates the transitive equality assumption. // However, in the one-dimensional case the assumption holds. individuals.Sort(new DominationComparer(1)); // ascending Assert.AreEqual(1, individuals[0].GetScore(0), delta); Assert.AreEqual(1, individuals[1].GetScore(0), delta); Assert.AreEqual(3, individuals[2].GetScore(0), delta); Assert.AreEqual(4, individuals[3].GetScore(0), delta); Assert.AreEqual(5, individuals[4].GetScore(0), delta); Assert.AreEqual(9, individuals[5].GetScore(0), delta); } [Test] public void SortsTopologically() { var individuals = new List<Individual>(); individuals.Add(new SimpleIndividual(3)); individuals.Add(new SimpleIndividual(1)); individuals.Add(new SimpleIndividual(4)); individuals.Add(new SimpleIndividual(1)); individuals.Add(new SimpleIndividual(5)); individuals.Add(new SimpleIndividual(9)); TopologicalSorting.SortDescending(individuals, new DominationComparer(1)); // descending Assert.AreEqual(9, individuals[0].GetScore(0), delta); Assert.AreEqual(5, individuals[1].GetScore(0), delta); Assert.AreEqual(4, individuals[2].GetScore(0), delta); Assert.AreEqual(3, individuals[3].GetScore(0), delta); Assert.AreEqual(1, individuals[4].GetScore(0), delta); Assert.AreEqual(1, individuals[5].GetScore(0), delta); } [Test] public void SortsByDomination() { // create individuals var individuals = new List<Individual>(); individuals.Add(new ParetoIndividual(3, 6, 0)); // rank 1 individuals.Add(new ParetoIndividual(1, 5, 0)); // rank 2 individuals.Add(new ParetoIndividual(4, 4, 0)); // rank 1 individuals.Add(new ParetoIndividual(1, 3, 0)); // rank 3 individuals.Add(new ParetoIndividual(5, 2, 0)); // rank 1 individuals.Add(new ParetoIndividual(9, 1, 0)); // rank 1 TopologicalSorting.SortDescending(individuals, new DominationComparer(2)); // sort by rank Assert.AreEqual(6, individuals[0].GetScore(1), delta); // rank 1 Assert.AreEqual(4, individuals[1].GetScore(1), delta); // rank 1 Assert.AreEqual(2, individuals[2].GetScore(1), delta); // rank 1 Assert.AreEqual(1, individuals[3].GetScore(1), delta); // rank 1 Assert.AreEqual(5, individuals[4].GetScore(1), delta); // rank 2 Assert.AreEqual(3, individuals[5].GetScore(1), delta); // rank 3 } private const double delta = 0.1; } }
42.678571
86
0.604463
[ "MIT" ]
lumpn/infinite-zelda
Lumpn.Mooga.Test/DominationComparerTest.cs
3,587
C#
using System; using System.Net; using System.Runtime.Serialization; namespace Syncfusion.Report.Server.Api.Helper.V1.Models { public class Group { /// <summary> /// Name of the group. /// </summary> public string Name { get; set; } /// <summary> /// Description of the group. /// </summary> public string Description { get; set; } [DataMember] public string Message { get; set; } [DataMember] public HttpStatusCode StatusCode { get; set; } } }
21.423077
55
0.56553
[ "MIT" ]
subhasukumaran/enterpriseserver-reportapiclient
Src/API.Helper/V1/Models/Group.cs
559
C#
#region Licence // Distributed under MIT License // =========================================================== // // digiCamControl - DSLR camera remote control open source software // Copyright (C) 2014 Duka Istvan // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH // THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #endregion #region using System; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Threading; using CameraControl.Devices.Classes; using CameraControl.Devices.TransferProtocol; using CameraControl.Devices.Xml; using PortableDeviceLib; using Timer = System.Timers.Timer; #endregion namespace CameraControl.Devices { public class DeviceEventArgs : EventArgs { public uint Code { get; set; } } public class BaseMTPCamera : BaseCameraDevice { /// <summary> /// The number of times to retry failed transfers. /// </summary> public const int TransferRetries = 10; public delegate void DeviceEventHandler(object sender, DeviceEventArgs eventArgs); public event DeviceEventHandler DeviceEvent; public void OnDeviceEvent(DeviceEventArgs eventargs) { DeviceEventHandler handler = DeviceEvent; if (handler != null) handler(this, eventargs); } protected const string AppName = "CameraControl"; protected const int AppMajorVersionNumber = 1; protected const int AppMinorVersionNumber = 0; // common MTP commands public const uint CONST_CMD_GetDevicePropValue = 0x1015; public const uint CONST_CMD_SetDevicePropValue = 0x1016; public const uint CONST_CMD_GetDevicePropDesc = 0x1014; public const uint CONST_CMD_GetObject = 0x1009; public const uint CONST_CMD_GetObjectHandles = 0x1007; public const uint CONST_CMD_GetObjectInfo = 0x1008; public const uint CONST_CMD_GetThumb = 0x100A; public const uint CONST_CMD_DeleteObject = 0x100B; public const uint CONST_CMD_InitiateCapture = 0x100E; public const uint CONST_CMD_FormatStore = 0x100F; public const uint CONST_CMD_GetStorageIDs = 0x1004; public const uint CONST_Event_ObjectAdded = 0x4002; public const uint CONST_Event_ObjectAddedInSdram = 0xC101; public const uint CONST_PROP_BatteryLevel = 0x5001; private const int CONST_READY_TIME = 1; private const int CONST_LOOP_TIME = 100; protected ITransferProtocol StillImageDevice = null; protected bool DeviceIsBusy = false; /// <summary> /// The timer for get periodically the event list /// </summary> protected Timer _timer = new Timer(1000 / 10); /// <summary> /// Variable to check if event processing is in progress /// </summary> protected bool _eventIsbusy = false; public override bool Init(DeviceDescriptor deviceDescriptor) { StillImageDevice = deviceDescriptor.StillImageDevice; StillImageDevice imageDevice = StillImageDevice as StillImageDevice; if (imageDevice != null) imageDevice.DeviceEvent += StillImageDevice_DeviceEvent; IsConnected = true; DeviceName = StillImageDevice.Model; Manufacturer = StillImageDevice.Manufacturer; var data = StillImageDevice.ExecuteReadData(CONST_CMD_GetDevicePropValue, CONST_PROP_BatteryLevel); if (data.Data != null && data.Data.Length > 0) Battery = data.Data[0]; return true; } public override void CapturePhoto() { Monitor.Enter(Locker); try { IsBusy = true; ErrorCodes.GetException(ExecuteWithNoData(CONST_CMD_InitiateCapture)); } catch (COMException comException) { IsBusy = false; ErrorCodes.GetException(comException); } catch { IsBusy = false; throw; } finally { Monitor.Exit(Locker); } } public void StopEventTimer() { while (_eventIsbusy) { } _timer.Stop(); } public void StartEventTimer() { _timer.Start(); } private void StillImageDevice_DeviceEvent(object sender, PortableDeviceEventArgs e) { if (e.EventType.EventGuid == PortableDeviceGuids.WPD_EVENT_DEVICE_REMOVED) { _timer.Stop(); StillImageDevice.Disconnect(); StillImageDevice.IsConnected = false; IsConnected = false; OnCameraDisconnected(this, new DisconnectCameraEventArgs { StillImageDevice = StillImageDevice }); } } public override bool DeleteObject(DeviceObject deviceObject) { uint res = ExecuteWithNoData(CONST_CMD_DeleteObject, (uint)deviceObject.Handle); return res == 0 || res == ErrorCodes.MTP_OK; } public override AsyncObservableCollection<DeviceObject> GetObjects(object storageId, bool loadThumbs) { AsyncObservableCollection<DeviceObject> res = new AsyncObservableCollection<DeviceObject>(); MTPDataResponse response = ExecuteReadDataEx(CONST_CMD_GetObjectHandles, 0xFFFFFFFF); if (response.Data == null) { Log.Debug("Get object error :" + response.ErrorCode.ToString("X")); ErrorCodes.GetException(response.ErrorCode); return res; } int objCount = BitConverter.ToInt32(response.Data, 0); for (int i = 0; i < objCount; i++) { DeviceObject deviceObject = new DeviceObject(); uint handle = BitConverter.ToUInt32(response.Data, 4 * i + 4); deviceObject.Handle = handle; MTPDataResponse objectdata = ExecuteReadDataEx(CONST_CMD_GetObjectInfo, handle); if (objectdata.Data != null) { uint objFormat = BitConverter.ToUInt16(objectdata.Data, 4); if (objFormat == 0x3000 || objFormat == 0x3801 || objFormat == 0x3800) { deviceObject.FileName = Encoding.Unicode.GetString(objectdata.Data, 53, 12 * 2); if (deviceObject.FileName.Contains("\0")) deviceObject.FileName = deviceObject.FileName.Split('\0')[0]; try { string datesrt = Encoding.Unicode.GetString(objectdata.Data, 53 + (12 * 2) + 3, 30); //datesrt = datesrt.Replace("T", ""); DateTime date = DateTime.MinValue; if (DateTime.TryParseExact(datesrt, "yyyyMMddTHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.None, out date)) { deviceObject.FileDate = date; } } catch (Exception) { } if (loadThumbs) { MTPDataResponse thumbdata = ExecuteReadDataEx(CONST_CMD_GetThumb, handle); deviceObject.ThumbData = thumbdata.Data; } res.Add(deviceObject); } } } return res; } /// <summary> /// Transfers the file and saves it to the specified filename. /// </summary> /// <param name="o">The object handle.</param> /// <param name="filename">The filename.</param> public override void TransferFile(object o, string filename) { using (var fs = File.Open(filename, FileMode.Create)) { TransferFile(o, fs); } } /// <summary> /// Transfers the file and writes it to the specified stream. /// </summary> /// <param name="o">The object handle.</param> /// <param name="stream">The stream.</param> public override void TransferFile(object o, Stream stream) { // Sanity checks. if (!stream.CanWrite) throw new ArgumentException("Specified stream is not writable.", "stream"); lock (Locker) { string s = o as string; if (s != null) { ((StillImageDevice)StillImageDevice).SaveFile(s, stream); return; } int retryes = TransferRetries; _timer.Stop(); MTPDataResponse result = new MTPDataResponse(); //=================== managed file write do { try { //using (MemoryStream mStream = new MemoryStream()) //{ result = StillImageDevice.ExecuteReadBigData(CONST_CMD_GetObject, stream, (total, current) => { double i = (double)current / total; TransferProgress = Convert.ToUInt32(i * 100); }, Convert.ToUInt32(o)); //if (result != null && result.Data != null) //{ // stream.Write(result.Data, 0, result.Data.Length); //} //stream.Write(mStream.ToArray(), 0, (int)mStream.Length); break; //} } catch (COMException ex) { Log.Error("Transfer error", ex); Thread.Sleep(200); retryes--; } } while (retryes > 0); //================================================================== //=================== direct file write //StillImageDevice.ExecuteReadBigDataWriteToFile(CONST_CMD_GetObject, // Convert.ToInt32(o), -1, // (total, current) => // { // double i = (double)current / total; // TransferProgress = // Convert.ToUInt32(i * 100); // }, filename); //================================================================== _timer.Start(); TransferProgress = 0; } } public override void FormatStorage(object storageId) { MTPDataResponse response = ExecuteReadDataEx(CONST_CMD_GetStorageIDs); if (response.Data.Length > 4) { int objCount = BitConverter.ToInt32(response.Data, 0); for (int i = 0; i < objCount; i++) { uint handle = BitConverter.ToUInt32(response.Data, 4 * i + 4); ErrorCodes.GetException(ExecuteWithNoData(CONST_CMD_FormatStore, handle)); } } } public MTPDataResponse ExecuteReadDataEx(uint code, uint param1, uint param2) { return ExecuteReadDataEx(code, param1, param2, CONST_LOOP_TIME, 0); } public uint ExecuteWithNoData(uint code, uint param1) { return ExecuteWithNoData(code, param1, CONST_LOOP_TIME, 0); } public uint ExecuteWithNoData(uint code, uint param1, uint param2, uint param3) { return ExecuteWithNoData(code, param1, param2, param3, CONST_LOOP_TIME, 0); } public uint ExecuteWithNoData(uint code) { return ExecuteWithNoData(code, CONST_LOOP_TIME, 0); } public uint ExecuteWithNoData(uint code, uint param1, int loop, int counter) { uint res = 0; bool allok; do { allok = true; res = StillImageDevice.ExecuteWithNoData(code, param1); if ((res == ErrorCodes.MTP_Device_Busy || res == PortableDeviceErrorCodes.ERROR_BUSY) && counter < loop) { Thread.Sleep(CONST_READY_TIME); counter++; allok = false; } } while (!allok); return res; } public uint ExecuteWithNoData(uint code, uint param1, uint param2, uint param3, int loop, int counter) { uint res = 0; bool allok; do { allok = true; res = StillImageDevice.ExecuteWithNoData(code, param1, param2, param3); if ((res == ErrorCodes.MTP_Device_Busy || res == PortableDeviceErrorCodes.ERROR_BUSY) && counter < loop) { Thread.Sleep(CONST_READY_TIME); counter++; allok = false; } } while (!allok); return res; } public uint ExecuteWithNoData(uint code, int loop, int counter) { uint res = 0; bool allok; do { allok = true; res = StillImageDevice.ExecuteWithNoData(code); if ((res == ErrorCodes.MTP_Device_Busy || res == PortableDeviceErrorCodes.ERROR_BUSY) && counter < loop) { Thread.Sleep(CONST_READY_TIME); counter++; allok = false; } } while (!allok); return res; } public uint ExecuteWithNoData(uint code, uint param1, uint param2) { uint res = StillImageDevice.ExecuteWithNoData(code, param1, param2); return res; } public MTPDataResponse ExecuteReadDataEx(uint code, uint param1, uint param2, int loop, int counter) { DeviceIsBusy = true; MTPDataResponse res = new MTPDataResponse(); bool allok; do { allok = true; res = StillImageDevice.ExecuteReadData(code, param1, param2); if ((res.ErrorCode == ErrorCodes.MTP_Device_Busy || res.ErrorCode == PortableDeviceErrorCodes.ERROR_BUSY) && counter < loop) { Thread.Sleep(CONST_READY_TIME); counter++; allok = false; } } while (!allok); DeviceIsBusy = false; return res; } public MTPDataResponse ExecuteReadDataEx(uint code, uint param1, uint param2, uint param3, int loop, int counter) { DeviceIsBusy = true; MTPDataResponse res = new MTPDataResponse(); bool allok; do { allok = true; res = StillImageDevice.ExecuteReadData(code, param1, param2, param3); if ((res.ErrorCode == ErrorCodes.MTP_Device_Busy || res.ErrorCode == PortableDeviceErrorCodes.ERROR_BUSY) && counter < loop) { Thread.Sleep(CONST_READY_TIME); counter++; allok = false; } } while (!allok); DeviceIsBusy = false; return res; } public MTPDataResponse ExecuteReadDataEx(uint code, uint param1) { int counter = 0; DeviceIsBusy = true; MTPDataResponse res = new MTPDataResponse(); bool allok; do { res = StillImageDevice.ExecuteReadData(code, param1); allok = true; if ((res.ErrorCode == ErrorCodes.MTP_Device_Busy || res.ErrorCode == PortableDeviceErrorCodes.ERROR_BUSY) && counter < CONST_LOOP_TIME) { Thread.Sleep(CONST_READY_TIME); counter++; allok = false; } } while (!allok); DeviceIsBusy = false; return res; } public MTPDataResponse ExecuteReadDataEx(uint code) { int counter = 0; DeviceIsBusy = true; MTPDataResponse res = new MTPDataResponse(); bool allok; do { res = StillImageDevice.ExecuteReadData(code); allok = true; if ((res.ErrorCode == ErrorCodes.MTP_Device_Busy || res.ErrorCode == PortableDeviceErrorCodes.ERROR_BUSY) && counter < CONST_LOOP_TIME) { Thread.Sleep(CONST_READY_TIME); counter++; allok = false; } } while (!allok); DeviceIsBusy = false; return res; } public void SetProperty(uint code, byte[] data, uint param1) { bool timerstate = _timer.Enabled; _timer.Stop(); bool retry = false; int retrynum = 0; //DeviceReady(); do { if (retrynum > 5) { return; } try { retry = false; uint resp = StillImageDevice.ExecuteWriteData(code, data, param1); if (resp != 0 || resp != ErrorCodes.MTP_OK) { //Console.WriteLine("Retry ...." + resp.ToString("X")); if (resp == ErrorCodes.MTP_Device_Busy || resp == 0x800700AA) { Thread.Sleep(50); retry = true; retrynum++; } else { ErrorCodes.GetException(resp); } } } catch (Exception exception) { Log.Debug("Error set property :" + param1.ToString("X"), exception); } } while (retry); if (timerstate) _timer.Start(); } public void SetProperty(uint code, byte[] data, uint param1, uint param2) { bool timerstate = _timer.Enabled; _timer.Stop(); bool retry = false; int retrynum = 0; //DeviceReady(); do { if (retrynum > 5) { return; } try { retry = false; uint resp = StillImageDevice.ExecuteWriteData(code, data, param1, param2); if (resp != 0 || resp != ErrorCodes.MTP_OK) { //Console.WriteLine("Retry ...." + resp.ToString("X")); if (resp == ErrorCodes.MTP_Device_Busy || resp == 0x800700AA) { Thread.Sleep(50); retry = true; retrynum++; } else { ErrorCodes.GetException(resp); } } } catch (Exception exception) { Log.Debug("Error set property :" + param1.ToString("X"), exception); } } while (retry); if (timerstate) _timer.Start(); } public void SetProperty(uint code, byte[] data, uint param1, uint param2, uint param3) { bool timerstate = _timer.Enabled; _timer.Stop(); bool retry = false; int retrynum = 0; //DeviceReady(); do { if (retrynum > 5) { return; } try { retry = false; uint resp = StillImageDevice.ExecuteWriteData(code, data, param1, param2, param3); if (resp != 0 || resp != ErrorCodes.MTP_OK) { //Console.WriteLine("Retry ...." + resp.ToString("X")); if (resp == ErrorCodes.MTP_Device_Busy || resp == 0x800700AA) { Thread.Sleep(100); retry = true; retrynum++; } else { ErrorCodes.GetException(resp); } } } catch (Exception exception) { Log.Debug("Error set property :" + param1.ToString("X"), exception); } } while (retry); if (timerstate) _timer.Start(); } public static short ToInt16(byte[] value, int startIndex) { int i = (short)(value[startIndex] << 8 | value[startIndex + 1]); return (short)(i); //return System.BitConverter.ToInt16(value.Reverse().ToArray(), value.Length - sizeof(Int16) - startIndex); } public static UInt16 ToUInt16(byte[] value, int startIndex) { uint i = (uint)(value[startIndex] << 8 | value[startIndex + 1]); return (UInt16)(i); //return System.BitConverter.ToInt16(value.Reverse().ToArray(), value.Length - sizeof(Int16) - startIndex); } public static int ToInt32(byte[] value, int startIndex) { int i = (value[startIndex] << 24 | value[startIndex + 1] << 16 | value[startIndex + 2] << 8 | value[startIndex + 3]); return i; //return System.BitConverter.ToInt16(value.Reverse().ToArray(), value.Length - sizeof(Int16) - startIndex); } public decimal ToDeciaml(byte[] value, int startIndex) { int i = ToUInt16(value, startIndex); int d = ToUInt16(value, startIndex + 2); if (d == 0 && i == 0) return 0; string s = i + "." + d; return Convert.ToDecimal(s, new CultureInfo("en-US")); } protected XmlDeviceData LoadDeviceData(MTPDataResponse res) { XmlDeviceData deviceInfo = new XmlDeviceData(); ErrorCodes.GetException(res.ErrorCode); deviceInfo.Manufacturer = Manufacturer; int index = 2 + 4 + 2; int vendorDescCount = res.Data[index]; index += vendorDescCount * 2; index += 3; int comandsCount = res.Data[index]; index += 2; // load commands for (int i = 0; i < comandsCount; i++) { index += 2; deviceInfo.AvaiableCommands.Add(new XmlCommandDescriptor() { Code = BitConverter.ToUInt16(res.Data, index) }); } index += 2; int eventcount = res.Data[index]; index += 2; // load events for (int i = 0; i < eventcount; i++) { index += 2; deviceInfo.AvaiableEvents.Add(new XmlEventDescriptor() { Code = BitConverter.ToUInt16(res.Data, index) }); } index += 2; int propertycount = res.Data[index]; index += 2; // load properties codes for (int i = 0; i < propertycount; i++) { index += 2; deviceInfo.AvaiableProperties.Add(new XmlPropertyDescriptor() { Code = BitConverter.ToUInt16(res.Data, index) }); } try { MTPDataResponse vendor_res = ExecuteReadDataEx(0x90CA); if (vendor_res.Data.Length > 0) { index = 0; propertycount = vendor_res.Data[index]; index += 2; for (int i = 0; i < propertycount; i++) { index += 2; deviceInfo.AvaiableProperties.Add(new XmlPropertyDescriptor() { Code = BitConverter.ToUInt16(vendor_res.Data, index) }); } } } catch (Exception) { } return deviceInfo; } } }
37.791549
144
0.480471
[ "MIT" ]
mathcham/digiCamControl
CameraControl.Devices/BaseMTPCamera.cs
26,832
C#
using System; using System.Collections.Generic; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Dime.System.Tests { [TestClass] public class EnsureEqualTests { [TestMethod] public void Ensure_Equal_ValuesAreEqual_ShouldNotThrowException() => Ensure.Equal(1, 1); [TestMethod] public void Ensure_Equal_ValuesAreNotEqual_ShouldThrowException() => Assert.ThrowsException<Exception>(() => Ensure.Equal(1, 2)); } }
25.85
75
0.694391
[ "MIT" ]
dimenics/dime-system
src/test/Ensure/EnsureEqualTests.cs
519
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models { using Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.PowerShell; /// <summary> /// A PowerShell PSTypeConverter to support converting to an instance of <see cref="Any" /> /// </summary> public partial class AnyTypeConverter : global::System.Management.Automation.PSTypeConverter { /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c>. /// </returns> public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="Any" /// /> type.</param> /// <returns> /// <c>true</c> if the instance could be converted to a <see cref="Any" /> type, otherwise <c>false</c> /// </returns> public static bool CanConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return true; } global::System.Type type = sourceValue.GetType(); if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { // we say yest to PSObjects return true; } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { // we say yest to Hashtables/dictionaries return true; } try { if (null != sourceValue.ToJsonString()) { return true; } } catch { // Not one of our objects } try { string text = sourceValue.ToString()?.Trim(); return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonType.Object; } catch { // Doesn't look like it can be treated as JSON } return false; } /// <summary> /// Determines if the <see cref="sourceValue" /> parameter can be converted to the <see cref="destinationType" /> parameter /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c> /// </returns> public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; /// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns> /// an instance of <see cref="Any" />, or <c>null</c> if there is no suitable conversion. /// </returns> public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); /// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the value to convert into an instance of <see cref="Any" />.</param> /// <returns> /// an instance of <see cref="Any" />, or <c>null</c> if there is no suitable conversion. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.IAny ConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return null; } global::System.Type type = sourceValue.GetType(); if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.IAny).IsAssignableFrom(type)) { return sourceValue; } try { return Any.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; } catch { // Unable to use JSON pattern } if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { return Any.DeserializeFromPSObject(sourceValue); } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { return Any.DeserializeFromDictionary(sourceValue); } return null; } /// <summary>NotImplemented -- this will return <c>null</c></summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns>will always return <c>null</c>.</returns> public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; } }
50.367347
245
0.578876
[ "MIT" ]
3quanfeng/azure-powershell
src/Migrate/generated/api/Models/Any.TypeConverter.cs
7,258
C#
using OpenTibiaUnity.Core.Components; using OpenTibiaUnity.Core.Components.Base; using UnityEngine; using UnityEngine.UI; namespace OpenTibiaUnity.Modules.Options { [DisallowMultipleComponent] public sealed class LegacyOptionsWindowItem : AbstractComponent { public ButtonWrapper buttonWrapper; public TMPro.TextMeshProUGUI label; } }
24.6
67
0.775068
[ "MIT" ]
DwarvenSoft/OpenTibia-Unity
OpenTibia/Assets/Scripts/Modules/Options/LegacyOptionsWindowItem.cs
371
C#
using System; using System.Collections.Generic; using System.Numerics; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; using System.Text; namespace LifeOhLife { /// <summary> /// Uses AVX2 instruction set to handle field cells in chunks of 32 bytes /// The fastest algorithm so far, but does not work on old processors. /// Also note that SIMD intrinsics are only available in .NET Core, so this class /// won't compile in .NET Framework /// </summary> public unsafe class AdvancedLifeExtensionsInLineCompressed : LifeJourney { const int LINE_WIDTH = WIDTH / 2; byte[] field = new byte[LINE_WIDTH * HEIGHT + 32]; byte[] upperLineSumOf2 = new byte[LINE_WIDTH]; byte[] upperLineSumOf3 = new byte[LINE_WIDTH]; byte[] middleLineSumOf2 = new byte[LINE_WIDTH]; byte[] middleLineSumOf3 = new byte[LINE_WIDTH]; byte[] lowerLineSumOf2 = new byte[LINE_WIDTH]; byte[] lowerLineSumOf3 = new byte[LINE_WIDTH]; private Vector256<byte> v_lookup; private Vector256<byte> v_hi, v_lo; public AdvancedLifeExtensionsInLineCompressed() { if (!Avx2.IsSupported) throw new NotImplementedException("Not in this life!!!"); byte[] lookup = new byte[] { 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0 }; fixed (byte* ptr = lookup) v_lookup = Avx2.LoadVector256(ptr); byte b_hi = 0xF0; byte b_lo = 0x0F; v_hi = Avx2.BroadcastScalarToVector256(&b_hi); v_lo = Avx2.BroadcastScalarToVector256(&b_lo); } public override bool Get(int x, int y) { int pos = y * LINE_WIDTH + x / 2; int offset = (x % 2) * 4; ulong mask = 1ul << offset; return (field[pos] & mask) == mask; } public override void Set(int x, int y, bool value) { int pos = y * LINE_WIDTH + x / 2; int offset = (x % 2) * 4; byte mask = (byte)(1 << offset); if (value) field[pos] |= mask; else field[pos] &= (byte)~mask; } public override void Step() { fixed (byte* currentFieldPtr = field, upperLineSumOf2Ptr = upperLineSumOf2, upperLineSumOf3Ptr = upperLineSumOf3, middleLineSumOf2Ptr = middleLineSumOf2, middleLineSumOf3Ptr = middleLineSumOf3, lowerLineSumOf2Ptr = lowerLineSumOf2, lowerLineSumOf3Ptr = lowerLineSumOf3) { byte* upper2 = upperLineSumOf2Ptr, upper3 = upperLineSumOf3Ptr; byte* middle2 = middleLineSumOf2Ptr, middle3 = middleLineSumOf3Ptr; byte* lower2 = lowerLineSumOf2Ptr, lower3 = lowerLineSumOf3Ptr; byte* nextLinePtr = currentFieldPtr + LINE_WIDTH; for (int x = 0; x < LINE_WIDTH; x += 32) { Avx2.Store(upper2 + x, Vector256<byte>.Zero); Avx2.Store(upper3 + x, Vector256<byte>.Zero); Avx2.Store(middle2 + x, Vector256<byte>.Zero); Avx2.Store(middle3 + x, Vector256<byte>.Zero); Vector256<byte> nextLeft = Avx2.LoadVector256(nextLinePtr + x - 8); Vector256<byte> nextCenter = Avx2.LoadVector256(nextLinePtr + x); Vector256<byte> nextRight = Avx2.LoadVector256(nextLinePtr + x + 8); Vector256<byte> lowerSum2 = Avx2.Add( Avx2.Add( Avx2.ShiftRightLogical(nextCenter.AsUInt64(), 4), Avx2.ShiftLeftLogical(nextCenter.AsUInt64(), 4)), Avx2.Add( Avx2.ShiftRightLogical(nextLeft.AsUInt64(), 60), Avx2.ShiftLeftLogical(nextRight.AsUInt64(), 60))).AsByte(); Avx2.Store(lower2 + x, lowerSum2); Vector256<byte> lowerSum3 = Avx2.Add(lowerSum2, nextCenter); Avx2.Store(lower3 + x, lowerSum3); } for (int y = 1; y < HEIGHT - 1; y++) { nextLinePtr += LINE_WIDTH; byte* temp2 = upper2; byte* temp3 = upper3; upper2 = middle2; upper3 = middle3; middle2 = lower2; middle3 = lower3; lower2 = temp2; lower3 = temp3; for (int x = 0; x < LINE_WIDTH; x += 32) { Vector256<byte> nextLeft = Avx2.LoadVector256(nextLinePtr + x - 8); Vector256<byte> nextCenter = Avx2.LoadVector256(nextLinePtr + x); Vector256<byte> nextRight = Avx2.LoadVector256(nextLinePtr + x + 8); Vector256<byte> lowerSum2 = Avx2.Add( Avx2.Add( Avx2.ShiftRightLogical(nextCenter.AsUInt64(), 4), Avx2.ShiftLeftLogical(nextCenter.AsUInt64(), 4)), Avx2.Add( Avx2.ShiftRightLogical(nextLeft.AsUInt64(), 60), Avx2.ShiftLeftLogical(nextRight.AsUInt64(), 60))).AsByte(); Avx2.Store(lower2 + x, lowerSum2); Vector256<byte> lowerSum3 = Avx2.Add(lowerSum2, nextCenter); Avx2.Store(lower2 + x, lowerSum2); Avx2.Store(lower3 + x, Avx2.Add(lowerSum2, nextCenter)); Vector256<byte> neighbours = Avx2.Add( Avx2.LoadVector256(middle2 + x), Avx2.Add(Avx2.LoadVector256(upper3 + x), lowerSum3)); Vector256<byte> alive = Avx2.LoadVector256(nextLinePtr - LINE_WIDTH + x); alive = Avx2.ShiftLeftLogical(alive.AsUInt64(), (byte)3).AsByte(); Vector256<byte> mask = Avx2.Or(neighbours, alive); Vector256<byte> mask_hi = Avx2.And(mask, v_hi); Vector256<byte> mask_lo = Avx2.And(mask, v_lo); mask_hi = Avx2.ShiftRightLogical(mask_hi.AsUInt64(), 4).AsByte(); Vector256<byte> shouldBeAlive_hi = Avx2.Shuffle(v_lookup, mask_hi); Vector256<byte> shouldBeAlive_lo = Avx2.Shuffle(v_lookup, mask_lo); shouldBeAlive_hi = Avx2.ShiftLeftLogical(shouldBeAlive_hi.AsUInt64(), 4).AsByte(); Vector256<byte> shouldBeAlive = Avx2.Or(shouldBeAlive_hi, shouldBeAlive_lo); Avx2.Store(nextLinePtr - LINE_WIDTH + x, shouldBeAlive); } *(byte*)(nextLinePtr - LINE_WIDTH) &= 0xF0; *(byte*)(nextLinePtr - 1) &= 0x0F; } } } } }
45.160494
144
0.507654
[ "MIT" ]
lightln2/LifeOhLife
csharp/LifeOhLife/7_AdvancedLifeExtensionsInLineCompressed.cs
7,318
C#
#nullable disable using Carbon.Jose; namespace Carbon.Acme; public sealed class ChangeKeyRequest { public JwsEncodedMessage Message { get; init; } }
14.272727
51
0.757962
[ "MIT" ]
carbon/Acme
src/Carbon.Acme/Actions/ChangeKeyRequest.cs
159
C#
// ------------------------------------------------------------------------------ // <auto-generated> // This file was generated by VSIX Synchronizer // </auto-generated> // ------------------------------------------------------------------------------ namespace SvgViewer { internal sealed partial class Vsix { public const string Id = "SvgViewer.7a08d0d4-985c-4415-93d5-ddd9135d8f4f"; public const string Name = "SVG Viewer"; public const string Description = @"Makes it much easier to work with SVG files by showing a live preview in the bottom-right corner of the code window"; public const string Language = "en-US"; public const string Version = "1.0"; public const string Author = "Mads Kristensen"; public const string Tags = "svg, xml"; } }
43.263158
161
0.537713
[ "Apache-2.0" ]
madskristensen/SvgViewer
src/source.extension.cs
822
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.DBforPostgreSQL.V20171201 { public static class GetConfiguration { /// <summary> /// Represents a Configuration. /// </summary> public static Task<GetConfigurationResult> InvokeAsync(GetConfigurationArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetConfigurationResult>("azure-nextgen:dbforpostgresql/v20171201:getConfiguration", args ?? new GetConfigurationArgs(), options.WithVersion()); } public sealed class GetConfigurationArgs : Pulumi.InvokeArgs { /// <summary> /// The name of the server configuration. /// </summary> [Input("configurationName", required: true)] public string ConfigurationName { get; set; } = null!; /// <summary> /// The name of the resource group. The name is case insensitive. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; /// <summary> /// The name of the server. /// </summary> [Input("serverName", required: true)] public string ServerName { get; set; } = null!; public GetConfigurationArgs() { } } [OutputType] public sealed class GetConfigurationResult { /// <summary> /// Allowed values of the configuration. /// </summary> public readonly string AllowedValues; /// <summary> /// Data type of the configuration. /// </summary> public readonly string DataType; /// <summary> /// Default value of the configuration. /// </summary> public readonly string DefaultValue; /// <summary> /// Description of the configuration. /// </summary> public readonly string Description; /// <summary> /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} /// </summary> public readonly string Id; /// <summary> /// The name of the resource /// </summary> public readonly string Name; /// <summary> /// Source of the configuration. /// </summary> public readonly string? Source; /// <summary> /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" /// </summary> public readonly string Type; /// <summary> /// Value of the configuration. /// </summary> public readonly string? Value; [OutputConstructor] private GetConfigurationResult( string allowedValues, string dataType, string defaultValue, string description, string id, string name, string? source, string type, string? value) { AllowedValues = allowedValues; DataType = dataType; DefaultValue = defaultValue; Description = description; Id = id; Name = name; Source = source; Type = type; Value = value; } } }
30.741667
197
0.586067
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/DBforPostgreSQL/V20171201/GetConfiguration.cs
3,689
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 Microsoft.Interop { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.Interop.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Marshalling an array from unmanaged to managed requires either the &apos;SizeParamIndex&apos; or &apos;SizeConst&apos; fields to be set on a &apos;MarshalAsAttribute&apos; or the &apos;ConstantElementCount&apos; or &apos;CountElementName&apos; properties to be set on a &apos;MarshalUsingAttribute&apos;.. /// </summary> internal static string ArraySizeMustBeSpecified { get { return ResourceManager.GetString("ArraySizeMustBeSpecified", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The &apos;SizeParamIndex&apos; value in the &apos;MarshalAsAttribute&apos; is out of range.. /// </summary> internal static string ArraySizeParamIndexOutOfRange { get { return ResourceManager.GetString("ArraySizeParamIndexOutOfRange", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The &apos;BlittableTypeAttribute&apos; and &apos;NativeMarshallingAttribute&apos; attributes are mutually exclusive.. /// </summary> internal static string CannotHaveMultipleMarshallingAttributesDescription { get { return ResourceManager.GetString("CannotHaveMultipleMarshallingAttributesDescription", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Type &apos;{0}&apos; is marked with &apos;BlittableTypeAttribute&apos; and &apos;NativeMarshallingAttribute&apos;. A type can only have one of these two attributes.. /// </summary> internal static string CannotHaveMultipleMarshallingAttributesMessage { get { return ResourceManager.GetString("CannotHaveMultipleMarshallingAttributesMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to A native type with the &apos;GenericContiguousCollectionMarshallerAttribute&apos; must have at least one of the two marshalling methods as well as a &apos;ManagedValues&apos; property of type &apos;Span&lt;T&gt;&apos; for some &apos;T&apos; and a &apos;NativeValueStorage&apos; property of type &apos;Span&lt;byte&gt;&apos; to enable marshalling the managed type.. /// </summary> internal static string CollectionNativeTypeMustHaveRequiredShapeDescription { get { return ResourceManager.GetString("CollectionNativeTypeMustHaveRequiredShapeDescription", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The native type &apos;{0}&apos; must be a value type and have a constructor that takes two parameters, one of type &apos;{1}&apos; and an &apos;int&apos;, or have a parameterless instance method named &apos;ToManaged&apos; that returns &apos;{1}&apos; as well as a &apos;ManagedValues&apos; property of type &apos;Span&lt;T&gt;&apos; for some &apos;T&apos; and a &apos;NativeValueStorage&apos; property of type &apos;Span&lt;byte&gt;&apos;. /// </summary> internal static string CollectionNativeTypeMustHaveRequiredShapeMessage { get { return ResourceManager.GetString("CollectionNativeTypeMustHaveRequiredShapeMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The specified collection size parameter for an collection must be an integer type. If the size information is applied to a nested collection, the size parameter must be a collection of one less level of nesting with an integral element.. /// </summary> internal static string CollectionSizeParamTypeMustBeIntegral { get { return ResourceManager.GetString("CollectionSizeParamTypeMustBeIntegral", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Only one of &apos;ConstantElementCount&apos; or &apos;ElementCountInfo&apos; may be used in a &apos;MarshalUsingAttribute&apos; for a given &apos;ElementIndirectionLevel&apos;. /// </summary> internal static string ConstantAndElementCountInfoDisallowed { get { return ResourceManager.GetString("ConstantAndElementCountInfoDisallowed", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The specified parameter needs to be marshalled from managed to native, but the native type &apos;{0}&apos; does not support it.. /// </summary> internal static string CustomTypeMarshallingManagedToNativeUnsupported { get { return ResourceManager.GetString("CustomTypeMarshallingManagedToNativeUnsupported", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The specified parameter needs to be marshalled from native to managed, but the native type &apos;{0}&apos; does not support it.. /// </summary> internal static string CustomTypeMarshallingNativeToManagedUnsupported { get { return ResourceManager.GetString("CustomTypeMarshallingNativeToManagedUnsupported", resourceCulture); } } /// <summary> /// Looks up a localized string similar to This element cannot depend on &apos;{0}&apos; for collection size information without creating a dependency cycle. /// </summary> internal static string CyclicalCountInfo { get { return ResourceManager.GetString("CyclicalCountInfo", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Count information for a given element at a given indirection level can only be specified once. /// </summary> internal static string DuplicateCountInfo { get { return ResourceManager.GetString("DuplicateCountInfo", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Multiple marshalling attributes per element per indirection level is unsupported, but duplicate information was provided for indirection level {0}. /// </summary> internal static string DuplicateMarshallingInfo { get { return ResourceManager.GetString("DuplicateMarshallingInfo", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Marshalling info was specified for &apos;ElementIndirectionLevel&apos; {0}, but marshalling info was only needed for {1} level(s) of indirection. /// </summary> internal static string ExtraneousMarshallingInfo { get { return ResourceManager.GetString("ExtraneousMarshallingInfo", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The provided graph has cycles and cannot be topologically sorted.. /// </summary> internal static string GraphHasCycles { get { return ResourceManager.GetString("GraphHasCycles", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The &apos;[In]&apos; attribute is not supported unless the &apos;[Out]&apos; attribute is also used. The behavior of the &apos;[In]&apos; attribute without the &apos;[Out]&apos; attribute is the same as the default behavior.. /// </summary> internal static string InAttributeNotSupportedWithoutOut { get { return ResourceManager.GetString("InAttributeNotSupportedWithoutOut", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The &apos;[In]&apos; and &apos;[Out]&apos; attributes are unsupported on parameters passed by reference. Use the &apos;in&apos;, &apos;ref&apos;, or &apos;out&apos; keywords instead.. /// </summary> internal static string InOutAttributeByRefNotSupported { get { return ResourceManager.GetString("InOutAttributeByRefNotSupported", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The provided &apos;[In]&apos; and &apos;[Out]&apos; attributes on this parameter are unsupported on this parameter.. /// </summary> internal static string InOutAttributeMarshalerNotSupported { get { return ResourceManager.GetString("InOutAttributeMarshalerNotSupported", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Marshalling char with &apos;CharSet.{0}&apos; is not supported. Instead, manually convert the char type to the desired byte representation and pass to the source-generated P/Invoke.. /// </summary> internal static string MarshallingCharAsSpecifiedCharSetNotSupported { get { return ResourceManager.GetString("MarshallingCharAsSpecifiedCharSetNotSupported", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Marshalling string or char without explicit marshalling information is not supported. Specify either &apos;GeneratedDllImportAttribute.CharSet&apos; or &apos;MarshalAsAttribute&apos;.. /// </summary> internal static string MarshallingStringOrCharAsUndefinedNotSupported { get { return ResourceManager.GetString("MarshallingStringOrCharAsUndefinedNotSupported", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The native type &apos;{0}&apos; for managed type &apos;{1}&apos; must be a closed generic type or have the same arity as the managed type.. /// </summary> internal static string NativeGenericTypeMustBeClosedOrMatchArityMessage { get { return ResourceManager.GetString("NativeGenericTypeMustBeClosedOrMatchArityMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The native type must have at least one of the two marshalling methods to enable marshalling the managed type.. /// </summary> internal static string NativeTypeMustHaveRequiredShapeDescription { get { return ResourceManager.GetString("NativeTypeMustHaveRequiredShapeDescription", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The native type &apos;{0}&apos; must be a value type and have a constructor that takes one parameter of type &apos;{1}&apos; or a parameterless instance method named &apos;ToManaged&apos; that returns &apos;{1}&apos;. /// </summary> internal static string NativeTypeMustHaveRequiredShapeMessage { get { return ResourceManager.GetString("NativeTypeMustHaveRequiredShapeMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The &apos;[Out]&apos; attribute is only supported on array parameters.. /// </summary> internal static string OutByValueNotSupportedDescription { get { return ResourceManager.GetString("OutByValueNotSupportedDescription", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The &apos;[Out]&apos; attribute is not supported on the &apos;{0}&apos; parameter.. /// </summary> internal static string OutByValueNotSupportedMessage { get { return ResourceManager.GetString("OutByValueNotSupportedMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The &apos;Value&apos; property must not be a &apos;ref&apos; or &apos;readonly ref&apos; property.. /// </summary> internal static string RefValuePropertyUnsupportedDescription { get { return ResourceManager.GetString("RefValuePropertyUnsupportedDescription", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The &apos;Value&apos; property on the native type &apos;{0}&apos; must not be a &apos;ref&apos; or &apos;readonly ref&apos; property.. /// </summary> internal static string RefValuePropertyUnsupportedMessage { get { return ResourceManager.GetString("RefValuePropertyUnsupportedMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Runtime marshalling must be disabled in this project by applying the &apos;System.Runtime.InteropServices.DisableRuntimeMarshallingAttribute&apos; to the assembly to enable marshalling this type.. /// </summary> internal static string RuntimeMarshallingMustBeDisabled { get { return ResourceManager.GetString("RuntimeMarshallingMustBeDisabled", resourceCulture); } } /// <summary> /// Looks up a localized string similar to An abstract type derived from &apos;SafeHandle&apos; cannot be marshalled by reference. The provided type must be concrete.. /// </summary> internal static string SafeHandleByRefMustBeConcrete { get { return ResourceManager.GetString("SafeHandleByRefMustBeConcrete", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Specified type is not supported by source-generated P/Invokes. /// </summary> internal static string TypeNotSupportedTitle { get { return ResourceManager.GetString("TypeNotSupportedTitle", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Marshalling a value between managed and native with a native type with a &apos;Value&apos; property requires extra state, which is not supported in this context.. /// </summary> internal static string ValuePropertyMarshallingRequiresAdditionalState { get { return ResourceManager.GetString("ValuePropertyMarshallingRequiresAdditionalState", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The native type&apos;s &apos;Value&apos; property must have a getter to support marshalling from managed to native.. /// </summary> internal static string ValuePropertyMustHaveGetterDescription { get { return ResourceManager.GetString("ValuePropertyMustHaveGetterDescription", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The &apos;Value&apos; property on the native type &apos;{0}&apos; must have a getter. /// </summary> internal static string ValuePropertyMustHaveGetterMessage { get { return ResourceManager.GetString("ValuePropertyMustHaveGetterMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The native type&apos;s &apos;Value&apos; property must have a setter to support marshalling from native to managed.. /// </summary> internal static string ValuePropertyMustHaveSetterDescription { get { return ResourceManager.GetString("ValuePropertyMustHaveSetterDescription", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The &apos;Value&apos; property on the native type &apos;{0}&apos; must have a setter. /// </summary> internal static string ValuePropertyMustHaveSetterMessage { get { return ResourceManager.GetString("ValuePropertyMustHaveSetterMessage", resourceCulture); } } } }
51.683377
493
0.635644
[ "MIT" ]
BodyBuildingKang/runtime
src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Resources.Designer.cs
19,590
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Threading; using DamageMeter.Sniffing; using Microsoft.Win32; using Tera; using Tera.Game.Messages; using MouseEventArgs = System.Windows.Input.MouseEventArgs; using OpcodeId = System.UInt16; using Point = System.Windows.Point; namespace PacketViewer.UI { /// <summary> /// Logique d'interaction pour MainWindow.xaml /// </summary> public partial class MainWindow : INotifyPropertyChanged { private bool _topMost = true; private int _count; private int _queued; private bool _bottom; private bool _newMessagesBelow; private PacketViewModel _packetDetails; private int _sizeFilter = -1; private int _currentSelectedItemIndex = 0; private string _currentFile; private DispatcherTimer _dbUpdateTimer; public int Queued { get => _queued; set { _queued = value; OnPropertyChanged(nameof(Queued)); } } public PacketViewModel PacketDetails { get => _packetDetails; set { if (_packetDetails == value) return; _packetDetails = value; OnPropertyChanged(nameof(PacketDetails)); } } public bool NewMessagesBelow { get => _newMessagesBelow; set { if (_newMessagesBelow == value) return; _newMessagesBelow = value; OnPropertyChanged(nameof(NewMessagesBelow)); } } public ObservableDictionary<ushort, OpcodeEnum> Known { get; set; } = new ObservableDictionary<ushort, OpcodeEnum>(); public ObservableCollection<PacketViewModel> All { get; set; } = new ObservableCollection<PacketViewModel>(); public ObservableCollection<OpcodeToFindVm> OpcodesToFind { get; set; } = new ObservableCollection<OpcodeToFindVm>(); public ObservableCollection<FilteredOpcodeVm> FilteredOpcodes { get; set; } = new ObservableCollection<FilteredOpcodeVm>(); public List<PacketViewModel> SearchList { get; set; } = new List<PacketViewModel>(); public DatabaseVm Database { get; } = new DatabaseVm(); public MainWindow() { InitializeComponent(); // Handler for exceptions in threads behind forms. TeraSniffer.Instance.Enabled = true; //TeraSniffer.Instance.Warning += PcapWarning; NetworkController.Instance.Connected += HandleConnected; NetworkController.Instance.GuildIconAction += InstanceOnGuildIconAction; Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.AboveNormal; Title = "Opcode Searcher V0"; SystemEvents.SessionEnding += new SessionEndingEventHandler(SystemEvents_SessionEnding); NetworkController.Instance.TickUpdated += (msg) => Dispatcher.BeginInvoke(new Action(() => HandleNewMessage(msg)), DispatcherPriority.Background); NetworkController.Instance.ResetUi += () => Dispatcher.Invoke(() => { All.Clear(); Known.Clear(); OpcodeNameConv.Instance.Clear(); }); All.CollectionChanged += All_CollectionChanged; DataContext = this; //((ItemsControl)KnownSw.Content).ItemsSource = Known; _dbUpdateTimer = new DispatcherTimer(); _dbUpdateTimer.Interval = TimeSpan.FromSeconds(1); _dbUpdateTimer.Tick += (sender, args) => Dispatcher.Invoke(()=> { Database.RefreshDatabase(); OnPropertyChanged(nameof(Database)); }); } private void CheckFindList(ushort opcode, OpcodeEnum opname) { var opc = OpcodesToFind.FirstOrDefault(x => x.OpcodeName == opname.ToString()); if (opc == null) { return; } if (opc.Opcode == 0) { opc.Opcode = opcode; opc.Confirmed = true; } else { if (opc.Opcode == opcode) { opc.Confirmed = true; } else { opc.Mismatching = opcode; } } } private void HandleNewMessage(Tuple<List<ParsedMessage>, Dictionary<OpcodeId, OpcodeEnum>, int> update) { Queued = update.Item3; if (update.Item2.Count != 0) { foreach (var opcode in update.Item2) { Dispatcher.Invoke(() => { Known.Add(opcode.Key, opcode.Value); CheckFindList(opcode.Key, opcode.Value); }); OpcodeNameConv.Instance.Known.Add(opcode.Key, opcode.Value); foreach (var packetViewModel in All.Where(x => x.Message.OpCode == opcode.Key)) { packetViewModel.RefreshName(); } } KnownSw.ScrollToBottom(); } foreach (var msg in update.Item1) { _count++; if (msg.Direction == MessageDirection.ServerToClient && ServerCb.IsChecked == false) return; if (msg.Direction == MessageDirection.ClientToServer && ClientCb.IsChecked == false) return; if (FilteredOpcodes.Count(x => x.Mode == FilterMode.ShowOnly) > 0 && FilteredOpcodes.Where(x => x.Mode == FilterMode.ShowOnly).All(x => x.Opcode != msg.OpCode)) return; if (FilteredOpcodes.Any(x => x.Opcode == msg.OpCode && x.Mode == FilterMode.Exclude)) return; if (SpamCb.IsChecked == true && All.Count > 0 && All.Last().Message.OpCode == msg.OpCode) return; if (_sizeFilter != -1) { if (msg.Payload.Count != _sizeFilter) return; } var vm = new PacketViewModel(msg, _count); All.Add(vm); if (SearchList.Count > 0) { if (SearchList[0].Message.OpCode == msg.OpCode) UpdateSearch(msg.OpCode.ToString(), false); //could be performance intensive } } //Dispatcher.Invoke(() => //{ // Database.RefreshDatabase(); // OnPropertyChanged(nameof(Database)); //}); } private void AllSw_ScrollChanged(object sender, System.Windows.Controls.ScrollChangedEventArgs e) { var b = VisualTreeHelper.GetChild(AllItemsControl, 0) as Border; var sw = VisualTreeHelper.GetChild(b, 0) as ScrollViewer; if (sw.VerticalOffset == sw.ScrollableHeight) { _bottom = true; NewMessagesBelow = false; } else _bottom = false; } private void All_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { var b = VisualTreeHelper.GetChild(AllItemsControl, 0) as Border; var sw = VisualTreeHelper.GetChild(b, 0) as ScrollViewer; if (_bottom) Dispatcher.Invoke(() => sw.ScrollToBottom()); else { NewMessagesBelow = true; } } private void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e) { Exit(); } private void InstanceOnGuildIconAction(Bitmap icon) { void ChangeUi(Bitmap bitmap) { //Icon = bitmap?.ToImageSource() ?? BasicTeraData.Instance.ImageDatabase.Icon; //NotifyIcon.Tray.Icon = bitmap?.GetIcon() ?? BasicTeraData.Instance.ImageDatabase.Tray; } Dispatcher.Invoke((NetworkController.GuildIconEvent)ChangeUi, icon); } private void MainWindow_OnLoaded(object sender, RoutedEventArgs e) { Top = 0; Left = 0; _dbUpdateTimer.Stop(); _dbUpdateTimer.Start(); } private void MainWindow_OnClosed(object sender, EventArgs e) { Exit(); } public void VerifyClose() { Close(); } public void Exit() { _topMost = false; NetworkController.Instance.Exit(); } public void HandleConnected(string serverName) { void ChangeTitle(string newServerName) { Title = newServerName; } Dispatcher.Invoke((ChangeTitle)ChangeTitle, serverName); } internal void StayTopMost() { if (!_topMost || !Topmost) { Debug.WriteLine("Not topmost"); return; } foreach (Window window in System.Windows.Application.Current.Windows) { window.Topmost = false; window.Topmost = true; } } private delegate void ChangeTitle(string servername); private void MessageClick(object sender, MouseButtonEventArgs e) { var s = ((Grid)sender); PacketDetails = s.DataContext as PacketViewModel; foreach (var packetViewModel in All) { packetViewModel.IsSelected = packetViewModel.Message == PacketDetails.Message; } OpcodeToFilter.Text = PacketDetails.Message.OpCode.ToString(); } private void HexSwChanged(object sender, ScrollChangedEventArgs e) { var s = sender as ScrollViewer; if (s.Name == nameof(HexSw)) TextSw.ScrollToVerticalOffset(HexSw.VerticalOffset); else HexSw.ScrollToVerticalOffset(TextSw.VerticalOffset); } private void ClearAll(object sender, RoutedEventArgs e) { All.Clear(); } private void Dump(object sender, RoutedEventArgs e) { var lines = new List<string>(); foreach (KeyValuePair<ushort, OpcodeEnum> keyVal in Known) { var s = $"{keyVal.Value} = {keyVal.Key}"; lines.Add(s); } File.WriteAllLines($"{Environment.CurrentDirectory}/opcodes {DateTime.Now.ToString().Replace('/', '-').Replace(':', '-')}.txt", lines); } private void LoadLog(object sender, RoutedEventArgs e) { var openFileDialog = new Microsoft.Win32.OpenFileDialog { Filter = "Supported Formats (*.TeraLog)|*.TeraLog" }; if (openFileDialog.ShowDialog() == false) return; NetworkController.Instance.LoadFileName = openFileDialog.FileName; } private void SaveLog(object sender, RoutedEventArgs e) { NetworkController.Instance.NeedToSave = true; } private void RemoveFilteredOpcode(object sender, RoutedEventArgs e) { var s = (System.Windows.Controls.Button)sender; FilteredOpcodes.Remove((FilteredOpcodeVm)s.DataContext); } private void AddBlackListedOpcode(object sender, RoutedEventArgs e) { if (string.IsNullOrEmpty(OpcodeToFilter.Text)) return; if (!ushort.TryParse(OpcodeToFilter.Text, out ushort result)) return; if (FilteredOpcodes.FirstOrDefault(x => x.Opcode == result) != null) return; FilteredOpcodes.Add(new FilteredOpcodeVm(result, FilterMode.Exclude)); OpcodeToFilter.Text = ""; } private void AddWhiteListedOpcode(object sender, RoutedEventArgs e) { if (string.IsNullOrEmpty(OpcodeToFilter.Text)) return; if (!ushort.TryParse(OpcodeToFilter.Text, out ushort result)) return; if (FilteredOpcodes.FirstOrDefault(x => x.Opcode == result) != null) return; FilteredOpcodes.Add(new FilteredOpcodeVm(result, FilterMode.ShowOnly)); OpcodeToFilter.Text = ""; } private void CopyPacketDetailsHex(object sender, RoutedEventArgs e) { StringBuilder bldr = new StringBuilder(); foreach (var a in PacketDetails.Data) { bldr.Append(a.Hex); } System.Windows.Clipboard.Clear(); System.Windows.Clipboard.SetDataObject(bldr.ToString(),false); } private void DataChunkMouseEnter(object sender, MouseEventArgs e) { var s = sender as FrameworkElement; var bvm = s.DataContext as ByteViewModel; bvm.IsHovered = true; int i = 0; i = HexIc.Items.IndexOf(bvm); if (i == -1) i = TextIc.Items.IndexOf(bvm); PacketDetails.RefreshData(i); } private void DataChunkMouseLeave(object sender, MouseEventArgs e) { var s = sender as FrameworkElement; var bvm = s.DataContext as ByteViewModel; bvm.IsHovered = false; } private void NewMessagesButtonClick(object sender, MouseButtonEventArgs e) { var b = VisualTreeHelper.GetChild(AllItemsControl, 0) as Border; var sw = VisualTreeHelper.GetChild(b, 0) as ScrollViewer; sw.ScrollToBottom(); } private void LoadOpcode(object sender, RoutedEventArgs e) { var openFileDialog = new Microsoft.Win32.OpenFileDialog { Filter = "Supported Formats, with / without '=' separator (*.txt)|*.txt" }; if (openFileDialog.ShowDialog() == false) return; NetworkController.Instance.StrictCheck = false; NetworkController.Instance.LoadOpcodeCheck = openFileDialog.FileName; } private void LoadOpcodeForViewing(object sender, RoutedEventArgs e) { var openFileDialog = new Microsoft.Win32.OpenFileDialog { Filter = "Supported Formats, with / without '=' separator (*.txt)|*.txt" }; if (openFileDialog.ShowDialog() == false) return; NetworkController.Instance.LoadOpcodeForViewing = openFileDialog.FileName; } private void SizeFilterTextChanged(object sender, TextChangedEventArgs e) { var s = sender as System.Windows.Controls.TextBox; if (string.IsNullOrEmpty(s.Text)) { _sizeFilter = -1; return; } try { _sizeFilter = Convert.ToInt32(s.Text); } catch { _sizeFilter = -1; } } private void SearchBoxChanged(object sender, TextChangedEventArgs e) { var s = sender as System.Windows.Controls.TextBox; UpdateSearch(s.Text, true); } private void UpdateSearch(string q, bool bringIntoView) { SearchList.Clear(); OnPropertyChanged(nameof(SearchList)); foreach (var packetViewModel in All) { //packetViewModel.IsSearched = true; packetViewModel.IsSearched = false; } if (string.IsNullOrEmpty(q)) { foreach (var packetViewModel in All) { //packetViewModel.IsSearched = true; packetViewModel.IsSearched = false; } return; } try { var query = Convert.ToUInt16(q); //search by opcode foreach (var packetViewModel in All.Where(x => x.Message.OpCode == query)) { packetViewModel.IsSearched = true; SearchList.Add(packetViewModel); } if (SearchList.Count != 0) { var i = All.IndexOf(SearchList[0]); if (bringIntoView) { //var container = AllItemsControl.ItemContainerGenerator.ContainerFromItem(All[i]) as FrameworkElement; //container.BringIntoView(); AllItemsControl.VirtualizedScrollIntoView(All[i]); PacketDetails = All[i]; } foreach (var packetViewModel in All) { packetViewModel.IsSelected = packetViewModel == All[i]; } } } catch (Exception exception) { //search by opcodename OpcodeEnum opEnum; try { opEnum = (OpcodeEnum)Enum.Parse(typeof(OpcodeEnum), q); } catch (Exception e1) { return; } foreach (var packetViewModel in All.Where(x => x.Message.OpCode == OpcodeFinder.Instance.GetOpcode(opEnum))) { packetViewModel.IsSearched = true; SearchList.Add(packetViewModel); } if (SearchList.Count != 0) { var i = All.IndexOf(SearchList[0]); if (bringIntoView) { //var container = AllItemsControl.ItemContainerGenerator.ContainerFromItem(All[i]) as FrameworkElement; //container.BringIntoView(); AllItemsControl.VirtualizedScrollIntoView(All[i]); PacketDetails = All[i]; } foreach (var packetViewModel in All) { packetViewModel.IsSelected = packetViewModel == All[i]; } } } OnPropertyChanged(nameof(SearchList)); } private void PreviousResult(object sender, RoutedEventArgs e) { if (SearchList.Count <2) return; if (_currentSelectedItemIndex == 0) _currentSelectedItemIndex = SearchList.Count - 1; else _currentSelectedItemIndex--; var i = All.IndexOf(SearchList[_currentSelectedItemIndex]); //var container = AllItemsControl.ItemContainerGenerator.ContainerFromItem(All[i]) as FrameworkElement; //container.BringIntoView(); AllItemsControl.VirtualizedScrollIntoView(All[i]); PacketDetails = All[i]; foreach (var packetViewModel in All) { packetViewModel.IsSelected = packetViewModel == All[i]; } } private void NextResult(object sender, RoutedEventArgs e) { if (SearchList.Count <2) return; if (_currentSelectedItemIndex == SearchList.Count - 1) _currentSelectedItemIndex = 0; else _currentSelectedItemIndex++; var i = All.IndexOf(SearchList[_currentSelectedItemIndex]); //var container = AllItemsControl.ItemContainerGenerator.ContainerFromItem(All[i]) as FrameworkElement; //container.BringIntoView(); AllItemsControl.VirtualizedScrollIntoView(All[i]); PacketDetails = All[i]; foreach (var packetViewModel in All) { packetViewModel.IsSelected = packetViewModel == All[i]; } } private void LoadOpcodeStrict(object sender, RoutedEventArgs e) { var openFileDialog = new Microsoft.Win32.OpenFileDialog { Filter = "Supported Formats, with / without '=' separator (*.txt)|*.txt" }; if (openFileDialog.ShowDialog() == false) return; NetworkController.Instance.StrictCheck = true; NetworkController.Instance.LoadOpcodeCheck = openFileDialog.FileName; } private void LoadList(object sender, RoutedEventArgs e) { var openFileDialog = new Microsoft.Win32.OpenFileDialog { Filter = "Opcode names list (*.txt, *map)|*.txt;*.map" }; if (openFileDialog.ShowDialog() == false) return; _currentFile = openFileDialog.FileName; var f = File.OpenText(_currentFile); OpcodesToFind.Clear(); while (true) { uint opc = 0; var l = f.ReadLine(); if (string.IsNullOrEmpty(l)) break; string opn = String.Empty; if (l.Contains("#")) { var symbolIndex = l.IndexOf("#"); if (symbolIndex == 0) continue; else { opn = l.Substring(0, symbolIndex - 1); } } else { opn = l; } var split = opn.Split(new string[] { " = " }, StringSplitOptions.RemoveEmptyEntries); if (split.Length > 1) { opn = split[0]; opc = Convert.ToUInt32(split[1]); OpcodesToFind.Add(new OpcodeToFindVm(opn, opc)); continue; } split = l.Split(' '); if (split.Length == 2) { opn = split[0]; opc = Convert.ToUInt32(split[1]); OpcodesToFind.Add(new OpcodeToFindVm(opn, opc)); continue; } OpcodesToFind.Add(new OpcodeToFindVm(opn, opc)); } foreach (KeyValuePair<ushort, OpcodeEnum> o in Known) { CheckFindList(o.Key, o.Value); } } private void SaveList(object sender, RoutedEventArgs e) { var lines = new List<string>(); foreach (var opcodeToFindVm in OpcodesToFind) { var line = $"{opcodeToFindVm.OpcodeName} = {opcodeToFindVm.Opcode}"; lines.Add(line); } File.WriteAllLines(_currentFile, lines); } private void TabClicked(object sender, MouseButtonEventArgs e) { var s = sender as FrameworkElement; var w = s.ActualWidth; var tp = s.TemplatedParent as FrameworkElement; var p = tp.Parent as UIElement; var r = s.TranslatePoint(new Point(0, 0), p); var sizeAn = new DoubleAnimation(w, TimeSpan.FromMilliseconds(250)) { EasingFunction = new QuadraticEase() }; var posAn = new DoubleAnimation(r.X, TimeSpan.FromMilliseconds(250)) { EasingFunction = new QuadraticEase() }; TabSelectionRect.BeginAnimation(WidthProperty, sizeAn); TabSelectionRect.RenderTransform.BeginAnimation(TranslateTransform.XProperty, posAn); } private void ClearAllFilters(object sender, RoutedEventArgs e) { FilteredOpcodes.Clear(); } private void HideLeftSlide(object sender, MouseButtonEventArgs e) { LeftSlide.RenderTransform.BeginAnimation(TranslateTransform.XProperty, new DoubleAnimation(-230,TimeSpan.FromMilliseconds(150)) {EasingFunction = new QuadraticEase()}); } private void OpenLeftSlide(object sender, RoutedEventArgs e) { LeftSlide.RenderTransform.BeginAnimation(TranslateTransform.XProperty, new DoubleAnimation(0, TimeSpan.FromMilliseconds(150)) { EasingFunction = new QuadraticEase() }); } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } private void ListEncounter_OnDropDownOpened(object sender, EventArgs e) { _topMost = false; } private void Close_MouseLeftButtonDown(object sender, RoutedEventArgs e) { VerifyClose(); } } }
38.966561
184
0.55907
[ "MIT" ]
Fenixk/ShinraMeter
PacketViewer.UI/Windows/MainWindow.xaml.cs
24,473
C#
using System; namespace RadianTools.Memory { internal class BufferMemoryCopier : AbstractMemoryCopier { public override string MethodName => $"{typeof(Buffer).FullName}.MemoryCopy"; public override unsafe void Copy(void* source, void* destination, uint destinationStart, uint length) { Buffer.MemoryCopy(source, (byte*)destination + destinationStart, length, length); } } }
28.866667
109
0.683603
[ "MIT" ]
radian-jp/RadianTools.Memory
src/RadianTools.Memory/BufferMemoryCopier.cs
435
C#
using System; using System.Collections.Generic; using System.Xml.Linq; namespace ApplicationCore.Core.RssCore { public class RssSyndicationCore { public string Title { get; set; } public string Description { get; set; } public string Link { get; set; } public ICollection<IRssItem> RssItems { get; set; } = new List<IRssItem>(); public XDocument Serialize() { var document = new XDocument(new XElement("rss")); document.Root.Add(new XAttribute("version", "2.0")); var channel = new XElement("channel"); channel.Add(new XElement("title", Title)); channel.Add(new XElement("link", Link)); channel.Add(new XElement("description", Description)); document.Root.Add(channel); foreach (var item in RssItems) { var itemElement = new XElement("item"); itemElement.Add(new XElement("title", item.Title)); itemElement.Add(new XElement("link", item.Link)); itemElement.Add(new XElement("description", item.Body)); if (item.AuthorName != null) { itemElement.Add(new XElement("author", $"{item.AuthorEmail} ({item.AuthorName})")); } if (!string.IsNullOrWhiteSpace(item.Permalink)) { itemElement.Add(new XElement("guid", item.Permalink)); } var dateFormat = item.CreateAt.ToString("r"); if (item.CreateAt != DateTime.MinValue) { itemElement.Add(new XElement("pubDate", dateFormat)); } channel.Add(itemElement); } return document; } } }
32.696429
103
0.533042
[ "MIT" ]
snicoper/BlogNet
src/ApplicationCore/Core/RssCore/RssSyndicationCore.cs
1,831
C#
using UnityEngine; using System.Collections; using System.Collections.Generic; using ComicSans.UI; using ComicSans.Player; using ComicSans.PoolingSystem; using ComicSans.DataContainers; using ComicSans.Boss.ActionSystem; namespace ComicSans.Boss { // The base script for the Bosses. // IMPORTANT: Remember to add a BossStateMachineHandler on the last Boss phase AnimationController in the 'Win' and 'Die' states. [AddComponentMenu("Scripts/Entity/Boss")] public class BossScript : EntityScript { public static BossScript instance; [Tooltip("Used to uniquile identify this Boss and to tag it's Audios and Projectiles.")] public string id; [Tooltip("Object containing all the colliders used by the Boss.")] [SerializeField] private GameObject _colliders = null; private Rigidbody2D _rigidbody = null; [Tooltip("List of phases used by the current Boss.")] [SerializeField] private List<BossPhase> phases = null; private int currentPhase = 0; private BossPattern currentPattern; private int currentAction = 0; private Animator _animator; [Tooltip("Delay after the Boss end animation.")] public float endAnimationDelay = 1.25f; // Use this for initialization protected override void Awake () { if(instance != null) { Debug.LogWarning("BossScript.Awake: More than one BossScript found! Deleting " + transform.name + "..."); Destroy(gameObject); } instance = this; base.Awake(); // Finds the boss Animator. _animator = GetComponentInChildren<Animator>(); if(_animator == null) Debug.LogWarning("BossScript.Awake: No Animator found on " + transform.name + "!"); // Gives an error if no collider GameObject is assigned the boss Collider. if(_colliders == null) Debug.LogWarning("BossScript.Awake: You need to assign the Colliders GameObject on " + transform.name + "!"); // Finds the boss Rigidbody. _rigidbody = GetComponentInChildren<Rigidbody2D>(); if(_rigidbody == null) Debug.LogWarning("BossScript.Awake: No Rigidbody found on " + transform.name + "!"); // Starts Boss movimentation. Initialize(); } public void Initialize() { // Checks if there is a phase. if(phases.Count < 1) { Debug.LogError("BossScript.Initialize " + transform.name + " has no phases!"); return; } // Initializes the Boss health bar. if(GameController.instance.uiController != null) GameController.instance.uiController.InitializeBossHUD(phases[currentPhase].bossPhaseName, health.Hp); else Debug.LogWarning("BossScript.Initialize: No UIController found!"); // Start the Boss invincibility. StartCoroutine(Reset(phases[currentPhase].invincibilityMultiplier)); // Sets the Boss AnimationController. if(_animator != null) _animator.runtimeAnimatorController = phases[currentPhase].animationController; // Initializes the Boss movementation. if(phases[currentPhase].firstPattern == null) { Debug.LogWarning("BossScript.Initialize: " + transform.name + "'s current phase has no first pattern."); return; } currentPattern = phases[currentPhase].firstPattern; // Gets the action to be executed. currentAction = 0; currentPattern.actions[currentAction].caller = this; currentPattern.actions[currentAction].DoAction(); } public void NextAction () { // Gets the action to be executed. currentAction++; // Goes to the next movement pattern. if(currentAction >= currentPattern.actions.Count) NextPattern(); currentPattern.actions[currentAction].caller = this; // Sets the caller of the action to this script. currentPattern.actions[currentAction].DoAction(); } private void NextPattern () { if(currentPattern.nextPattern.Count == 0) { Debug.LogWarning("BossScript.NextPattern: Current pattern has no nextPattern on " + transform.name + "!"); return; } transform.localScale = Vector3.one; // Ensures the Boss scale can't be left wrong by a previous pattern. // Checks the choice types for next pattern. foreach(BossPattern pattern in currentPattern.nextPattern) { // If the pattern choice type is Trigger check if the trigger is satisfied. if(pattern.choiceType != BossPattern.ChoiceType.Random) { switch (pattern.trigger) { case BossPattern.Trigger.PlayerOnRight: if(PlayerScript.instance != null) { if(PlayerScript.instance.transform.position.x > transform.position.x) { currentPattern = pattern; currentAction = 0; return; } } else Debug.LogWarning("BossScript.NextPattern: Player not found!"); break; case BossPattern.Trigger.PlayerOnLeft: if(PlayerScript.instance != null) { if(PlayerScript.instance.transform.position.x < transform.position.x) { currentPattern = pattern; currentAction = 0; return; } } else Debug.LogWarning("BossScript.NextPattern: Player not found!"); break; case BossPattern.Trigger.PlayerOnTop: if(PlayerScript.instance != null) { if(PlayerScript.instance.transform.position.y > transform.position.y) { currentPattern = pattern; currentAction = 0; return; } } else Debug.LogWarning("BossScript.NextPattern: Player not found!"); break; case BossPattern.Trigger.PlayerOnScreenRight: if(PlayerScript.instance != null) { if(PlayerScript.instance.transform.position.x >= 0) { currentPattern = pattern; currentAction = 0; return; } } else Debug.LogWarning("BossScript.NextPattern: Player not found!"); break; case BossPattern.Trigger.PlayerOnScreenLeft: if(PlayerScript.instance != null) { if(PlayerScript.instance.transform.position.x < 0) { currentPattern = pattern; currentAction = 0; return; } } else Debug.LogWarning("BossScript.NextPattern: Player not found!"); break; case BossPattern.Trigger.PlayerOnScreenTop: if(PlayerScript.instance != null) { if(PlayerScript.instance.transform.position.y >= 0) { currentPattern = pattern; currentAction = 0; return; } } else Debug.LogWarning("BossScript.NextPattern: Player not found!"); break; case BossPattern.Trigger.PlayerOnScreenBottom: if(PlayerScript.instance != null) { if(PlayerScript.instance.transform.position.y < 0) { currentPattern = pattern; currentAction = 0; return; } } else Debug.LogWarning("BossScript.NextPattern: Player not found!"); break; case BossPattern.Trigger.PlayerOnScreenDiagonalTop: if(PlayerScript.instance != null) { if(PlayerScript.instance.transform.position.y >= PlayerScript.instance.transform.position.x) { currentPattern = pattern; currentAction = 0; return; } } break; case BossPattern.Trigger.PlayerOnScreenDiagonalBottom: if(PlayerScript.instance != null) { if(PlayerScript.instance.transform.position.y < PlayerScript.instance.transform.position.x) { currentPattern = pattern; currentAction = 0; return; } } break; case BossPattern.Trigger.PlayerOnScreenAntiDiagonalTop: if(PlayerScript.instance != null) { if(PlayerScript.instance.transform.position.y >= -PlayerScript.instance.transform.position.x) { currentPattern = pattern; currentAction = 0; return; } } break; case BossPattern.Trigger.PlayerOnScreenAntiDiagonalBottom: if(PlayerScript.instance != null) { if(PlayerScript.instance.transform.position.y < -PlayerScript.instance.transform.position.x) { currentPattern = pattern; currentAction = 0; return; } } break; } } } // If no trigger is satisfied or all patterns choiceType is random, picks a random one between those that are not OnlyTrigger. // Goes through each possible next patterns and adds their chances together. int maxChance = 0; foreach(BossPattern pattern in currentPattern.nextPattern) { if(pattern.choiceType != BossPattern.ChoiceType.OnlyTrigger) maxChance += pattern.chance; } int newRandomPattern = Random.Range(0, maxChance); // Uses the random number to select between a boss patterns. int patternCounter = 0; foreach(BossPattern pattern in currentPattern.nextPattern) { if(pattern.choiceType != BossPattern.ChoiceType.OnlyTrigger) { if(newRandomPattern >= patternCounter && newRandomPattern < patternCounter + pattern.chance) { currentPattern = pattern; currentAction = 0; return; } patternCounter += pattern.chance; } } Debug.LogError("BossScript.NextPattern: No pattern randomly selected on " + transform.name + "! Either dark magic happened, or (more probable) someone did something wrong with the selection code."); } private void NextPhase() { currentPhase++; Debug.Log("BossScript.NextPhase: " + transform.name + " has gone to phase " + (currentPhase + 1) + "."); // Sets the Boss phase name. if(GameController.instance.uiController != null) GameController.instance.uiController.UpdateBossName(phases[currentPhase].bossPhaseName); else Debug.LogWarning("BossScript.NextPhase: No UIController found!"); // Sets the boss to the initial conditions. StopAllCoroutines(); // Despawns all previous phase projectiles. PoolingController.instance.DespawnBossObjects(); // Stops all previous phase sounds. AudioController.instance.StopWithTag(id); StartCoroutine(Reset(phases[currentPhase].invincibilityMultiplier)); // Resets the Boss position. transform.position = new Vector3(phases[currentPhase].initialPosition.x, phases[currentPhase].initialPosition.y, 0); // Sets the first pattern. currentPattern = phases[currentPhase].firstPattern; // Assigns the new AnimationController. _animator.runtimeAnimatorController = phases[currentPhase].animationController; // Gets the action to be executed. currentAction = 0; // Initiates new phase's first pattern actions. currentPattern.actions[currentAction].caller = this; currentPattern.actions[currentAction].DoAction(); } protected override void Damage() { // Guaratees the Boss can't take damage when he shouldn't. if(GameController.instance.currentGameState != GameController.GameState.Play) return; // Damages the Boss. health.Hp-=10; // Verifies if the Boss should pass to the next phase. if(health.Hp < phases[currentPhase].healthToNextPhase) { if(phases.Count > currentPhase + 1) NextPhase(); else Debug.LogWarning("BossScript.Damage: " + transform.name + " is trying to go to the next phase but it doesn't exist! If the current phase is the final remember to set lifeToNextPhase to a negative number on it's file."); return; } // Verifies if the boss has died. if(health.Hp <= 0) { Die(); return; } } // Updates the Boss health bar. protected override void UpdateLifeHUD() { if(GameController.instance.uiController != null) GameController.instance.uiController.UpdateBossHealthBar(health.Hp); else Debug.LogWarning("PlayerScript.UpdateLifeHUD: No UIController found!"); } // Resets the Boss position and aplies invincibility in scene transitions. protected override IEnumerator Reset(float invincibilityMultiplier) { _colliders.SetActive(false); // Disable Boss colliders so it doesn't take damage. // Idles for some time. float timer = 0; while(timer < health.invincibilityTime * invincibilityMultiplier) { timer += Time.fixedDeltaTime; yield return new WaitForFixedUpdate(); } _colliders.SetActive(true); // Re-enables Boss colliders. } protected override void Die() { // WORKAROUND =================================================================================== // Workaround used to stop Boss sounds played using PlayAudioDelayed, may not be necessary if a better fix is implemented. // Stops all Boss sounds. AudioController.instance.StopWithTag(BossScript.instance.id); // WORKAROUND =================================================================================== // Adds the Boss to the lsit of defeated Bosses and sets the game state. GameController.instance.defeatedBosses.Add(id); GameController.instance.currentGameState = GameController.GameState.Win; Debug.Log("BossScript.Die: " + transform.name + " has been defeated! (" + GameController.instance.defeatedBosses.Count + " different Bosses defeated)"); // Stops coroutines and despawns projectiles. StopAllCoroutines(); PoolingController.instance.DespawnBossObjects(); // Sets the animation. if(_animator != null) _animator.Play("Die", 0); // Disables the HUD. if(GameController.instance.uiController != null) GameController.instance.uiController.DisableHUD(); else Debug.LogWarning("BossScript.Die: No UIController found!"); } // Called by the player when it's defeated by the Boss. public void PlayerDefeated() { // WORKAROUND =================================================================================== // Workaround used to stop Boss sounds played using PlayAudioDelayed, may not be necessary if a better fix is implemented. // Stops all Boss sounds. AudioController.instance.StopWithTag(BossScript.instance.id); // WORKAROUND =================================================================================== // Sets the game state. GameController.instance.currentGameState = GameController.GameState.Lose; // Stops coroutines and despawns projectiles. StopAllCoroutines(); PoolingController.instance.DespawnBossObjects(); // Sets the animation. if(_animator != null) _animator.Play("Win", 0); // Disables the HUD. if(GameController.instance.uiController != null) GameController.instance.uiController.DisableHUD(); else Debug.LogWarning("BossScript.Die: No UIController found!"); } public void SetAnimation(List<AnimationSet> animations) { // Sets all animation parameters. foreach (AnimationSet anim in animations) _animator.SetInteger(anim.name, anim.value); } protected void OnDestroy() { // Stops the necessary Boss sounds (must be marked with this script Boss "id"). if(AudioController.instance != null) AudioController.instance.StopWithTag(id); // Destroys the pools generated by this Boss (must be marked with this script Boss "id"). if(PoolingController.instance != null) PoolingController.instance.DestroyWithTag(id); } } }
30.775391
225
0.642064
[ "MIT" ]
FellowshipOfTheGame/comic-sans
ComicSans/Assets/Scripts/Boss/BossScript.cs
15,759
C#
/* * LeagueClient * * 7.23.209.3517 * * OpenAPI spec version: 1.0.0 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.Text; using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; using System.ComponentModel.DataAnnotations; namespace LeagueClientApi.Model { /// <summary> /// LolEsportStreamNotificationsLiveMatch /// </summary> [DataContract] public partial class LolEsportStreamNotificationsLiveMatch : IEquatable<LolEsportStreamNotificationsLiveMatch>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="LolEsportStreamNotificationsLiveMatch" /> class. /// </summary> /// <param name="Id">Id.</param> /// <param name="StreamGroup">StreamGroup.</param> /// <param name="Teams">Teams.</param> /// <param name="Title">Title.</param> /// <param name="TournamentDescription">TournamentDescription.</param> public LolEsportStreamNotificationsLiveMatch(string Id = default(string), string StreamGroup = default(string), List<LolEsportStreamNotificationsLiveMatchTeam> Teams = default(List<LolEsportStreamNotificationsLiveMatchTeam>), string Title = default(string), string TournamentDescription = default(string)) { this.Id = Id; this.StreamGroup = StreamGroup; this.Teams = Teams; this.Title = Title; this.TournamentDescription = TournamentDescription; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id", EmitDefaultValue=false)] public string Id { get; set; } /// <summary> /// Gets or Sets StreamGroup /// </summary> [DataMember(Name="streamGroup", EmitDefaultValue=false)] public string StreamGroup { get; set; } /// <summary> /// Gets or Sets Teams /// </summary> [DataMember(Name="teams", EmitDefaultValue=false)] public List<LolEsportStreamNotificationsLiveMatchTeam> Teams { get; set; } /// <summary> /// Gets or Sets Title /// </summary> [DataMember(Name="title", EmitDefaultValue=false)] public string Title { get; set; } /// <summary> /// Gets or Sets TournamentDescription /// </summary> [DataMember(Name="tournamentDescription", EmitDefaultValue=false)] public string TournamentDescription { 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 LolEsportStreamNotificationsLiveMatch {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" StreamGroup: ").Append(StreamGroup).Append("\n"); sb.Append(" Teams: ").Append(Teams).Append("\n"); sb.Append(" Title: ").Append(Title).Append("\n"); sb.Append(" TournamentDescription: ").Append(TournamentDescription).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as LolEsportStreamNotificationsLiveMatch); } /// <summary> /// Returns true if LolEsportStreamNotificationsLiveMatch instances are equal /// </summary> /// <param name="other">Instance of LolEsportStreamNotificationsLiveMatch to be compared</param> /// <returns>Boolean</returns> public bool Equals(LolEsportStreamNotificationsLiveMatch other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.StreamGroup == other.StreamGroup || this.StreamGroup != null && this.StreamGroup.Equals(other.StreamGroup) ) && ( this.Teams == other.Teams || this.Teams != null && this.Teams.SequenceEqual(other.Teams) ) && ( this.Title == other.Title || this.Title != null && this.Title.Equals(other.Title) ) && ( this.TournamentDescription == other.TournamentDescription || this.TournamentDescription != null && this.TournamentDescription.Equals(other.TournamentDescription) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Id != null) hash = hash * 59 + this.Id.GetHashCode(); if (this.StreamGroup != null) hash = hash * 59 + this.StreamGroup.GetHashCode(); if (this.Teams != null) hash = hash * 59 + this.Teams.GetHashCode(); if (this.Title != null) hash = hash * 59 + this.Title.GetHashCode(); if (this.TournamentDescription != null) hash = hash * 59 + this.TournamentDescription.GetHashCode(); return hash; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
37.218085
313
0.554095
[ "MIT" ]
wildbook/LeagueClientApi
Model/LolEsportStreamNotificationsLiveMatch.cs
6,997
C#
//------------------------------------------------------------------------------ // <copyright file="SavedSearchProvider.cs" company="Aras Corporation"> // © 2017-2018 Aras Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.Xml; namespace Aras.VS.MethodPlugin.ItemSearch { public class SavedSearchProvider : ISavedSearchProvider { private readonly dynamic innovatorInstance; private readonly Dictionary<string, List<SavedSearch>> cachedSavedSearches = new Dictionary<string, List<SavedSearch>>(); public SavedSearchProvider(dynamic innovatorInstance) { if (innovatorInstance == null) throw new ArgumentNullException(nameof(innovatorInstance)); this.innovatorInstance = innovatorInstance; } public List<SavedSearch> GetSavedSearch(string itemTypeName) { List<SavedSearch> resultList; if (!cachedSavedSearches.TryGetValue(itemTypeName, out resultList)) { resultList = new List<SavedSearch>(); dynamic savedSearches = innovatorInstance.newItem(); savedSearches.loadAML(string.Format(@" <AML> <Item type=""SavedSearch"" action=""get""> <itname>{0}</itname> <auto_saved>0</auto_saved> </Item> </AML>", itemTypeName)); savedSearches = savedSearches.apply(); var searchesCount = savedSearches.getItemCount(); for (int i = 0; i < searchesCount; i++) { var search = new SavedSearch(); var savedSearch = savedSearches.getItemByIndex(i); search.SearchId = savedSearch.getID(); search.SearchName = savedSearch.getProperty("label"); search.ItemName = itemTypeName; string criteria = savedSearch.getProperty("criteria"); if (!string.IsNullOrEmpty(criteria)) { XmlDocument doc = new XmlDocument(); doc.LoadXml(criteria); var properties = doc.FirstChild.ChildNodes; foreach (XmlNode prop in properties) { var propertyInfo = new PropertyInfo(); propertyInfo.PropertyName = prop.Name; propertyInfo.PropertyValue = prop.InnerText; search.SavedSearchProperties.Add(propertyInfo); } } resultList.Add(search); } cachedSavedSearches.Add(itemTypeName, resultList); } return resultList; } } }
30.986842
123
0.65138
[ "MIT" ]
VitaliiPasichnykAmcbridge/ArasVSMethodPlugin
Aras.VS.MethodPlugin/ItemSearch/SavedSearchProvider.cs
2,358
C#
namespace AFramework { using System.Collections.Generic; /// <summary> /// SimpleObjectPool的二级父物体 /// </summary> /// <typeparam name="T"></typeparam> public abstract class Pool<T> : IPool<T>,ICountObserveAble { #region ICountObserverable /// <summary> /// 获取当前对象池中对象数量 /// </summary> public int CurCount { get { return mCacheStack.Count; } } #endregion //抽象工厂 protected IObjectFactory<T> mFactory; protected Stack<T> mCacheStack = new Stack<T>(); /// <summary> /// 默认为12 /// </summary> protected int mMaxCount = 12; public virtual T Allocate() { return mCacheStack.Count == 0 ? mFactory.Create() : mCacheStack.Pop(); } /// <summary> /// 回收 /// </summary> /// <param name="obj"></param> /// <returns></returns> public abstract bool Recycle(T obj); } }
24.046512
62
0.5
[ "Apache-2.0" ]
webloverand/AFramework
AFramework/Assets/Scripts/AFramework/Runtime/7.Extend/2.Pool/Pool/Pool.cs
1,088
C#
// ***************************************************************************** // BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE) // © Component Factory Pty Ltd, 2006-2019, All rights reserved. // The software and associated documentation supplied hereunder are the // proprietary information of Component Factory Pty Ltd, 13 Swallows Close, // Mornington, Vic 3931, Australia and are supplied subject to license terms. // // Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2019. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.472) // Version 5.472.0.0 www.ComponentFactory.com // ***************************************************************************** using System.Drawing; using System.Diagnostics; namespace ComponentFactory.Krypton.Ribbon { /// <summary> /// Draws either a large or small image from a group label. /// </summary> internal class ViewDrawRibbonGroupLabelImage : ViewDrawRibbonGroupImageBase { #region Static Fields private static Size _smallSize; // = new Size(16, 16); private static Size _largeSize;// = new Size(32, 32); #endregion #region Instance Fields private readonly KryptonRibbonGroupLabel _ribbonLabel; private readonly bool _large; #endregion #region Identity /// <summary> /// Initialize a new instance of the ViewDrawRibbonGroupLabelImage class. /// </summary> /// <param name="ribbon">Reference to owning ribbon control.</param> /// <param name="ribbonLabel">Reference to ribbon group label definition.</param> /// <param name="large">Show the large image.</param> public ViewDrawRibbonGroupLabelImage(KryptonRibbon ribbon, KryptonRibbonGroupLabel ribbonLabel, bool large) : base(ribbon) { Debug.Assert(ribbonLabel != null); //Seb dpi aware _smallSize = new Size((int)(16 * FactorDpiX), (int)(16 * FactorDpiY)); _largeSize = new Size((int)(32 * FactorDpiX), (int)(32 * FactorDpiY)); _ribbonLabel = ribbonLabel; _large = large; } /// <summary> /// Obtains the String representation of this instance. /// </summary> /// <returns>User readable name of the instance.</returns> public override string ToString() { // Return the class name and instance identifier return "ViewDrawRibbonGroupLabelImage:" + Id; } #endregion #region Protected /// <summary> /// Gets the size to draw the image. /// </summary> protected override Size DrawSize => _large ? _largeSize : _smallSize; /// <summary> /// Gets the image to be drawn. /// </summary> protected override Image DrawImage => _large ? _ribbonLabel.ImageLarge : _ribbonLabel.ImageSmall; #endregion } }
38.345679
157
0.586929
[ "BSD-3-Clause" ]
dave-w-au/Krypton-NET-5.472
Source/Krypton Components/ComponentFactory.Krypton.Ribbon/View Draw/ViewDrawRibbonGroupLabelImage.cs
3,109
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace apidata.Controllers { [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; } [HttpGet] public IEnumerable<WeatherForecast> Get() { var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)] }) .ToArray(); } } }
28.475
110
0.598771
[ "Apache-2.0" ]
mohamadlawand087/v43-delegates
apidata/Controllers/WeatherForecastController.cs
1,141
C#
using _7dtd_svmanager_fix_mvvm.Update.Models; using CommonStyleLib.Models; using CommonStyleLib.ViewModels; using Prism.Commands; using Reactive.Bindings; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; using System.Windows.Media; using _7dtd_svmanager_fix_mvvm.Update.Views; using CommonStyleLib.ExMessageBox; using CommonStyleLib.Views; using Reactive.Bindings.Extensions; namespace _7dtd_svmanager_fix_mvvm.Update.ViewModels { public class UpdFormViewModel : ViewModelBase { private readonly UpdFormModel _model; public UpdFormViewModel(WindowService windowService, UpdFormModel model, bool isAsync = false) : base(windowService, model) { _model = model; if (isAsync) { Loaded = new DelegateCommand(() => { }); } VersionListView = model.ToReactivePropertyAsSynchronized(m => m.VersionList); VersionListSelectedIndex = model.ToReactivePropertyAsSynchronized(m => m.VersionListSelectedIndex); UpdateBtIsEnabled = model.ToReactivePropertyAsSynchronized(m => m.CanUpdate); CancelBtIsEnabled = model.ToReactivePropertyAsSynchronized(m => m.CanCancel); RichDetailText = model.ToReactivePropertyAsSynchronized(m => m.RichDetailText); DetailText = model.ToReactivePropertyAsSynchronized(m => m.DetailText); CurrentVersion = model.ToReactivePropertyAsSynchronized(m => m.CurrentVersion); LatestVersion = model.ToReactivePropertyAsSynchronized(m => m.LatestVersion); VersionListSelectionChanged = new DelegateCommand<int?>(VersionList_SelectionChanged); DoUpdateCommand = new DelegateCommand(Update); DoCleanUpdateCommand = new DelegateCommand(CleanUpdate); OpenLinkCommand = new DelegateCommand<string>(OpenLink); } #region Properties public ReactiveProperty<ObservableCollection<string>> VersionListView { get; set; } public ReactiveProperty<int> VersionListSelectedIndex { get; set; } public ReactiveProperty<bool> UpdateBtIsEnabled { get; set; } public ReactiveProperty<bool> CancelBtIsEnabled { get; set; } public ReactiveProperty<ObservableCollection<RichTextItem>> RichDetailText { get; set; } public ReactiveProperty<string> DetailText { get; set; } public ReactiveProperty<string> CurrentVersion { get; set; } public ReactiveProperty<string> LatestVersion { get; set; } #endregion #region EventProperties public ICommand VersionListSelectionChanged { get; } public ICommand DoCleanUpdateCommand { get; } public ICommand DoUpdateCommand { get; } public ICommand OpenLinkCommand { get; } #endregion #region EventMethods protected override void MainWindow_Loaded() { var task = _model.Initialize(); task.ContinueWith(t => { if (t.Exception == null) return; foreach (var exceptionInnerException in t.Exception.InnerExceptions) App.ShowAndWriteException(exceptionInnerException); }, TaskContinuationOptions.OnlyOnFaulted); } private void VersionList_SelectionChanged(int? arg) { if (arg != null) { var index = arg.Value; _model.ShowDetails(index); } } private void Update() { _ = CheckUpdate(); } private void CleanUpdate() { var files = _model.GetCleanFiles().Where(x => !x.Contains("Updater\\")); var checkFileModel = new CheckCleanFileModel(files); var checkViewModel = new CheckCleanFileViewModel(new WindowService(), checkFileModel); WindowManageService.ShowDialog<CheckCleanFile>(checkViewModel); if (checkFileModel.CanCleanUpdate) { var targets = checkFileModel.GetTargetFiles(); var enumerable = targets.ToList(); _ = CheckCleanUpdate(enumerable); } } private async Task CheckUpdate() { var (notice, isConfirm) = await _model.CheckAlert(); if (string.IsNullOrEmpty(notice)) { await _model.Update(); return; } if (isConfirm) { var dr = WindowManageService.MessageBoxShow(notice, "Notice", ExMessageBoxBase.MessageType.Exclamation, ExMessageBoxBase.ButtonType.YesNo); if (dr == ExMessageBoxBase.DialogResult.Yes) await _model.Update(); } else { WindowManageService.MessageBoxShow(notice, "Notice", ExMessageBoxBase.MessageType.Exclamation); await _model.Update(); } } private async Task CheckCleanUpdate(IReadOnlyCollection<string> targets) { var (notice, isConfirm) = await _model.CheckAlert(); if (string.IsNullOrEmpty(notice)) { await (targets.Any() ? _model.CleanUpdate(targets) : _model.Update()); return; } if (isConfirm) { var dr = WindowManageService.MessageBoxShow(notice, "Notice", ExMessageBoxBase.MessageType.Exclamation, ExMessageBoxBase.ButtonType.YesNo); if (dr == ExMessageBoxBase.DialogResult.Yes) await (targets.Any() ? _model.CleanUpdate(targets) : _model.Update()); } else { WindowManageService.MessageBoxShow(notice, "Notice", ExMessageBoxBase.MessageType.Exclamation); await (targets.Any() ? _model.CleanUpdate(targets) : _model.Update()); } } public void OpenLink(string url) { var dialogResult = ExMessageBoxBase.Show("Are you sure open it with default browser?", "Open Browser", ExMessageBoxBase.MessageType.Question, ExMessageBoxBase.ButtonType.YesNo); if (dialogResult == ExMessageBoxBase.DialogResult.Yes) Process.Start(new ProcessStartInfo { UseShellExecute = true, FileName = url }); } #endregion } }
38.137143
153
0.615523
[ "MIT", "BSD-3-Clause" ]
AonaSuzutsuki/SavannahManager
SavannahManager/Update/ViewModels/UpdFormViewModel.cs
6,676
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. // // Revision history: // // ER, BD - July 2013 - Created this file. // using System.Collections.Generic; using System.Linq.CompilerServices; using System.Linq.Expressions; using System.Runtime.CompilerServices; namespace Tests.Nuqleon.DataModel.CompilerServices { internal class ExpressionComparator : ExpressionEqualityComparator { private readonly IEqualityComparer<object> _objectComparer; public ExpressionComparator(TypeComparator typeComparer, ObjectComparator objectComparer) : base(typeComparer, typeComparer.MemberComparer, objectComparer, EqualityComparer<CallSiteBinder>.Default) { objectComparer.ExpressionComparator = this; _objectComparer = objectComparer; } public static ExpressionComparator CreateInstance() { return new ExpressionComparator(new TypeComparator(), ObjectComparator.CreateInstance()); } public override bool Equals(Expression x, Expression y) { if (x == null && y == null) { return true; } if (x == null || y == null) { return false; } if (x.NodeType != y.NodeType) { var xValue = x.Evaluate(); var yValue = y.Evaluate(); return _objectComparer.Equals(xValue, yValue); } return base.Equals(x, y); } } }
29.649123
119
0.618935
[ "MIT" ]
Botcoin-com/reaqtor
Nuqleon/Core/DataModel/Tests.Nuqleon.DataModel.CompilerServices/Helpers/ExpressionComparator.cs
1,692
C#
namespace Estagiado.Views { partial class FormExcluirContaEst { /// <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.label1 = new System.Windows.Forms.Label(); this.btnExcluirConta = new System.Windows.Forms.Button(); this.cbIdCandidato = new System.Windows.Forms.ComboBox(); this.btnEncontrarIdComCpf = new System.Windows.Forms.Button(); this.txtCpfBusca = new System.Windows.Forms.MaskedTextBox(); this.label11 = new System.Windows.Forms.Label(); this.dgvEstudante = new System.Windows.Forms.DataGridView(); this.txtSenha = new System.Windows.Forms.TextBox(); this.labelSenha = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.dgvEstudante)).BeginInit(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.86792F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.ForeColor = System.Drawing.Color.Red; this.label1.ImeMode = System.Windows.Forms.ImeMode.NoControl; this.label1.Location = new System.Drawing.Point(201, 70); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(396, 40); this.label1.TabIndex = 104; this.label1.Text = "Tem certeza que deseja excluir sua conta?\r\nIsso apagará permanentemente os seus d" + "ados. \r\n"; this.label1.TextAlign = System.Drawing.ContentAlignment.TopCenter; // // btnExcluirConta // this.btnExcluirConta.BackColor = System.Drawing.Color.Red; this.btnExcluirConta.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.18868F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnExcluirConta.ImeMode = System.Windows.Forms.ImeMode.NoControl; this.btnExcluirConta.Location = new System.Drawing.Point(347, 369); this.btnExcluirConta.Name = "btnExcluirConta"; this.btnExcluirConta.Size = new System.Drawing.Size(113, 46); this.btnExcluirConta.TabIndex = 108; this.btnExcluirConta.Text = "Excluir Conta"; this.btnExcluirConta.UseVisualStyleBackColor = false; this.btnExcluirConta.Click += new System.EventHandler(this.btnExcluirConta_Click); // // cbIdCandidato // this.cbIdCandidato.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.18868F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.cbIdCandidato.FormattingEnabled = true; this.cbIdCandidato.Location = new System.Drawing.Point(423, 213); this.cbIdCandidato.Name = "cbIdCandidato"; this.cbIdCandidato.Size = new System.Drawing.Size(37, 26); this.cbIdCandidato.TabIndex = 113; // // btnEncontrarIdComCpf // this.btnEncontrarIdComCpf.BackColor = System.Drawing.SystemColors.Highlight; this.btnEncontrarIdComCpf.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.18868F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnEncontrarIdComCpf.Location = new System.Drawing.Point(347, 211); this.btnEncontrarIdComCpf.Name = "btnEncontrarIdComCpf"; this.btnEncontrarIdComCpf.Size = new System.Drawing.Size(72, 28); this.btnEncontrarIdComCpf.TabIndex = 112; this.btnEncontrarIdComCpf.Text = "Buscar"; this.btnEncontrarIdComCpf.UseVisualStyleBackColor = false; this.btnEncontrarIdComCpf.Click += new System.EventHandler(this.btnEncontrarIdComCpf_Click); // // txtCpfBusca // this.txtCpfBusca.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.18868F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtCpfBusca.Location = new System.Drawing.Point(347, 151); this.txtCpfBusca.Mask = "000,000,000-00"; this.txtCpfBusca.Name = "txtCpfBusca"; this.txtCpfBusca.Size = new System.Drawing.Size(113, 24); this.txtCpfBusca.TabIndex = 111; // // label11 // this.label11.AutoSize = true; this.label11.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.18868F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label11.Location = new System.Drawing.Point(346, 125); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(107, 20); this.label11.TabIndex = 110; this.label11.Text = "Buscar dados"; // // dgvEstudante // this.dgvEstudante.AllowUserToAddRows = false; this.dgvEstudante.AllowUserToDeleteRows = false; this.dgvEstudante.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.DisplayedCells; this.dgvEstudante.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.DisplayedCells; this.dgvEstudante.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dgvEstudante.Location = new System.Drawing.Point(58, 257); this.dgvEstudante.Name = "dgvEstudante"; this.dgvEstudante.ReadOnly = true; this.dgvEstudante.RowHeadersWidth = 45; this.dgvEstudante.Size = new System.Drawing.Size(691, 91); this.dgvEstudante.TabIndex = 109; // // txtSenha // this.txtSenha.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.18868F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtSenha.Location = new System.Drawing.Point(347, 181); this.txtSenha.Name = "txtSenha"; this.txtSenha.PasswordChar = '*'; this.txtSenha.Size = new System.Drawing.Size(113, 24); this.txtSenha.TabIndex = 115; // // labelSenha // this.labelSenha.AutoSize = true; this.labelSenha.Font = new System.Drawing.Font("Segoe UI", 10.18868F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelSenha.Location = new System.Drawing.Point(294, 184); this.labelSenha.Name = "labelSenha"; this.labelSenha.Size = new System.Drawing.Size(53, 21); this.labelSenha.TabIndex = 114; this.labelSenha.Text = "Senha"; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.18868F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.Location = new System.Drawing.Point(294, 157); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(40, 20); this.label2.TabIndex = 116; this.label2.Text = "CPF"; // // FormExcluirContaEst // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(800, 450); this.Controls.Add(this.label2); this.Controls.Add(this.txtSenha); this.Controls.Add(this.labelSenha); this.Controls.Add(this.cbIdCandidato); this.Controls.Add(this.btnEncontrarIdComCpf); this.Controls.Add(this.txtCpfBusca); this.Controls.Add(this.label11); this.Controls.Add(this.dgvEstudante); this.Controls.Add(this.btnExcluirConta); this.Controls.Add(this.label1); this.Name = "FormExcluirContaEst"; this.Text = "Formulário de Exclusão de Conta"; this.Load += new System.EventHandler(this.FormExcluirContaEst_Load); ((System.ComponentModel.ISupportInitialize)(this.dgvEstudante)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.Button btnExcluirConta; private System.Windows.Forms.Button btnEncontrarIdComCpf; private System.Windows.Forms.MaskedTextBox txtCpfBusca; private System.Windows.Forms.Label label11; private System.Windows.Forms.DataGridView dgvEstudante; private System.Windows.Forms.ComboBox cbIdCandidato; private System.Windows.Forms.TextBox txtSenha; private System.Windows.Forms.Label labelSenha; private System.Windows.Forms.Label label2; } }
53.005236
186
0.62337
[ "MIT" ]
coivan/Estagiado
Estagiado/Views/FormExcluirContaEst.Designer.cs
10,129
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; using System.Web; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Filters; namespace Xigadee { public class ClientCertificateAuthorizationFilter : IAuthorizationFilter { private readonly bool mVerifyCertificate; private readonly List<string> mClientCertificateThumbprints; private readonly HashSet<string> mValidThumbprints; public bool AllowMultiple => false; public ClientCertificateAuthorizationFilter(bool verifyCertificate, List<string> clientCertificateThumbprints) { mVerifyCertificate = verifyCertificate; mClientCertificateThumbprints = clientCertificateThumbprints; mValidThumbprints = new HashSet<string>(); } public Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation) { HttpContext context = HttpContext.Current; var request = actionContext.Request; if (!context.Request.ClientCertificate.IsPresent) { // If no certificate has been supplied but this controller/action allows no certificate // access then let this call through if (actionContext.ActionDescriptor.GetCustomAttributes<AllowNoClientCertificateAttribute>().Any() || actionContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes<AllowNoClientCertificateAttribute>().Any()) return continuation(); HttpResponseMessage response = request.CreateResponse(HttpStatusCode.Unauthorized); response.Content = new StringContent("Client certificate missing"); return Task.FromResult(response); } try { var clientCert = new X509Certificate2(context.Request.ClientCertificate.Certificate); if (DateTime.Now < clientCert.NotBefore || DateTime.Now > clientCert.NotAfter) { HttpResponseMessage response = request.CreateResponse(HttpStatusCode.Unauthorized); response.Content = new StringContent($"Client certificate has expired or not yet valid {clientCert.NotBefore}-{clientCert.NotAfter}"); return Task.FromResult(response); } if (mVerifyCertificate && !clientCert.Verify()) { HttpResponseMessage response = request.CreateResponse(HttpStatusCode.Unauthorized); response.Content = new StringContent("Client certificate not valid"); return Task.FromResult(response); } // If we have already validated this thumbprint then continue if (!string.IsNullOrEmpty(clientCert.Thumbprint) && mValidThumbprints.Contains(clientCert.Thumbprint)) return continuation(); // If we have thumbprints to verify against check the certificate is in the list if (mClientCertificateThumbprints.Any() && mClientCertificateThumbprints.FirstOrDefault(m => m.Equals(clientCert.Thumbprint?.Trim(), StringComparison.InvariantCultureIgnoreCase)) == null) { HttpResponseMessage response = request.CreateResponse(HttpStatusCode.Unauthorized); response.Content = new StringContent($"Client thumbprint ({clientCert.Thumbprint?.Trim()}) does not match an expected value "); return Task.FromResult(response); } if (!string.IsNullOrEmpty(clientCert.Thumbprint) && !mValidThumbprints.Contains(clientCert.Thumbprint)) mValidThumbprints.Add(clientCert.Thumbprint); } catch (Exception ex) { HttpResponseMessage response = request.CreateResponse(HttpStatusCode.Unauthorized); response.Content = new StringContent($"Cannot check client certificate - {ex.Message}"); return Task.FromResult(response); } // All good so continue return continuation(); } } }
47.808511
188
0.653316
[ "Apache-2.0" ]
xigadee/Microservice
Src/Xigadee.Api.Server/Owin/ClientCertificateAuthorizationFilter.cs
4,496
C#
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace Microsoft.Azure.Cosmos.Performance.Tests { using System; using System.Collections.Generic; using System.Linq; using BenchmarkDotNet.Configs; using BenchmarkDotNet.Reports; using BenchmarkDotNet.Running; class Program { static int Main(string[] args) { //CosmosDBConfiguration environmentConfiguration = ConfigurationService.Configuration; //Console.WriteLine($"Starting benchmark and dropping results on {environmentConfiguration.ReportsPath}."); //BenchmarkRunner.Run<ItemBenchmark>(new CustomBenchmarkConfiguration(environmentConfiguration)); IEnumerable<Summary> summaries = BenchmarkSwitcher .FromAssembly(typeof(Program).Assembly) .Run(args); // If any of the operations have NA then something failed. Returning -1 will cause the gates to fail. foreach (Summary summary in summaries) { string[] content = summary.Table.Columns.First(x => string.Equals(@"Op/s", x.Header)).Content; foreach (string ops in content) { if (string.Equals(@"NA", ops)) { return -1; } } } return 0; } } }
35.767442
119
0.542263
[ "MIT" ]
ORuban/azure-cosmos-dotnet-v3
Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Performance.Tests/Program.cs
1,540
C#
using System.Net; using System.Threading.Tasks; using KdyWeb.BaseInterface.BaseModel; using KdyWeb.Dto.SearchVideo; using KdyWeb.IService.SearchVideo; using Microsoft.AspNetCore.Mvc; namespace KdyWeb.Job.Controllers { /// <summary> /// 影片采集 /// </summary> public class VideoCaptureController : OldBaseApiController { private readonly IVideoCaptureService _videoCaptureService; public VideoCaptureController(IVideoCaptureService videoCaptureService) { _videoCaptureService = videoCaptureService; } /// <summary> /// 根据影片源详情创建影片 /// </summary> /// <returns></returns> [HttpPost("createForDetail")] [ProducesResponseType(typeof(KdyResult), (int)HttpStatusCode.OK)] public async Task<IActionResult> QueryUserSubscribeAsync(CreateVideoInfoByDetailInput input) { var result = await _videoCaptureService.CreateVideoInfoByDetailAsync(input); return Ok(result); } } }
29.342857
100
0.677702
[ "Apache-2.0" ]
bohejing/KdyWeb.NetCore
src/KdyWeb.Job/Controllers/VideoCaptureController.cs
1,059
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using FlowTomator.Common; namespace FlowTomator.Desktop { public class RenameVariableAction : Action { public VariableInfo VariableInfo { get; private set; } public RenameVariableAction(VariableInfo variableInfo, string name) { VariableInfo = variableInfo; } public override void Do() { VariableInfo.Update(); } public override void Undo() { VariableInfo.Update(); } } }
20.666667
75
0.622581
[ "MIT" ]
jbatonnet/FlowTomator
FlowTomator.Desktop/Actions/RenameVariable.cs
622
C#
namespace p03._01.FightingArena { using System; public class StartUp { public static void Main(string[] args) { //Creates arena Arena arena = new Arena("Armeec"); //Creates stats Stat firstGlariatorStat = new Stat(20, 25, 35, 14, 48); Stat secondGlariatorStat = new Stat(40, 40, 40, 40, 40); Stat thirdGlariatorStat = new Stat(20, 25, 35, 14, 48); //Creates weapons Weapon firstGlariatorWeapon = new Weapon(5, 28, 100); Weapon secondGlariatorWeapon = new Weapon(5, 28, 100); Weapon thirdGlariatorWeapon = new Weapon(50, 50, 50); //Creates gladiators Gladiator firstGladiator = new Gladiator("Stoyan", firstGlariatorStat, firstGlariatorWeapon); Gladiator secondGladiator = new Gladiator("Pesho", secondGlariatorStat, secondGlariatorWeapon); Gladiator thirdGladiator = new Gladiator("Gosho", thirdGlariatorStat, thirdGlariatorWeapon); //Adds gladiators to arena arena.Add(firstGladiator); arena.Add(secondGladiator); arena.Add(thirdGladiator); //Prints gladiators count at the arena Console.WriteLine(arena.Count); //Gets strongest gladiator and print him Gladiator strongestGladiator = arena.GetGladitorWithHighestTotalPower(); Console.WriteLine(strongestGladiator); //Gets gladiator with the strongest weapon and print him Gladiator bestWeaponGladiator = arena.GetGladitorWithHighestWeaponPower(); Console.WriteLine(bestWeaponGladiator); //Gets gladiator with the strongest stat and print him Gladiator bestStatGladiator = arena.GetGladitorWithHighestStatPower(); Console.WriteLine(bestStatGladiator); //Removes gladiator arena.Remove("Gosho"); //Prints gladiators count at the arena Console.WriteLine(arena.Count); //Prints the arena Console.WriteLine(arena); } } }
36.896552
107
0.62243
[ "MIT" ]
vesy53/SoftUni
C# Advanced/C#Adanced/Exams/Exam16April2019/p03.01.FightingArena/StartUp.cs
2,142
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Rotation : MonoBehaviour { // Before rendering each frame.. void Update () { // Rotate the game object that this script is attached to by 15 in the X axis, // 30 in the Y axis and 45 in the Z axis, multiplied by deltaTime in order to make it per second // rather than per frame. transform.Rotate (new Vector3 (15, 30, 45) * Time.deltaTime); } }
28.25
98
0.721239
[ "MIT" ]
myersans/john_lemon
Assets/Scripts/Rotation.cs
452
C#
using System; namespace Chartreuse.Today.Core.Shared.Tools.Tracking { public static class TrackingManagerHelper { public static void Exception(Exception exception, string message = null, bool isFatal = false) { if (Ioc.HasType<ITrackingManager>()) { ITrackingManager trackingManager = Ioc.Resolve<ITrackingManager>(); trackingManager.Exception(exception, message, isFatal); } } public static void Trace(string message) { if (Ioc.HasType<ITrackingManager>()) { ITrackingManager trackingManager = Ioc.Resolve<ITrackingManager>(); trackingManager.Trace(message); } } } }
29.5
102
0.586701
[ "MIT" ]
2DayApp/2day
src/2Day.Core.Shared/Tools/Tracking/TrackingManagerHelper.cs
769
C#
using System; using System.ComponentModel.DataAnnotations; namespace signup_verification.Models.Accounts { public class ForgotPasswordRequest { [Required] [EmailAddress] public string Email { get; set; } } }
18.923077
45
0.682927
[ "MIT" ]
shockzinfinity/signup-verification-test
Models/Accounts/ForgotPasswordRequest.cs
248
C#
#pragma checksum "C:\School\NP\Np_class\SSD\week 05\RazorPagesMovie\RazorPagesMovie\Pages\Movies\Details.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "a8c7cb8c8b365cbf9d2845fc41e47874926481fe" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(RazorPagesMovie.Pages.Movies.Pages_Movies_Details), @"mvc.1.0.razor-page", @"/Pages/Movies/Details.cshtml")] [assembly:global::Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.RazorPageAttribute(@"/Pages/Movies/Details.cshtml", typeof(RazorPagesMovie.Pages.Movies.Pages_Movies_Details), @"{id:int?}")] namespace RazorPagesMovie.Pages.Movies { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #line 1 "C:\School\NP\Np_class\SSD\week 05\RazorPagesMovie\RazorPagesMovie\Pages\_ViewImports.cshtml" using RazorPagesMovie; #line default #line hidden [global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemMetadataAttribute("RouteTemplate", "{id:int?}")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"a8c7cb8c8b365cbf9d2845fc41e47874926481fe", @"/Pages/Movies/Details.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"5bffd98f02597e6a09295a2131188dc64093be78", @"/Pages/_ViewImports.cshtml")] public class Pages_Movies_Details : global::Microsoft.AspNetCore.Mvc.RazorPages.Page { private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-page", "./Edit", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-page", "./Index", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); #line hidden #pragma warning disable 0169 private string __tagHelperStringValueBuffer; #pragma warning restore 0169 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner(); private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager { get { if (__backed__tagHelperScopeManager == null) { __backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); } return __backed__tagHelperScopeManager; } } private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper; #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { BeginContext(69, 2, true); WriteLiteral("\r\n"); EndContext(); #line 4 "C:\School\NP\Np_class\SSD\week 05\RazorPagesMovie\RazorPagesMovie\Pages\Movies\Details.cshtml" ViewData["Title"] = "Details"; #line default #line hidden BeginContext(114, 126, true); WriteLiteral("\r\n<h1>Details</h1>\r\n\r\n<div>\r\n <h4>Movie</h4>\r\n <hr />\r\n <dl class=\"row\">\r\n <dt class=\"col-sm-2\">\r\n "); EndContext(); BeginContext(241, 47, false); #line 15 "C:\School\NP\Np_class\SSD\week 05\RazorPagesMovie\RazorPagesMovie\Pages\Movies\Details.cshtml" Write(Html.DisplayNameFor(model => model.Movie.Title)); #line default #line hidden EndContext(); BeginContext(288, 61, true); WriteLiteral("\r\n </dt>\r\n <dd class=\"col-sm-10\">\r\n "); EndContext(); BeginContext(350, 43, false); #line 18 "C:\School\NP\Np_class\SSD\week 05\RazorPagesMovie\RazorPagesMovie\Pages\Movies\Details.cshtml" Write(Html.DisplayFor(model => model.Movie.Title)); #line default #line hidden EndContext(); BeginContext(393, 60, true); WriteLiteral("\r\n </dd>\r\n <dt class=\"col-sm-2\">\r\n "); EndContext(); BeginContext(454, 53, false); #line 21 "C:\School\NP\Np_class\SSD\week 05\RazorPagesMovie\RazorPagesMovie\Pages\Movies\Details.cshtml" Write(Html.DisplayNameFor(model => model.Movie.ReleaseDate)); #line default #line hidden EndContext(); BeginContext(507, 61, true); WriteLiteral("\r\n </dt>\r\n <dd class=\"col-sm-10\">\r\n "); EndContext(); BeginContext(569, 49, false); #line 24 "C:\School\NP\Np_class\SSD\week 05\RazorPagesMovie\RazorPagesMovie\Pages\Movies\Details.cshtml" Write(Html.DisplayFor(model => model.Movie.ReleaseDate)); #line default #line hidden EndContext(); BeginContext(618, 60, true); WriteLiteral("\r\n </dd>\r\n <dt class=\"col-sm-2\">\r\n "); EndContext(); BeginContext(679, 47, false); #line 27 "C:\School\NP\Np_class\SSD\week 05\RazorPagesMovie\RazorPagesMovie\Pages\Movies\Details.cshtml" Write(Html.DisplayNameFor(model => model.Movie.Genre)); #line default #line hidden EndContext(); BeginContext(726, 61, true); WriteLiteral("\r\n </dt>\r\n <dd class=\"col-sm-10\">\r\n "); EndContext(); BeginContext(788, 43, false); #line 30 "C:\School\NP\Np_class\SSD\week 05\RazorPagesMovie\RazorPagesMovie\Pages\Movies\Details.cshtml" Write(Html.DisplayFor(model => model.Movie.Genre)); #line default #line hidden EndContext(); BeginContext(831, 60, true); WriteLiteral("\r\n </dd>\r\n <dt class=\"col-sm-2\">\r\n "); EndContext(); BeginContext(892, 47, false); #line 33 "C:\School\NP\Np_class\SSD\week 05\RazorPagesMovie\RazorPagesMovie\Pages\Movies\Details.cshtml" Write(Html.DisplayNameFor(model => model.Movie.Price)); #line default #line hidden EndContext(); BeginContext(939, 61, true); WriteLiteral("\r\n </dt>\r\n <dd class=\"col-sm-10\">\r\n "); EndContext(); BeginContext(1001, 43, false); #line 36 "C:\School\NP\Np_class\SSD\week 05\RazorPagesMovie\RazorPagesMovie\Pages\Movies\Details.cshtml" Write(Html.DisplayFor(model => model.Movie.Price)); #line default #line hidden EndContext(); BeginContext(1044, 60, true); WriteLiteral("\r\n </dd>\r\n <dt class=\"col-sm-2\">\r\n "); EndContext(); BeginContext(1105, 48, false); #line 39 "C:\School\NP\Np_class\SSD\week 05\RazorPagesMovie\RazorPagesMovie\Pages\Movies\Details.cshtml" Write(Html.DisplayNameFor(model => model.Movie.Rating)); #line default #line hidden EndContext(); BeginContext(1153, 61, true); WriteLiteral("\r\n </dt>\r\n <dd class=\"col-sm-10\">\r\n "); EndContext(); BeginContext(1215, 44, false); #line 42 "C:\School\NP\Np_class\SSD\week 05\RazorPagesMovie\RazorPagesMovie\Pages\Movies\Details.cshtml" Write(Html.DisplayFor(model => model.Movie.Rating)); #line default #line hidden EndContext(); BeginContext(1259, 47, true); WriteLiteral("\r\n </dd>\r\n </dl>\r\n</div>\r\n<div>\r\n "); EndContext(); BeginContext(1306, 60, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "a8c7cb8c8b365cbf9d2845fc41e47874926481fe8671", async() => { BeginContext(1358, 4, true); WriteLiteral("Edit"); EndContext(); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Page = (string)__tagHelperAttribute_0.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0); if (__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues == null) { throw new InvalidOperationException(InvalidTagHelperIndexerAssignment("asp-route-id", "Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper", "RouteValues")); } BeginWriteTagHelperAttribute(); #line 47 "C:\School\NP\Np_class\SSD\week 05\RazorPagesMovie\RazorPagesMovie\Pages\Movies\Details.cshtml" WriteLiteral(Model.Movie.ID); #line default #line hidden __tagHelperStringValueBuffer = EndWriteTagHelperAttribute(); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"] = __tagHelperStringValueBuffer; __tagHelperExecutionContext.AddTagHelperAttribute("asp-route-id", __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"], global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(1366, 8, true); WriteLiteral(" |\r\n "); EndContext(); BeginContext(1374, 38, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "a8c7cb8c8b365cbf9d2845fc41e47874926481fe11010", async() => { BeginContext(1396, 12, true); WriteLiteral("Back to List"); EndContext(); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Page = (string)__tagHelperAttribute_1.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(1412, 10, true); WriteLiteral("\r\n</div>\r\n"); EndContext(); } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<RazorPagesMovie.Pages.Movies.DetailsModel> Html { get; private set; } public global::Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary<RazorPagesMovie.Pages.Movies.DetailsModel> ViewData => (global::Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary<RazorPagesMovie.Pages.Movies.DetailsModel>)PageContext?.ViewData; public RazorPagesMovie.Pages.Movies.DetailsModel Model => ViewData.Model; } } #pragma warning restore 1591
56.983051
298
0.679581
[ "MIT" ]
dodieboy/Np_class
SSD/week 05/RazorPagesMovie/RazorPagesMovie/obj/Debug/netcoreapp2.2/Razor/Pages/Movies/Details.cshtml.g.cs
13,448
C#
using System.Windows.Controls; namespace NuPattern.Authoring.PatternToolkit.Assets.Wizards.Pages { /// <summary> /// A custom wizard page that edits the properties of the current element. /// </summary> partial class ToolkitInfo : Page { /// <summary> /// Initializes a new instance of the <see cref="ToolkitInfo"/> class. /// </summary> public ToolkitInfo() { InitializeComponent(); } } }
26.388889
78
0.6
[ "Apache-2.0" ]
dbremner/nupattern
Src/Authoring/Source/Authoring.PatternToolkit/Assets/Wizards/Pages/ToolkitInfo.xaml.cs
477
C#