content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Microsoft.Azure.Commands.SecurityCenter.Models.SqlVulnerabilityAssessment { public class PSSqlVulnerabilityAssessmentQueryCheck { public string Query { get; set; } public string[][] ExpectedResult { get; set; } public string[] ColumnNames { get; set; } public override string ToString() { return string.Join(Environment.NewLine, $"{{", $"Query:", $"{Query}", $"Column Names:", $"{string.Join(", ", ColumnNames)}", $"Expected Results:", (ExpectedResult.Any() ? $"{string.Join(Environment.NewLine, ExpectedResult.Select(row => $"{{{string.Join(", ", row)}}}"))}" : "{}") + $"}}"); } } }
33.111111
151
0.536913
[ "MIT" ]
Agazoth/azure-powershell
src/Security/Security/Models/SqlVulnerabilityAssessment/PSSqlVulnerabilityAssessmentQueryCheck.cs
870
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; namespace x_IMU_GUI { /// <summary> /// ToggleButton class. /// </summary> public partial class ToggleButton : Button { /// <summary> /// Protected toggle state. /// </summary> protected bool toggleState; /// <summary> /// Protected prefix text used when toggle state is true. /// </summary> protected string truePrefixText; /// <summary> /// Protected prefix text used when toggle state is false. /// </summary> protected string falsePrefixText; /// <summary> /// Protected suffix text. /// </summary> protected string suffixText; /// <summary> /// Gets or sets the toggle state. /// </summary> public bool ToggleState { get { return toggleState; } set { toggleState = value; UpdateText(); } } /// <summary> /// Gets or sets the prefix text used when toggle state is true. /// </summary> public string TruePrefixText { get { return truePrefixText; } set { truePrefixText = value; UpdateText(); } } /// <summary> /// Gets or sets the prefix text used when toggle state is false. /// </summary> public string FalsePrefixText { get { return falsePrefixText; } set { falsePrefixText = value; UpdateText(); } } /// <summary> /// Gets or sets the suffix text. /// </summary> public string SuffixText { get { return suffixText; } set { suffixText = value; UpdateText(); } } /// <summary> /// Initialises a new instance of the <see cref="ToggleButton"/> class. /// </summary> public ToggleButton() { InitializeComponent(); toggleState = false; truePrefixText = "TruePrefixText"; falsePrefixText = "FalsePrefixText"; suffixText = "SuffixText"; UpdateText(); } /// <summary> /// Mouse click event toggles state and update text. /// </summary> protected override void OnClick(EventArgs e) { toggleState = !toggleState; UpdateText(); base.OnClick(e); } /// <summary> /// Updates the button text. /// </summary> public void UpdateText() { this.Text = (toggleState ? TruePrefixText : FalsePrefixText) + suffixText; } } }
24.992481
87
0.447353
[ "MIT" ]
juhnowski/xIMU
x-IMU GUI 12.3/x-IMU GUI/x-IMU GUI/CustomControls/ToggleButton.cs
3,326
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Gov.Jag.PillPressRegistry.Interfaces { using Microsoft.Rest; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// Certificateapprovedproductbulkdeletefailures operations. /// </summary> public partial class Certificateapprovedproductbulkdeletefailures : IServiceOperations<DynamicsClient>, ICertificateapprovedproductbulkdeletefailures { /// <summary> /// Initializes a new instance of the Certificateapprovedproductbulkdeletefailures class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public Certificateapprovedproductbulkdeletefailures(DynamicsClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the DynamicsClient /// </summary> public DynamicsClient Client { get; private set; } /// <summary> /// Get bcgov_certificateapprovedproduct_BulkDeleteFailures from /// bcgov_certificateapprovedproducts /// </summary> /// <param name='bcgovCertificateapprovedproductid'> /// key: bcgov_certificateapprovedproductid of bcgov_certificateapprovedproduct /// </param> /// <param name='top'> /// </param> /// <param name='skip'> /// </param> /// <param name='search'> /// </param> /// <param name='filter'> /// </param> /// <param name='count'> /// </param> /// <param name='orderby'> /// Order items by property values /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<MicrosoftDynamicsCRMbulkdeletefailureCollection>> GetWithHttpMessagesAsync(string bcgovCertificateapprovedproductid, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (bcgovCertificateapprovedproductid == null) { throw new ValidationException(ValidationRules.CannotBeNull, "bcgovCertificateapprovedproductid"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("bcgovCertificateapprovedproductid", bcgovCertificateapprovedproductid); tracingParameters.Add("top", top); tracingParameters.Add("skip", skip); tracingParameters.Add("search", search); tracingParameters.Add("filter", filter); tracingParameters.Add("count", count); tracingParameters.Add("orderby", orderby); tracingParameters.Add("select", select); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "bcgov_certificateapprovedproducts({bcgov_certificateapprovedproductid})/bcgov_certificateapprovedproduct_BulkDeleteFailures").ToString(); _url = _url.Replace("{bcgov_certificateapprovedproductid}", System.Uri.EscapeDataString(bcgovCertificateapprovedproductid)); List<string> _queryParameters = new List<string>(); if (top != null) { _queryParameters.Add(string.Format("$top={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(top, Client.SerializationSettings).Trim('"')))); } if (skip != null) { _queryParameters.Add(string.Format("$skip={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(skip, Client.SerializationSettings).Trim('"')))); } if (search != null) { _queryParameters.Add(string.Format("$search={0}", System.Uri.EscapeDataString(search))); } if (filter != null) { _queryParameters.Add(string.Format("$filter={0}", System.Uri.EscapeDataString(filter))); } if (count != null) { _queryParameters.Add(string.Format("$count={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(count, Client.SerializationSettings).Trim('"')))); } if (orderby != null) { _queryParameters.Add(string.Format("$orderby={0}", System.Uri.EscapeDataString(string.Join(",", orderby)))); } if (select != null) { _queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(string.Join(",", select)))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(string.Join(",", expand)))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<MicrosoftDynamicsCRMbulkdeletefailureCollection>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<MicrosoftDynamicsCRMbulkdeletefailureCollection>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get bcgov_certificateapprovedproduct_BulkDeleteFailures from /// bcgov_certificateapprovedproducts /// </summary> /// <param name='bcgovCertificateapprovedproductid'> /// key: bcgov_certificateapprovedproductid of bcgov_certificateapprovedproduct /// </param> /// <param name='bulkdeletefailureid'> /// key: bulkdeletefailureid of bulkdeletefailure /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<MicrosoftDynamicsCRMbulkdeletefailure>> BulkDeleteFailuresByKeyWithHttpMessagesAsync(string bcgovCertificateapprovedproductid, string bulkdeletefailureid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (bcgovCertificateapprovedproductid == null) { throw new ValidationException(ValidationRules.CannotBeNull, "bcgovCertificateapprovedproductid"); } if (bulkdeletefailureid == null) { throw new ValidationException(ValidationRules.CannotBeNull, "bulkdeletefailureid"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("bcgovCertificateapprovedproductid", bcgovCertificateapprovedproductid); tracingParameters.Add("bulkdeletefailureid", bulkdeletefailureid); tracingParameters.Add("select", select); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BulkDeleteFailuresByKey", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "bcgov_certificateapprovedproducts({bcgov_certificateapprovedproductid})/bcgov_certificateapprovedproduct_BulkDeleteFailures({bulkdeletefailureid})").ToString(); _url = _url.Replace("{bcgov_certificateapprovedproductid}", System.Uri.EscapeDataString(bcgovCertificateapprovedproductid)); _url = _url.Replace("{bulkdeletefailureid}", System.Uri.EscapeDataString(bulkdeletefailureid)); List<string> _queryParameters = new List<string>(); if (select != null) { _queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(string.Join(",", select)))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(string.Join(",", expand)))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<MicrosoftDynamicsCRMbulkdeletefailure>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<MicrosoftDynamicsCRMbulkdeletefailure>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
46.375291
576
0.58286
[ "Apache-2.0" ]
GeorgeWalker/jag-pill-press-registry
pill-press-interfaces/Dynamics-Autorest/Certificateapprovedproductbulkdeletefailures.cs
19,895
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class ObjectCreator { private static Dictionary<Vector3,GameObject> blocks = new Dictionary<Vector3,GameObject>(); public static void CreateObject(Vector3 position, string textureName){ CreateObject(position, textureName, Guid.NewGuid().ToString()); } public static void CreateObject(Vector3 position, string textureName, string name) { if(blocks.ContainsKey(position)) return; GameObject obj = new GameObject(); obj.name = name; obj.AddComponent<SpriteRenderer>(); obj.AddComponent<BoxCollider2D>(); obj.GetComponent<SpriteRenderer>().sprite = Resources.Load(textureName, typeof(Sprite)) as Sprite; obj.GetComponent<BoxCollider2D>().size = new Vector2(1,1); obj.transform.position = position; blocks.Add(position, obj); } public static void RemoveObject(Vector3 position) { foreach (Vector3 key in blocks.Keys) { if(position==key) { MonoBehaviour.Destroy(blocks[key]); blocks.Remove(key); } } } }
33.771429
106
0.664129
[ "MIT" ]
CrispyXYZ/Minecraft2D
Assets/Scripts/ObjectCreator.cs
1,182
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading.Tasks; using Data.Common.Domain; using Data.Common.Repository; using Xunit; namespace Data.MySql.Test { public class RepositoryTest : DbContextTest { private readonly IArticleRepository _articleRepository; public RepositoryTest() { _articleRepository = new ArticleRepository(DbContext); } [Fact] public async Task<ArticleEntity> AddTest() { var article = new ArticleEntity { Title = "ASP.NET Core", Body = "ASP.NET CoreASP.NET CoreASP.NET CoreASP.NET CoreASP.NET Core", MediaType = MediaType.Picture, CategoryId = CategoryId, CreatedTime = DateTime.Now }; var result = await _articleRepository.AddAsync(article); Assert.True(result); return article; } [Fact] public async Task BatchAddTest() { await AddTest(); var list = new List<ArticleEntity>(); for (int i = 0; i < 10000; i++) { var article = new ArticleEntity { Title = "ASP.NET Core", Body = "ASP.NET CoreASP.NET CoreASP.NET CoreASP.NET CoreASP.NET Core", MediaType = MediaType.Picture, CategoryId = CategoryId, CreatedTime = DateTime.Now }; list.Add(article); } var sw = new Stopwatch(); sw.Start(); await _articleRepository.AddAsync(list); sw.Stop(); var count = await _articleRepository.Count(); Assert.True(count == 10001); } [Fact] public async void DeleteTest() { var article = await AddTest(); var result = await _articleRepository.DeleteAsync(article.Id); Assert.True(result); } [Fact] public async void UpdateTest() { var article = await AddTest(); article.Title = "测试"; var result = await _articleRepository.UpdateAsync(article); Assert.True(result); } [Fact] public async void GetTest() { var article = await AddTest(); var result = await _articleRepository.GetAsync(article.Id); Assert.NotNull(result); Assert.Equal(result.Id, article.Id); } [Fact] public async void GetAllTest() { await BatchAddTest(); var list = await _articleRepository.GetAllAsync(); Assert.Equal(10001, list.Count); } [Fact] public async void SoftDeleteTest() { var article = await AddTest(); await _articleRepository.SoftDeleteAsync(article.Id); var article1 = await _articleRepository.GetAsync(article.Id); Assert.Null(article1); } } }
25.387097
90
0.526366
[ "MIT" ]
DoxMark/NetModular
test/Data/Data.MySql.Test/RepositoryTest.cs
3,154
C#
using System; using System.Collections.Generic; using WildFarm.Models; namespace WildFarm { class Program { static void Main(string[] args) { List<Animal> animals = new List<Animal>(); string input; while((input = Console.ReadLine()) != "End") { Animal animal = ParseAnimal(input); animals.Add(animal); string[] foodArgs = Console.ReadLine().Split(); Food food = ParseFood(foodArgs); Console.WriteLine(animal.MakeSound()); try { animal.TryEatFood(food); } catch(InvalidOperationException ioe) { Console.WriteLine(ioe.Message); } } foreach (Animal animal in animals) { Console.WriteLine(animal); } } private static Food ParseFood(string[] foodArgs) { string type = foodArgs[0]; int quantity = int.Parse(foodArgs[1]); switch (type) { case "Meat": return new Meat(quantity); case "Vegetable": return new Vegetable(quantity); case "Fruit": return new Fruit(quantity); case "Seeds": return new Seeds(quantity); default: throw new ArgumentException("Not a valid food type!"); } } private static Animal ParseAnimal(string input) { string[] animalArgs = input.Split(); string animalType = animalArgs[0]; string name = animalArgs[1]; double weight = double.Parse(animalArgs[2]); string dependantArg = animalArgs[3]; switch (animalType) { case "Cat": string catBreed = animalArgs[4]; return new Cat(name, weight, dependantArg, catBreed); case "Tiger": string tigerBreed = animalArgs[4]; return new Tiger(name, weight, dependantArg, tigerBreed); case "Dog": return new Dog(name, weight, dependantArg); case "Mouse": return new Mouse(name, weight, dependantArg); case "Owl": double owlWingSize = double.Parse(dependantArg); return new Owl(name, weight, owlWingSize); case "Hen": double henWingSize = double.Parse(dependantArg); return new Hen(name, weight, henWingSize); default: throw new ArgumentException("Not a valid animal type!"); } } } }
31.674157
81
0.485988
[ "MIT" ]
YonchevSimeon/CSharp-OOP-Basics
06.ExercisesPolymorphism/ExercisesPolymorphism/WildFarm/Program.cs
2,821
C#
using MaSch.Test; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; namespace MaSch.Core.UnitTests { [TestClass] public class DelegateDisposableEnumerableTests : TestClassBase { [TestMethod] public void Constructor_ParameterChecks() { _ = Assert.ThrowsException<ArgumentNullException>(() => new DelegateDisposableEnumerable<object>(null!, () => { }).Dispose()); _ = Assert.ThrowsException<ArgumentNullException>(() => new DelegateDisposableEnumerable<object>(Array.Empty<object>(), null!).Dispose()); } [TestMethod] [SuppressMessage("IDisposableAnalyzers.Correctness", "IDISP001:Dispose created.", Justification = "Would fail the test")] public void GetEnumerator_Generic() { var actionMock = new Mock<Action>(); var enumeratorMock = new Mock<IEnumerator<string>>(MockBehavior.Strict); var enumerableMock = new Mock<IEnumerable<string>>(MockBehavior.Strict); _ = enumerableMock.Setup(x => x.GetEnumerator()).Returns(enumeratorMock.Object); var dde = new DelegateDisposableEnumerable<string>(enumerableMock.Object, actionMock.Object); var result = dde.GetEnumerator(); Assert.AreSame(enumeratorMock.Object, result); enumerableMock.Verify(x => x.GetEnumerator(), Times.Once()); actionMock.Verify(x => x(), Times.Never()); } [TestMethod] public void GetEnumerator_NonGeneric() { var actionMock = new Mock<Action>(); var enumeratorMock = new Mock<IEnumerator>(MockBehavior.Strict); var enumerableMock = new Mock<IEnumerable<string>>(MockBehavior.Strict); _ = enumerableMock.As<IEnumerable>().Setup(x => x.GetEnumerator()).Returns(enumeratorMock.Object); using var dde = new DelegateDisposableEnumerable<string>(enumerableMock.Object, actionMock.Object); var result = ((IEnumerable)dde).GetEnumerator(); Assert.AreSame(enumeratorMock.Object, result); enumerableMock.As<IEnumerable>().Verify(x => x.GetEnumerator(), Times.Once()); actionMock.Verify(x => x(), Times.Never()); } [TestMethod] [SuppressMessage("IDisposableAnalyzers.Correctness", "IDISP017:Prefer using.", Justification = "Makes sense here")] [SuppressMessage("IDisposableAnalyzers.Correctness", "IDISP016:Don't use disposed instance.", Justification = "False positive.")] public void Dispose_() { var disposingMock = new Mock<EventHandler<DisposeEventArgs>>(); var disposedMock = new Mock<EventHandler<DisposeEventArgs>>(); var actionMock = new Mock<Action>(); var enumerableMock = new Mock<IEnumerable<string>>(MockBehavior.Strict); _ = disposingMock.Setup(x => x(It.IsAny<object?>(), It.IsAny<DisposeEventArgs>())) .Callback(() => { actionMock.Verify(x => x(), Times.Never()); disposedMock.Verify(x => x(It.IsAny<object?>(), It.IsAny<DisposeEventArgs>()), Times.Never()); }); _ = actionMock.Setup(x => x()) .Callback(() => { disposingMock.Verify(x => x(It.IsAny<object?>(), It.IsAny<DisposeEventArgs>()), Times.Once()); disposedMock.Verify(x => x(It.IsAny<object?>(), It.IsAny<DisposeEventArgs>()), Times.Never()); }); _ = disposedMock.Setup(x => x(It.IsAny<object?>(), It.IsAny<DisposeEventArgs>())) .Callback(() => { actionMock.Verify(x => x(), Times.Once()); disposedMock.Verify(x => x(It.IsAny<object?>(), It.IsAny<DisposeEventArgs>()), Times.Once()); }); void Act() { var dde = new DelegateDisposableEnumerable<string>(enumerableMock.Object, actionMock.Object); dde.Disposing += disposingMock.Object; dde.Disposed += disposedMock.Object; dde.Dispose(); actionMock.Verify(x => x(), Times.Once()); disposingMock.Verify(x => x(dde, It.Is<DisposeEventArgs>(a => a != null && a.IsDisposing)), Times.Once()); disposedMock.Verify(x => x(dde, It.Is<DisposeEventArgs>(a => a != null && a.IsDisposing)), Times.Once()); } Act(); GC.Collect(0, GCCollectionMode.Forced); GC.WaitForPendingFinalizers(); // Verify that after dispose no other events are executed. actionMock.Verify(x => x(), Times.Once()); disposingMock.Verify(x => x(It.IsAny<DelegateDisposableEnumerable<string>>(), It.IsAny<DisposeEventArgs>()), Times.Once()); disposedMock.Verify(x => x(It.IsAny<DelegateDisposableEnumerable<string>>(), It.IsAny<DisposeEventArgs>()), Times.Once()); } [TestMethod] [SuppressMessage("IDisposableAnalyzers.Correctness", "IDISP001:Dispose created.", Justification = "Would fail the test")] public void Finalizer() { var disposingMock = new Mock<EventHandler<DisposeEventArgs>>(); var disposedMock = new Mock<EventHandler<DisposeEventArgs>>(); var actionMock = new Mock<Action>(); var enumerableMock = new Mock<IEnumerable<string>>(MockBehavior.Strict); int ddeHash = 0; void Act() { var dde = new DelegateDisposableEnumerable<string>(enumerableMock.Object, actionMock.Object); dde.Disposing += disposingMock.Object; dde.Disposed += disposedMock.Object; ddeHash = dde.GetHashCode(); } Act(); GC.Collect(0, GCCollectionMode.Forced); GC.WaitForPendingFinalizers(); actionMock.Verify(x => x(), Times.Never()); } } [TestClass] public class DelegateOrderedDisposableEnumerableTests { [TestMethod] public void Constructor_ParameterChecks() { var enumerableMock = new Mock<IOrderedEnumerable<object>>(MockBehavior.Strict); _ = Assert.ThrowsException<ArgumentNullException>(() => new DelegateOrderedDisposableEnumerable<object>(null!, () => { }).Dispose()); _ = Assert.ThrowsException<ArgumentNullException>(() => new DelegateOrderedDisposableEnumerable<object>(enumerableMock.Object, null!).Dispose()); } [TestMethod] public void CreateOrderedEnumerable() { var actionMock = new Mock<Action>(); var keySelectorMock = new Mock<Func<string, int>>(); var comparerMock = new Mock<IComparer<int>>(MockBehavior.Strict); var resultEnumerableMock = new Mock<IOrderedEnumerable<string>>(MockBehavior.Strict); var enumerableMock = new Mock<IOrderedEnumerable<string>>(MockBehavior.Strict); _ = enumerableMock.Setup(x => x.CreateOrderedEnumerable(It.IsAny<Func<string, int>>(), It.IsAny<IComparer<int>>(), It.IsAny<bool>())).Returns(resultEnumerableMock.Object); using var dde = new DelegateOrderedDisposableEnumerable<string>(enumerableMock.Object, actionMock.Object); var result = dde.CreateOrderedEnumerable(keySelectorMock.Object, comparerMock.Object, true); Assert.AreSame(resultEnumerableMock.Object, result); enumerableMock.Verify(x => x.CreateOrderedEnumerable(keySelectorMock.Object, comparerMock.Object, true), Times.Once()); actionMock.Verify(x => x(), Times.Never()); } [TestMethod] [SuppressMessage("IDisposableAnalyzers.Correctness", "IDISP001:Dispose created.", Justification = "Would fail the test")] public void GetEnumerator_Generic() { var actionMock = new Mock<Action>(); var enumeratorMock = new Mock<IEnumerator<string>>(MockBehavior.Strict); var enumerableMock = new Mock<IOrderedEnumerable<string>>(MockBehavior.Strict); _ = enumerableMock.Setup(x => x.GetEnumerator()).Returns(enumeratorMock.Object); var dde = new DelegateOrderedDisposableEnumerable<string>(enumerableMock.Object, actionMock.Object); var result = dde.GetEnumerator(); Assert.AreSame(enumeratorMock.Object, result); enumerableMock.Verify(x => x.GetEnumerator(), Times.Once()); actionMock.Verify(x => x(), Times.Never()); } [TestMethod] public void GetEnumerator_NonGeneric() { var actionMock = new Mock<Action>(); var enumeratorMock = new Mock<IEnumerator>(MockBehavior.Strict); var enumerableMock = new Mock<IOrderedEnumerable<string>>(MockBehavior.Strict); _ = enumerableMock.As<IEnumerable>().Setup(x => x.GetEnumerator()).Returns(enumeratorMock.Object); using var dde = new DelegateOrderedDisposableEnumerable<string>(enumerableMock.Object, actionMock.Object); var result = ((IEnumerable)dde).GetEnumerator(); Assert.AreSame(enumeratorMock.Object, result); enumerableMock.As<IEnumerable>().Verify(x => x.GetEnumerator(), Times.Once()); actionMock.Verify(x => x(), Times.Never()); } [TestMethod] [SuppressMessage("IDisposableAnalyzers.Correctness", "IDISP017:Prefer using.", Justification = "Makes sense here")] [SuppressMessage("IDisposableAnalyzers.Correctness", "IDISP016:Don't use disposed instance.", Justification = "False positive.")] public void Dispose_() { var disposingMock = new Mock<EventHandler<DisposeEventArgs>>(); var disposedMock = new Mock<EventHandler<DisposeEventArgs>>(); var actionMock = new Mock<Action>(); var enumerableMock = new Mock<IOrderedEnumerable<string>>(MockBehavior.Strict); _ = disposingMock.Setup(x => x(It.IsAny<object?>(), It.IsAny<DisposeEventArgs>())) .Callback(() => { actionMock.Verify(x => x(), Times.Never()); disposedMock.Verify(x => x(It.IsAny<object?>(), It.IsAny<DisposeEventArgs>()), Times.Never()); }); _ = actionMock.Setup(x => x()) .Callback(() => { disposingMock.Verify(x => x(It.IsAny<object?>(), It.IsAny<DisposeEventArgs>()), Times.Once()); disposedMock.Verify(x => x(It.IsAny<object?>(), It.IsAny<DisposeEventArgs>()), Times.Never()); }); _ = disposedMock.Setup(x => x(It.IsAny<object?>(), It.IsAny<DisposeEventArgs>())) .Callback(() => { actionMock.Verify(x => x(), Times.Once()); disposedMock.Verify(x => x(It.IsAny<object?>(), It.IsAny<DisposeEventArgs>()), Times.Once()); }); void Act() { var dde = new DelegateOrderedDisposableEnumerable<string>(enumerableMock.Object, actionMock.Object); dde.Disposing += disposingMock.Object; dde.Disposed += disposedMock.Object; dde.Dispose(); actionMock.Verify(x => x(), Times.Once()); disposingMock.Verify(x => x(dde, It.Is<DisposeEventArgs>(a => a != null && a.IsDisposing)), Times.Once()); disposedMock.Verify(x => x(dde, It.Is<DisposeEventArgs>(a => a != null && a.IsDisposing)), Times.Once()); } Act(); GC.Collect(0, GCCollectionMode.Forced); GC.WaitForPendingFinalizers(); // Verify that after dispose no other events are executed. actionMock.Verify(x => x(), Times.Once()); disposingMock.Verify(x => x(It.IsAny<DelegateOrderedDisposableEnumerable<string>>(), It.IsAny<DisposeEventArgs>()), Times.Once()); disposedMock.Verify(x => x(It.IsAny<DelegateOrderedDisposableEnumerable<string>>(), It.IsAny<DisposeEventArgs>()), Times.Once()); } [TestMethod] [SuppressMessage("IDisposableAnalyzers.Correctness", "IDISP001:Dispose created.", Justification = "Would fail the test")] public void Finalizer() { var disposingMock = new Mock<EventHandler<DisposeEventArgs>>(); var disposedMock = new Mock<EventHandler<DisposeEventArgs>>(); var actionMock = new Mock<Action>(); var enumerableMock = new Mock<IOrderedEnumerable<string>>(MockBehavior.Strict); int ddeHash = 0; void Act() { var dde = new DelegateOrderedDisposableEnumerable<string>(enumerableMock.Object, actionMock.Object); dde.Disposing += disposingMock.Object; dde.Disposed += disposedMock.Object; ddeHash = dde.GetHashCode(); } Act(); GC.Collect(0, GCCollectionMode.Forced); GC.WaitForPendingFinalizers(); actionMock.Verify(x => x(), Times.Never()); } } }
48.299639
183
0.603334
[ "MIT" ]
MaSch0212/MaSch
test/Core.UnitTests/DelegateDisposableEnumerableTests.cs
13,381
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: Templates\CSharp\Model\EnumType.cs.tt namespace Microsoft.Graph { using Newtonsoft.Json; /// <summary> /// The enum PlannerPreviewType. /// </summary> [JsonConverter(typeof(EnumConverter))] public enum PlannerPreviewType { /// <summary> /// Automatic /// </summary> Automatic = 0, /// <summary> /// No Preview /// </summary> NoPreview = 1, /// <summary> /// Checklist /// </summary> Checklist = 2, /// <summary> /// Description /// </summary> Description = 3, /// <summary> /// Reference /// </summary> Reference = 4, } }
24
153
0.467687
[ "MIT" ]
OfficeGlobal/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Models/Generated/PlannerPreviewType.cs
1,176
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using EPBLab.ViewModel; using GalaSoft.MvvmLight.Messaging; namespace EPBLab.Messages { public class CloseBlueprintMessage : GenericMessage<BlueprintViewModel> { public CloseBlueprintMessage(BlueprintViewModel vm) : base(vm) { } } }
21.5
75
0.739018
[ "MIT" ]
ApanLoon/EmpyrionStuff
src/epb/EPBLab/Messages/CloseBlueprintMessage.cs
389
C#
using Newtonsoft.Json; namespace Dracoon.Sdk.SdkInternal.ApiModel { internal class ApiActiveDirectory { [JsonProperty("id", NullValueHandling = NullValueHandling.Ignore)] public int Id { get; set; } [JsonProperty("alias", NullValueHandling = NullValueHandling.Ignore)] public string Alias { get; set; } [JsonProperty("name", NullValueHandling = NullValueHandling.Ignore)] public string Name { get; set; } [JsonProperty("isGlobalAvailable", NullValueHandling = NullValueHandling.Ignore)] public bool IsGlobalAvailable { get; set; } } }
32.263158
89
0.683524
[ "Apache-2.0" ]
DAVISOL-GmbH/dracoon-csharp-sdk
DracoonSdk/SdkInternal/ApiModel/Settings/ApiActiveDirectory.cs
615
C#
using System; using NetRuntimeSystem = System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.ComponentModel; using System.Reflection; using System.Collections.Generic; using System.Collections; using NetOffice; namespace NetOffice.AccessApi { ///<summary> /// DispatchInterface Operations /// SupportByVersion Access, 14,15,16 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff192091.aspx ///</summary> [SupportByVersionAttribute("Access", 14,15,16)] [EntityTypeAttribute(EntityType.IsDispatchInterface)] public class Operations : COMObject ,IEnumerable<NetOffice.AccessApi.Operation> { #pragma warning disable #region Type Information private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(Operations); return _type; } } #endregion #region Construction ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> public Operations(Core factory, COMObject parentObject, object comProxy) : base(factory, parentObject, comProxy) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Operations(COMObject parentObject, object comProxy) : base(parentObject, comProxy) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Operations(Core factory, COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Operations(COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType) { } ///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Operations(COMObject replacedObject) : base(replacedObject) { } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Operations() : base() { } /// <param name="progId">registered ProgID</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Operations(string progId) : base(progId) { } #endregion #region Properties /// <summary> /// SupportByVersion Access 14, 15, 16 /// Get /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff192074.aspx /// Unknown COM Proxy /// </summary> [SupportByVersionAttribute("Access", 14,15,16)] public object Parent { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Parent", paramsArray); COMObject newObject = Factory.CreateObjectFromComProxy(this,returnItem); return newObject; } } /// <summary> /// SupportByVersion Access 14, 15, 16 /// Get /// </summary> /// <param name="index">object Index</param> [SupportByVersionAttribute("Access", 14,15,16)] [NetRuntimeSystem.Runtime.CompilerServices.IndexerName("Item")] public NetOffice.AccessApi.Operation this[object index] { get { object[] paramsArray = Invoker.ValidateParamsArray(index); object returnItem = Invoker.PropertyGet(this, "Item", paramsArray); NetOffice.AccessApi.Operation newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.AccessApi.Operation.LateBindingApiWrapperType) as NetOffice.AccessApi.Operation; return newObject; } } /// <summary> /// SupportByVersion Access 14, 15, 16 /// Get /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff845768.aspx /// </summary> [SupportByVersionAttribute("Access", 14,15,16)] public Int32 Count { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Count", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } } #endregion #region Methods /// <summary> /// SupportByVersion Access 14, 15, 16 /// /// </summary> /// <param name="dispid">Int32 dispid</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] [SupportByVersionAttribute("Access", 14,15,16)] public bool IsMemberSafe(Int32 dispid) { object[] paramsArray = Invoker.ValidateParamsArray(dispid); object returnItem = Invoker.MethodReturn(this, "IsMemberSafe", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } #endregion #region IEnumerable<NetOffice.AccessApi.Operation> Member /// <summary> /// SupportByVersionAttribute Access, 14,15,16 /// </summary> [SupportByVersionAttribute("Access", 14,15,16)] public IEnumerator<NetOffice.AccessApi.Operation> GetEnumerator() { NetRuntimeSystem.Collections.IEnumerable innerEnumerator = (this as NetRuntimeSystem.Collections.IEnumerable); foreach (NetOffice.AccessApi.Operation item in innerEnumerator) yield return item; } #endregion #region IEnumerable Members /// <summary> /// SupportByVersionAttribute Access, 14,15,16 /// </summary> [SupportByVersionAttribute("Access", 14,15,16)] IEnumerator NetRuntimeSystem.Collections.IEnumerable.GetEnumerator() { return NetOffice.Utils.GetProxyEnumeratorAsMethod(this); } #endregion #pragma warning restore } }
32.695431
189
0.701133
[ "MIT" ]
Engineerumair/NetOffice
Source/Access/DispatchInterfaces/Operations.cs
6,443
C#
using Newtonsoft.Json; using System; using System.Collections.Generic; namespace WebVella.Erp.Web.Models { public class PageBodyNode { [JsonProperty("id")] public Guid Id { get; set; } [JsonProperty("parent_id")] public Guid? ParentId { get; set; } [JsonProperty("page_id")] public Guid PageId { get; set; } //Could be used from a component that has embedded layout nodes. //In most cases null. If node has Id it should not be allowed to be removed from the Page Designer Layout by the user [JsonProperty("node_id")] public Guid? NodeId { get; set; } = null; [JsonProperty("container_id")] public string ContainerId { get; set; } = Guid.Empty.ToString(); [JsonProperty("weight")] public int Weight { get; set; } = 1; [JsonProperty("component_name")] public string ComponentName { get; set; } = ""; [JsonProperty("options")] public string Options { get; set; } = ""; //Json of the specific configuration selected from the user for this page [JsonProperty("nodes")] public List<PageBodyNode> Nodes { get; set; } = new List<PageBodyNode>(); } }
28.179487
119
0.687898
[ "Apache-2.0" ]
628426/WebVella-ERP
WebVella.Erp.Web/Models/PageBodyNode.cs
1,101
C#
using MarketingBox.Affiliate.Service.Domain.Models.Brands; using MyNoSqlServer.Abstractions; namespace MarketingBox.Affiliate.Service.MyNoSql.Brands { public class BrandNoSql : MyNoSqlDbEntity { public const string TableName = "marketingbox-affiliateservice-brands"; public static string GeneratePartitionKey(string tenantId) => $"{tenantId}"; public static string GenerateRowKey(long brandId) => $"{brandId}"; public BrandMessage Brand { get; set; } public static BrandNoSql Create(BrandMessage brandMessage) => new() { PartitionKey = GeneratePartitionKey(brandMessage.TenantId), RowKey = GenerateRowKey(brandMessage.Id), Brand = brandMessage }; } }
35.909091
84
0.663291
[ "MIT" ]
MyJetMarketingBox/MarketingBox.Affiliate.Service
src/MarketingBox.Affiliate.Service.MyNoSql/Brands/BrandNoSql.cs
792
C#
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace Compact { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { } }
17.833333
42
0.700935
[ "MPL-2.0" ]
gitter-badger/compact-1
Compact/Compact.xaml.cs
323
C#
///////////////////////////////////////////////// // // FIX Client // // Copyright @ 2021 VIRTU Financial Inc. // All rights reserved. // // Filename: Program.cs // Author: Gary Hughes // ///////////////////////////////////////////////// using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; using System.IO; namespace FixPerformanceTest { class Program { delegate void ActionDelegate(); static void TimeOperation(ActionDelegate action, string label) { var stopwatch = new Stopwatch(); stopwatch.Start(); action(); stopwatch.Stop(); Console.WriteLine("{0} - {1}", stopwatch.Elapsed, label); } static void Main() { TimeOperation(TestMessageFieldAccess, "Message Field Access"); TimeOperation(TestReadHistoryFile, "Read History File"); } static void TestMessageFieldAccess() { byte[] data = Encoding.ASCII.GetBytes("8=FIX.4.09=28635=849=ITGHK56=KODIAK_KASFQA34=163357=kasfqa52=20091023-05:40:1637=712-217=420=039=055=649707154=238=100000032=031=0.00000014=06=0.00000011=296.2.240=160=20091023-05:40:1659=047=A30=DMA15=KRW6005=ALT=18500TOT=1256276416111=09886=0.0000009887=09912=09911=010=135"); var message = new Fix.Message(data); int[] tags = new int[message.Fields.Count]; for (int index = 0; index < tags.Length; ++index) { tags[index] = message.Fields[index].Tag; } Console.WriteLine("length = {0}", tags.Length); var random = new Random(); for (int i = 0; i < 100000; ++i) { int tag = tags[random.Next(tags.Length)]; _ = message.Fields.Find(tag); } } static void TestReadHistoryFile() { const string filename = @"C:\Users\geh\Downloads\Latha\FIX_ExchangeSimulator20150113.history"; var messages = new Fix.MessageCollection(); try { long count = 0; long exceptions = 0; using (var stream = new FileStream(filename, FileMode.Open)) using (var reader = new Fix.Reader(stream)) { for (; ; ) { try { Fix.Message? message = reader.ReadLine(); if (message == null) break; messages.Add(message); } catch (Exception) { ++exceptions; reader.DiscardLine(); continue; } ++count; } } Console.WriteLine("{0} / {1}", count, exceptions); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.WriteLine("MESSAGES - {0}", messages.Count); var book = new Fix.OrderBook(); try { foreach (var message in messages) { book.Process(message); } } catch (Exception ex) { Console.WriteLine(ex); } Console.WriteLine("ORDERS - {0}", book.Orders.Count); } } }
31.891667
363
0.444735
[ "Apache-2.0" ]
epronk/FixClient
FixPerformanceTest/Program.cs
3,829
C#
protected void btnUpload_Click(object sender, EventArgs e) { string fileName = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName); FileUpload1.PostedFile.SaveAs(Server.MapPath("/Uploads/" + fileName)); } //http://pt.stackoverflow.com/q/15721/101
37.714286
82
0.765152
[ "MIT" ]
Everton75/estudo
CSharp/ASP.NET/CaminhoArquivoCliente.cs
264
C#
using MySql.Data.MySqlClient; using Proyecto.AccesoDatos.Interface; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProyectoWeb.AccesoDatos.Conection { public class Datos : Connection, IDatos { //Realizar operaciones en la base de datos public bool OperarDatos(string sql) { try { MySqlCommand comando = new MySqlCommand(sql, Conectar()); if (comando.ExecuteNonQuery() > 0) { Desconector(); return true; } return false; } catch { return false; } } //Realizar consulta en la base de datos. public DataTable ConsultarDatos(string sql) { DataTable datos = new DataTable(); try { MySqlDataAdapter da = new MySqlDataAdapter(sql, Conectar()); da.Fill(datos); Desconector(); return datos; } catch { return null; } } } }
20.72
68
0.59749
[ "MIT" ]
MitchAguilar/AlbergueUniamazonia
ProyectoFinal/ProyectoFinal/AccesoDatos/Conection/Datos.cs
1,038
C#
using System; using System.IO; using System.Net.Sockets; using System.Reflection; using System.Text; using System.Threading.Tasks; using SIS.HTTP.Common; using SIS.HTTP.Cookies; using SIS.HTTP.Enums; using SIS.HTTP.Exceptions; using SIS.HTTP.Requests; using SIS.HTTP.Responses; using SIS.HTTP.Sessions; using SIS.MvcFramework.Result; using SIS.WebServer.Routing; using SIS.WebServer.Sessions; namespace SIS.WebServer { public class ConnectionHandler { private readonly Socket client; private readonly IServerRoutingTable serverRoutingTable; public ConnectionHandler(Socket client, IServerRoutingTable serverRoutingTable) { CoreValidator.ThrowIfNull(client, nameof(client)); CoreValidator.ThrowIfNull(serverRoutingTable, nameof(serverRoutingTable)); this.client = client; this.serverRoutingTable = serverRoutingTable; } private async Task<IHttpRequest> ReadRequestAsync() { // PARSE REQUEST FROM BYTE DATA var result = new StringBuilder(); var data = new ArraySegment<byte>(new byte[1024]); while (true) { int numberOfBytesToRead = await this.client.ReceiveAsync(data, SocketFlags.None); if (numberOfBytesToRead == 0) { break; } var bytesAsString = Encoding.UTF8.GetString(data.Array, 0, numberOfBytesToRead); result.Append(bytesAsString); if (numberOfBytesToRead < 1023) { break; } } if (result.Length == 0) { return null; } return new HttpRequest(result.ToString()); } private IHttpResponse ReturnIfResource(IHttpRequest httpRequest) { string folderPrefix = "/../"; string assemblyLocation = Assembly.GetExecutingAssembly().Location; string resourceFolderPath = "Resources/"; string requestedResource = httpRequest.Path; string fullPathToResource = assemblyLocation + folderPrefix + resourceFolderPath + requestedResource; if (File.Exists(fullPathToResource)) { byte[] content = File.ReadAllBytes(fullPathToResource); return new InlineResourceResult(content, HttpResponseStatusCode.Ok); } else { return new TextResult($"Route with method {httpRequest.RequestMethod} and path \"{httpRequest.Path}\" not found.", HttpResponseStatusCode.NotFound); } } private IHttpResponse HandleRequest(IHttpRequest httpRequest) { // EXECUTE FUNCTION FOR CURRENT REQUEST -> RETURNS RESPONSE if (!this.serverRoutingTable.Contains(httpRequest.RequestMethod, httpRequest.Path)) { return this.ReturnIfResource(httpRequest); } return this.serverRoutingTable.Get(httpRequest.RequestMethod, httpRequest.Path).Invoke(httpRequest); } private string SetRequestSession(IHttpRequest httpRequest) { if (httpRequest.Cookies.ContainsCookie(HttpSessionStorage.SessionCookieKey)) { var cookie = httpRequest .Cookies .GetCookie(HttpSessionStorage.SessionCookieKey); string sessionId = cookie.Value; if (HttpSessionStorage.ContainsSession(sessionId)) { httpRequest.Session = HttpSessionStorage.GetSession(sessionId); } } if (httpRequest.Session == null) { string sessionId = Guid.NewGuid().ToString(); httpRequest.Session = HttpSessionStorage.GetSession(sessionId); } return httpRequest.Session?.Id; } private void SetResponseSession(IHttpResponse httpResponse, string sessionId) { IHttpSession responseSession = HttpSessionStorage.GetSession(sessionId); if (responseSession.IsNew) { responseSession.IsNew = false; httpResponse.AddCookie(new HttpCookie(HttpSessionStorage.SessionCookieKey, responseSession.Id)); } } private void PrepareResponse(IHttpResponse httpResponse) { // PREPARES RESPONSE -> MAPS IT TO BYTE DATA byte[] byteSegments = httpResponse.GetBytes(); this.client.Send(byteSegments, SocketFlags.None); } public async Task ProcessRequestAsync() { IHttpResponse httpResponse = null; try { IHttpRequest httpRequest = await this.ReadRequestAsync(); if (httpRequest != null) { Console.WriteLine($"Processing: {httpRequest.RequestMethod} {httpRequest.Path}..."); string sessionId = this.SetRequestSession(httpRequest); httpResponse = this.HandleRequest(httpRequest); this.SetResponseSession(httpResponse, sessionId); } } catch (BadRequestException e) { httpResponse = new TextResult(e.Message, HttpResponseStatusCode.BadRequest); } catch (Exception e) { httpResponse = new TextResult(e.Message, HttpResponseStatusCode.InternalServerError); } this.PrepareResponse(httpResponse); this.client.Shutdown(SocketShutdown.Both); } } }
32.965714
164
0.588664
[ "MIT" ]
MrPIvanov/SoftUni
16-C# Web Basics/12_EXERCISE MVC INTRODUCTION/BasicServerServicesAndActionResult/SIS.WebServer/ConnectionHandler.cs
5,771
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 TestViewModelHelper.Properties { 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", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// 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("TestViewModelHelper.Properties.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; } } } }
43.765625
185
0.615494
[ "MIT" ]
Steve-Hunt/ViewModelHelper
TestViewModelHelper/Properties/Resources.Designer.cs
2,803
C#
using AutoMapper; using Microsoft.AspNetCore.Mvc; using NarojayBlog.Manager.Entiy; using NarojayBlog.Manager.IManager; using NarojayBlog.ViewModel; namespace NarojayBlog.Webapi.Controllers { public class CatalogController : BaseController { private readonly ICatalogManager _catalogManager; public CatalogController(IMapper mapper, ICatalogManager catalogManager) : base(mapper) { _catalogManager = catalogManager; } [HttpPost] public IActionResult AddCatalog(CatalogAddViewModel catalogAddViewModel) { var result = _catalogManager.AddCatalog(Mapper.Map<CatalogEntity>(catalogAddViewModel)); if (!result) { return BadRequest("插入失败"); } return Ok(); } [HttpGet] public IActionResult GetCatalogs() { var catalogEntities = _catalogManager.GetCatalogs(); return Ok(catalogEntities); } } }
28.027778
100
0.638256
[ "MIT" ]
hjsjy/NarojayBlog
NarojayBlog.Webapi/Controllers/CatalogController.cs
1,019
C#
using System; using System.Collections.Concurrent; using System.ComponentModel; namespace DataLinq.Extensions { internal static class TypeExtensions { private static readonly ConcurrentDictionary<Type, Type> nullableTypes = new ConcurrentDictionary<Type, Type>(); internal static Type GetNullableConversionType(this Type returnType) { if (returnType.IsGenericType && returnType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) { if (!nullableTypes.TryGetValue(returnType, out Type nullableType)) { nullableType = new NullableConverter(returnType).UnderlyingType; nullableTypes.TryAdd(returnType, nullableType); } return nullableType; } return returnType; } } }
32.111111
120
0.630911
[ "MIT" ]
bazer/DataLinq
src/DataLinq/Extensions/TypeExtensions.cs
869
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Microsoft.Azure.Management.ResourceManager.Fluent.Authentication; using Microsoft.Rest; using Microsoft.Rest.TransientFaultHandling; using System.Net.Http; namespace Microsoft.Azure.Management.ResourceManager.Fluent.Core { public class AzureConfigurable<T> : IAzureConfigurable<T> where T : class, IAzureConfigurable<T> { private RestClient.RestClientBuilder.IBuildable restClientBuilder; protected AzureConfigurable() { restClientBuilder = RestClient .Configure() .WithEnvironment(AzureEnvironment.AzureGlobalCloud); } public T WithDelegatingHandler(DelegatingHandler delegatingHandler) { restClientBuilder.WithDelegatingHandler(delegatingHandler); return this as T; } public T WithDelegatingHandlers(params DelegatingHandler[] delegatingHandlers) { restClientBuilder.WithDelegatingHandlers(delegatingHandlers); return this as T; } public T WithLogLevel(HttpLoggingDelegatingHandler.Level level) { restClientBuilder.WithLogLevel(level); return this as T; } public T WithRetryPolicy(RetryPolicy retryPolicy) { restClientBuilder.WithRetryPolicy(retryPolicy); return this as T; } public T WithUserAgent(string product, string version) { restClientBuilder.WithUserAgent(product, version); return this as T; } public T WithHttpClient(HttpClient httpClient) { restClientBuilder.WithHttpClient(httpClient); return this as T; } protected RestClient BuildRestClient(AzureCredentials credentials) { return restClientBuilder .WithCredentials(credentials) .WithEnvironment(credentials.Environment) .WithDelegatingHandler(new ProviderRegistrationDelegatingHandler(credentials)) .Build(); } } }
32.926471
95
0.65431
[ "MIT" ]
Azure/azure-libraries-for-net
src/ResourceManagement/ResourceManager/Core/AzureConfigurable.cs
2,241
C#
// **************************************************************** // Copyright 2007, Charlie Poole // This is free software licensed under the NUnit license. You may // obtain a copy of the license at http://nunit.org/?p=license&r=2.4 // **************************************************************** using System.Diagnostics; using System.IO; using NUnit.Core; using NUnit.Core.Tests; using NUnit.Framework; namespace NUnit.Util.Tests { /// <summary> /// Summary description for ProcessRunnerTests. /// </summary> // TODO: Reinstate after release is complete //[TestFixture, Explicit] public class ProcessRunnerTests : BasicRunnerTests { private ProcessRunner myRunner; protected override TestRunner CreateRunner( int runnerID ) { myRunner = new ProcessRunner( runnerID ); myRunner.Start(); return myRunner; } [TearDown] public void StopServer() { if ( myRunner != null ) myRunner.Stop(); } [TestFixtureSetUp] public void CheckServerAvailable() { Assert.IsTrue( File.Exists( "nunit-server.exe" ), "Can't find server" ); } [Test] public void CreatedRunnerInSeparateProcess() { Assert.AreNotEqual( Process.GetCurrentProcess().Id, myRunner.Process.Id, "Runner is in same process" ); } } }
24.307692
76
0.63212
[ "Apache-2.0" ]
SvenPeldszus/conqat
org.conqat.engine.dotnet/test-data/org.conqat.engine.dotnet.scope/NUnit_Folder/ClientUtilities/tests/ProcessRunnerTests.cs
1,264
C#
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.HealthVault.RestApi.Generated.Models { using Microsoft.HealthVault; using Microsoft.HealthVault.RestApi; using Microsoft.HealthVault.RestApi.Generated; using Newtonsoft.Json; using System.Linq; public partial class SafeWaitHandle { /// <summary> /// Initializes a new instance of the SafeWaitHandle class. /// </summary> public SafeWaitHandle() { CustomInit(); } /// <summary> /// Initializes a new instance of the SafeWaitHandle class. /// </summary> public SafeWaitHandle(bool? isInvalid = default(bool?), bool? isClosed = default(bool?)) { IsInvalid = isInvalid; IsClosed = isClosed; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// </summary> [JsonProperty(PropertyName = "isInvalid")] public bool? IsInvalid { get; private set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "isClosed")] public bool? IsClosed { get; private set; } } }
28.6
96
0.597902
[ "MIT" ]
Bhaskers-Blu-Org2/healthvault-dotnetstandard-sdk
Microsoft.HealthVault.RestApi/Generated/Models/SafeWaitHandle.cs
1,430
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; using System.Collections.ObjectModel; using System.Management.Automation.Internal; using System.Management.Automation.Security; using System.Management.Automation.Tracing; using System.Threading; using Dbg = System.Management.Automation.Diagnostics; using PSHost = System.Management.Automation.Host.PSHost; namespace System.Management.Automation.Runspaces.Internal { /// <summary> /// Class which supports pooling local powerShell runspaces. /// </summary> internal class RunspacePoolInternal { #region Private data protected int maxPoolSz; protected int minPoolSz; // we need total active runspaces to avoid lock() statements everywhere protected int totalRunspaces; protected List<Runspace> runspaceList = new List<Runspace>(); // info of all the runspaces in the pool. protected Stack<Runspace> pool; // stack of runspaces that are available. protected Queue<GetRunspaceAsyncResult> runspaceRequestQueue; // request queue. // let requesters request on the runspaceRequestQueue..internally // pool services on this queue. protected Queue<GetRunspaceAsyncResult> ultimateRequestQueue; protected RunspacePoolStateInfo stateInfo; protected InitialSessionState _initialSessionState; protected PSHost host; protected Guid instanceId; private bool _isDisposed; protected bool isServicingRequests; protected object syncObject = new object(); private static readonly TimeSpan s_defaultCleanupPeriod = new TimeSpan(0, 15, 0); // 15 minutes. private TimeSpan _cleanupInterval; private Timer _cleanupTimer; #endregion #region Constructor /// <summary> /// Constructor which creates a RunspacePool using the /// supplied <paramref name="configuration"/>, <paramref name="minRunspaces"/> /// and <paramref name="maxRunspaces"/> /// </summary> /// <param name="maxRunspaces"> /// The maximum number of Runspaces that can exist in this pool. /// Should be greater than or equal to 1. /// </param> /// <param name="minRunspaces"> /// The minimum number of Runspaces that can exist in this pool. /// Should be greater than or equal to 1. /// </param> /// <param name="host"> /// The explicit PSHost implementation. /// </param> /// <exception cref="ArgumentNullException"> /// Host is null. /// </exception> /// <exception cref="ArgumentException"> /// Maximum runspaces is less than 1. /// Minimum runspaces is less than 1. /// </exception> public RunspacePoolInternal(int minRunspaces, int maxRunspaces, PSHost host) : this(minRunspaces, maxRunspaces) { if (host == null) { throw PSTraceSource.NewArgumentNullException("host"); } this.host = host; pool = new Stack<Runspace>(); runspaceRequestQueue = new Queue<GetRunspaceAsyncResult>(); ultimateRequestQueue = new Queue<GetRunspaceAsyncResult>(); _initialSessionState = InitialSessionState.CreateDefault(); } /// <summary> /// Constructor which creates a RunspacePool using the /// supplied <paramref name="configuration"/>, <paramref name="minRunspaces"/> /// and <paramref name="maxRunspaces"/> /// </summary> /// <param name="initialSessionState"> /// InitialSessionState to use when creating a new Runspace. /// </param> /// <param name="maxRunspaces"> /// The maximum number of Runspaces that can exist in this pool. /// Should be greater than or equal to 1. /// </param> /// <param name="minRunspaces"> /// The minimum number of Runspaces that can exist in this pool. /// Should be greater than or equal to 1. /// </param> /// <param name="host"> /// The explicit PSHost implementation. /// </param> /// <exception cref="ArgumentNullException"> /// initialSessionState is null. /// Host is null. /// </exception> /// <exception cref="ArgumentException"> /// Maximum runspaces is less than 1. /// Minimum runspaces is less than 1. /// </exception> public RunspacePoolInternal(int minRunspaces, int maxRunspaces, InitialSessionState initialSessionState, PSHost host) : this(minRunspaces, maxRunspaces) { if (initialSessionState == null) { throw PSTraceSource.NewArgumentNullException("initialSessionState"); } if (host == null) { throw PSTraceSource.NewArgumentNullException("host"); } _initialSessionState = initialSessionState.Clone(); this.host = host; ThreadOptions = initialSessionState.ThreadOptions; this.ApartmentState = initialSessionState.ApartmentState; pool = new Stack<Runspace>(); runspaceRequestQueue = new Queue<GetRunspaceAsyncResult>(); ultimateRequestQueue = new Queue<GetRunspaceAsyncResult>(); } /// <summary> /// Constructor for doing common initialization between /// this class and its derivatives. /// </summary> /// <param name="maxRunspaces"> /// The maximum number of Runspaces that can exist in this pool. /// Should be greater than or equal to 1. /// </param> /// <param name="minRunspaces"> /// The minimum number of Runspaces that can exist in this pool. /// Should be greater than or equal to 1. /// </param> protected RunspacePoolInternal(int minRunspaces, int maxRunspaces) { if (maxRunspaces < 1) { throw PSTraceSource.NewArgumentException("maxRunspaces", RunspacePoolStrings.MaxPoolLessThan1); } if (minRunspaces < 1) { throw PSTraceSource.NewArgumentException("minRunspaces", RunspacePoolStrings.MinPoolLessThan1); } if (minRunspaces > maxRunspaces) { throw PSTraceSource.NewArgumentException("minRunspaces", RunspacePoolStrings.MinPoolGreaterThanMaxPool); } maxPoolSz = maxRunspaces; minPoolSz = minRunspaces; stateInfo = new RunspacePoolStateInfo(RunspacePoolState.BeforeOpen, null); instanceId = Guid.NewGuid(); PSEtwLog.SetActivityIdForCurrentThread(instanceId); _cleanupInterval = s_defaultCleanupPeriod; _cleanupTimer = new Timer(new TimerCallback(CleanupCallback), null, Timeout.Infinite, Timeout.Infinite); } /// <summary> /// Default constructor. /// </summary> internal RunspacePoolInternal() { } #endregion #region Public Properties /// <summary> /// Get unique id for this instance of runspace pool. It is primarily used /// for logging purposes. /// </summary> public Guid InstanceId { get { return instanceId; } } /// <summary> /// Gets a boolean which describes if the runspace pool is disposed. /// </summary> public bool IsDisposed { get { return _isDisposed; } } /// <summary> /// Gets State of the current runspace pool. /// </summary> public RunspacePoolStateInfo RunspacePoolStateInfo { get { return stateInfo; } } /// <summary> /// Private data to be used by applications built on top of PowerShell. /// /// Local runspace pool is created with application private data set to an empty <see cref="PSPrimitiveDictionary"/>. /// </summary> internal virtual PSPrimitiveDictionary GetApplicationPrivateData() { if (_applicationPrivateData == null) { lock (this.syncObject) { if (_applicationPrivateData == null) { _applicationPrivateData = new PSPrimitiveDictionary(); } } } return _applicationPrivateData; } internal virtual void PropagateApplicationPrivateData(Runspace runspace) { runspace.SetApplicationPrivateData(this.GetApplicationPrivateData()); } private PSPrimitiveDictionary _applicationPrivateData; /// <summary> /// Gets the InitialSessionState object that this pool uses /// to create the runspaces. /// </summary> public InitialSessionState InitialSessionState { get { return _initialSessionState; } } /// <summary> /// The connection associated with this runspace pool. /// </summary> public virtual RunspaceConnectionInfo ConnectionInfo { get { return null; } } /// <summary> /// Specifies how often unused runspaces are disposed. /// </summary> public TimeSpan CleanupInterval { get { return _cleanupInterval; } set { lock (this.syncObject) { _cleanupInterval = value; } } } /// <summary> /// Returns runspace pool availability. /// </summary> public virtual RunspacePoolAvailability RunspacePoolAvailability { get { return (stateInfo.State == RunspacePoolState.Opened) ? RunspacePoolAvailability.Available : RunspacePoolAvailability.None; } } #endregion #region events /// <summary> /// Event raised when RunspacePoolState changes. /// </summary> public event EventHandler<RunspacePoolStateChangedEventArgs> StateChanged; /// <summary> /// Event raised when one of the runspaces in the pool forwards an event to this instance. /// </summary> public event EventHandler<PSEventArgs> ForwardEvent; /// <summary> /// Event raised when a new Runspace is created by the pool. /// </summary> internal event EventHandler<RunspaceCreatedEventArgs> RunspaceCreated; #endregion events #region Disconnect-Connect Methods /// <summary> /// Synchronously disconnect runspace pool. /// </summary> public virtual void Disconnect() { throw PSTraceSource.NewInvalidOperationException(RunspacePoolStrings.RunspaceDisconnectConnectNotSupported); } /// <summary> /// Asynchronously disconnect runspace pool. /// </summary> /// <param name="callback"></param> /// <param name="state"></param> /// <returns></returns> public virtual IAsyncResult BeginDisconnect(AsyncCallback callback, object state) { throw PSTraceSource.NewInvalidOperationException(RunspacePoolStrings.RunspaceDisconnectConnectNotSupported); } /// <summary> /// Wait for BeginDisconnect to complete. /// </summary> /// <param name="asyncResult"></param> public virtual void EndDisconnect(IAsyncResult asyncResult) { throw PSTraceSource.NewInvalidOperationException(RunspacePoolStrings.RunspaceDisconnectConnectNotSupported); } /// <summary> /// Synchronously connect runspace pool. /// </summary> public virtual void Connect() { throw PSTraceSource.NewInvalidOperationException(RunspacePoolStrings.RunspaceDisconnectConnectNotSupported); } /// <summary> /// Asynchronously connect runspace pool. /// </summary> /// <param name="callback"></param> /// <param name="state"></param> /// <returns></returns> public virtual IAsyncResult BeginConnect(AsyncCallback callback, object state) { throw PSTraceSource.NewInvalidOperationException(RunspacePoolStrings.RunspaceDisconnectConnectNotSupported); } /// <summary> /// Wait for BeginConnect to complete. /// </summary> /// <param name="asyncResult"></param> public virtual void EndConnect(IAsyncResult asyncResult) { throw PSTraceSource.NewInvalidOperationException(RunspacePoolStrings.RunspaceDisconnectConnectNotSupported); } /// <summary> /// Creates an array of PowerShell objects that are in the Disconnected state for /// all currently disconnected running commands associated with this runspace pool. /// </summary> /// <returns></returns> public virtual Collection<PowerShell> CreateDisconnectedPowerShells(RunspacePool runspacePool) { throw PSTraceSource.NewInvalidOperationException(RunspacePoolStrings.RunspaceDisconnectConnectNotSupported); } /// <summary> /// Returns RunspacePool capabilities. /// </summary> /// <returns>RunspacePoolCapability.</returns> public virtual RunspacePoolCapability GetCapabilities() { return RunspacePoolCapability.Default; } #endregion #region Public Methods /// <summary> /// Resets the runspace state on a runspace pool with a single /// runspace. /// This is currently supported *only* for remote runspaces. /// </summary> /// <returns>True if successful.</returns> internal virtual bool ResetRunspaceState() { throw new PSNotSupportedException(); } /// <summary> /// Sets the maximum number of Runspaces that can be active concurrently /// in the pool. All requests above that number remain queued until /// runspaces become available. /// </summary> /// <param name="maxRunspaces"> /// The maximum number of runspaces in the pool. /// </param> /// <returns> /// true if the change is successful; otherwise, false. /// </returns> /// <remarks> /// You cannot set the number of runspaces to a number smaller than /// the minimum runspaces. /// </remarks> internal virtual bool SetMaxRunspaces(int maxRunspaces) { bool isSizeIncreased = false; lock (pool) { if (maxRunspaces < this.minPoolSz) { return false; } if (maxRunspaces > this.maxPoolSz) { isSizeIncreased = true; } else { // since maxrunspaces limit is decreased // destroy unwanted runspaces from the top // of the pool. while (pool.Count > maxRunspaces) { Runspace rsToDestroy = pool.Pop(); DestroyRunspace(rsToDestroy); } } maxPoolSz = maxRunspaces; } // pool size is incremented.. check if we can release // some requests. if (isSizeIncreased) { EnqueueCheckAndStartRequestServicingThread(null, false); } return true; } /// <summary> /// Retrieves the maximum number of runspaces the pool maintains. /// </summary> /// <returns> /// The maximum number of runspaces in the pool /// </returns> public int GetMaxRunspaces() { return maxPoolSz; } /// <summary> /// Sets the minimum number of Runspaces that the pool maintains /// in anticipation of new requests. /// </summary> /// <param name="minRunspaces"> /// The minimum number of runspaces in the pool. /// </param> /// <returns> /// true if the change is successful; otherwise, false. /// </returns> /// <remarks> /// You cannot set the number of idle runspaces to a number smaller than /// 1 or greater than maximum number of active runspaces. /// </remarks> internal virtual bool SetMinRunspaces(int minRunspaces) { lock (pool) { if ((minRunspaces < 1) || (minRunspaces > this.maxPoolSz)) { return false; } minPoolSz = minRunspaces; } return true; } /// <summary> /// Retrieves the minimum number of runspaces the pool maintains. /// </summary> /// <returns> /// The minimum number of runspaces in the pool /// </returns> public int GetMinRunspaces() { return minPoolSz; } /// <summary> /// Retrieves the number of runspaces available at the time of calling /// this method. /// </summary> /// <exception cref="ArgumentException"> /// If the RunspacePool failed or has been closed /// </exception> /// <returns> /// The number of available runspace in the pool. /// </returns> internal virtual int GetAvailableRunspaces() { // Dont allow state changes while we get the count lock (syncObject) { if (stateInfo.State == RunspacePoolState.Opened) { // Win8: 169492 RunspacePool can report that there are negative runspaces available. // totalRunspaces represents all the runspaces that were ever created by ths RunspacePool // pool.Count represents the runspaces that are currently available // maxPoolSz represents the total capacity w.r.t runspaces for this RunspacePool // Once the RunspacePool allocates a runspace to a consumer, RunspacePool cannot reclaim the // runspace until the consumer released the runspace back to the pool. A SetMaxRunspaces() // call can arrive before the runspace is released..It is bad to make SetMaxRunspaces() // wait for the consumers to release runspaces, so we let SetMaxRunspaces() go by changing // maxPoolSz. Because of this there may be cases where maxPoolSz - totalRunspaces will become // less than 0. int unUsedCapacity = (maxPoolSz - totalRunspaces) < 0 ? 0 : (maxPoolSz - totalRunspaces); return (pool.Count + unUsedCapacity); } else if (stateInfo.State == RunspacePoolState.Disconnected) { throw new InvalidOperationException(RunspacePoolStrings.CannotWhileDisconnected); } else if (stateInfo.State != RunspacePoolState.BeforeOpen && stateInfo.State != RunspacePoolState.Opening) { throw new InvalidOperationException(HostInterfaceExceptionsStrings.RunspacePoolNotOpened); } else { return maxPoolSz; } } } /// <summary> /// Opens the runspacepool synchronously. RunspacePool must /// be opened before it can be used. /// </summary> /// <exception cref="InvalidRunspacePoolStateException"> /// RunspacePoolState is not BeforeOpen /// </exception> public virtual void Open() { CoreOpen(false, null, null); } /// <summary> /// Opens the RunspacePool asynchronously. RunspacePool must /// be opened before it can be used. /// To get the exceptions that might have occurred, call /// EndOpen. /// </summary> /// <param name="callback"> /// A AsyncCallback to call once the BeginOpen completes. /// </param> /// <param name="state"> /// A user supplied state to call the <paramref name="callback"/> /// with. /// </param> /// <returns> /// An AsyncResult object to monitor the state of the async /// operation. /// </returns> public IAsyncResult BeginOpen(AsyncCallback callback, object state) { return CoreOpen(true, callback, state); } /// <summary> /// Waits for the pending asynchronous BeginOpen to complete. /// </summary> /// <exception cref="ArgumentNullException"> /// asyncResult is a null reference. /// </exception> /// <exception cref="ArgumentException"> /// asyncResult object was not created by calling BeginOpen /// on this runspacepool instance. /// </exception> /// <exception cref="InvalidRunspacePoolStateException"> /// RunspacePoolState is not BeforeOpen. /// </exception> /// <remarks> /// TODO: Behavior if EndOpen is called multiple times. /// </remarks> public void EndOpen(IAsyncResult asyncResult) { if (asyncResult == null) { throw PSTraceSource.NewArgumentNullException("asyncResult"); } RunspacePoolAsyncResult rsAsyncResult = asyncResult as RunspacePoolAsyncResult; if ((rsAsyncResult == null) || (rsAsyncResult.OwnerId != instanceId) || (!rsAsyncResult.IsAssociatedWithAsyncOpen)) { throw PSTraceSource.NewArgumentException("asyncResult", RunspacePoolStrings.AsyncResultNotOwned, "IAsyncResult", "BeginOpen"); } rsAsyncResult.EndInvoke(); } /// <summary> /// Closes the RunspacePool and cleans all the internal /// resources. This will close all the runspaces in the /// runspacepool and release all the async operations /// waiting for a runspace. If the pool is already closed /// or broken or closing this will just return. /// </summary> public virtual void Close() { CoreClose(false, null, null); } /// <summary> /// Closes the RunspacePool asynchronously and cleans all the internal /// resources. This will close all the runspaces in the /// runspacepool and release all the async operations /// waiting for a runspace. If the pool is already closed /// or broken or closing this will just return. /// </summary> /// <param name="callback"> /// A AsyncCallback to call once the BeginClose completes. /// </param> /// <param name="state"> /// A user supplied state to call the <paramref name="callback"/> /// with. /// </param> /// <returns> /// An AsyncResult object to monitor the state of the async /// operation. /// </returns> public virtual IAsyncResult BeginClose(AsyncCallback callback, object state) { return CoreClose(true, callback, state); } /// <summary> /// Waits for the pending asynchronous BeginClose to complete. /// </summary> /// <exception cref="ArgumentException"> /// asyncResult object was not created by calling BeginClose /// on this runspacepool instance. /// </exception> /// <remarks> /// TODO: Behavior if EndClose is called multiple times. /// </remarks> public virtual void EndClose(IAsyncResult asyncResult) { if (asyncResult == null) { throw PSTraceSource.NewArgumentNullException("asyncResult"); } RunspacePoolAsyncResult rsAsyncResult = asyncResult as RunspacePoolAsyncResult; if ((rsAsyncResult == null) || (rsAsyncResult.OwnerId != instanceId) || (rsAsyncResult.IsAssociatedWithAsyncOpen)) { throw PSTraceSource.NewArgumentException("asyncResult", RunspacePoolStrings.AsyncResultNotOwned, "IAsyncResult", "BeginClose"); } rsAsyncResult.EndInvoke(); } /// <summary> /// Gets a Runspace from the pool. If no free runspace is available /// and if max pool size is not reached, a new runspace is created. /// Otherwise this will block a runspace is released and available. /// </summary> /// <returns> /// An opened Runspace. /// </returns> /// <exception cref="InvalidRunspacePoolStateException"> /// Cannot perform operation because RunspacePool is /// not in the opened state. /// </exception> public Runspace GetRunspace() { AssertPoolIsOpen(); // Get the runspace asynchronously. GetRunspaceAsyncResult asyncResult = (GetRunspaceAsyncResult)BeginGetRunspace(null, null); // Wait for async operation to complete. asyncResult.AsyncWaitHandle.WaitOne(); // throw the exception that occurred while // processing the async operation if (asyncResult.Exception != null) { throw asyncResult.Exception; } return asyncResult.Runspace; } /// <summary> /// Releases a Runspace to the pool. If pool is closed, this /// will be a no-op. /// </summary> /// <param name="runspace"> /// Runspace to release to the pool. /// </param> /// <exception cref="ArgumentException"> /// <paramref name="runspace"/> is null. /// </exception> /// <exception cref="InvalidRunspacePoolStateException"> /// Runspool is not in Opened state. /// </exception> /// <exception cref="InvalidOperationException"> /// Cannot release the runspace to this pool as the runspace /// doesn't belong to this pool. /// </exception> public void ReleaseRunspace(Runspace runspace) { if (runspace == null) { throw PSTraceSource.NewArgumentNullException("runspace"); } AssertPoolIsOpen(); bool isRunspaceReleased = false; bool destroyRunspace = false; // check if the runspace is owned by the pool lock (runspaceList) { if (!runspaceList.Contains(runspace)) { throw PSTraceSource.NewInvalidOperationException(RunspacePoolStrings.RunspaceNotBelongsToPool); } } // Release this runspace only if it is in valid state and is // owned by this pool. if (runspace.RunspaceStateInfo.State == RunspaceState.Opened) { lock (pool) { if (pool.Count < maxPoolSz) { isRunspaceReleased = true; pool.Push(runspace); } else { // this runspace is not going to be pooled as maxPoolSz is reduced. // so release the runspace and destroy it. isRunspaceReleased = true; destroyRunspace = true; } } } else { destroyRunspace = true; isRunspaceReleased = true; } if (destroyRunspace) { // Destroying a runspace might be costly. // so doing this outside of the lock. DestroyRunspace(runspace); } // it is important to release lock on Pool so that // other threads can service requests. if (isRunspaceReleased) { // service any pending runspace requests. EnqueueCheckAndStartRequestServicingThread(null, false); } } /// <summary> /// Dispose off the current runspace pool. /// </summary> /// <param name="disposing"> /// true to release all the internal resources. /// </param> public virtual void Dispose(bool disposing) { if (!_isDisposed) { if (disposing) { Close(); _cleanupTimer.Dispose(); _initialSessionState = null; host = null; } _isDisposed = true; } } #endregion #region Internal Methods /// <summary> /// The value of this property is propagated to all the Runspaces in this pool; /// it determines whether a new thread is create when a pipeline is executed. /// </summary> /// <remarks> /// Any updates to the value of this property must be done before the RunspacePool is opened /// </remarks> internal PSThreadOptions ThreadOptions { get; set; } = PSThreadOptions.Default; /// <summary> /// The value of this property is propagated to all the Runspaces in this pool. /// </summary> /// <remarks> /// Any updates to the value of this property must be done before the RunspacePool is opened /// </remarks> internal ApartmentState ApartmentState { get; set; } = Runspace.DefaultApartmentState; /// <summary> /// Gets Runspace asynchronously from the runspace pool. The caller /// will get notified with the runspace using <paramref name="callback"/> /// </summary> /// <param name="callback"> /// A AsyncCallback to call once the runspace is available. /// </param> /// <param name="state"> /// A user supplied state to call the <paramref name="callback"/> /// with. /// </param> /// <returns> /// An IAsyncResult object to track the status of the Async operation. /// </returns> internal IAsyncResult BeginGetRunspace( AsyncCallback callback, object state) { AssertPoolIsOpen(); GetRunspaceAsyncResult asyncResult = new GetRunspaceAsyncResult(this.InstanceId, callback, state); // Enqueue and start servicing thread in one go..saving multiple locks. EnqueueCheckAndStartRequestServicingThread(asyncResult, true); return asyncResult; } /// <summary> /// Cancels the pending asynchronous BeginGetRunspace operation. /// </summary> /// <param name="asyncResult"> /// </param> internal void CancelGetRunspace(IAsyncResult asyncResult) { if (asyncResult == null) { throw PSTraceSource.NewArgumentNullException("asyncResult"); } GetRunspaceAsyncResult grsAsyncResult = asyncResult as GetRunspaceAsyncResult; if ((grsAsyncResult == null) || (grsAsyncResult.OwnerId != instanceId)) { throw PSTraceSource.NewArgumentException("asyncResult", RunspacePoolStrings.AsyncResultNotOwned, "IAsyncResult", "BeginGetRunspace"); } grsAsyncResult.IsActive = false; } /// <summary> /// Waits for the pending asynchronous BeginGetRunspace to complete. /// </summary> /// <param name="asyncResult"> /// </param> /// <exception cref="ArgumentNullException"> /// asyncResult is a null reference. /// </exception> /// <exception cref="ArgumentException"> /// asyncResult object was not created by calling BeginGetRunspace /// on this runspacepool instance. /// </exception> /// <exception cref="InvalidRunspacePoolStateException"> /// RunspacePoolState is not BeforeOpen. /// </exception> /// <remarks> /// TODO: Behavior if EndGetRunspace is called multiple times. /// </remarks> internal Runspace EndGetRunspace(IAsyncResult asyncResult) { if (asyncResult == null) { throw PSTraceSource.NewArgumentNullException("asyncResult"); } GetRunspaceAsyncResult grsAsyncResult = asyncResult as GetRunspaceAsyncResult; if ((grsAsyncResult == null) || (grsAsyncResult.OwnerId != instanceId)) { throw PSTraceSource.NewArgumentException("asyncResult", RunspacePoolStrings.AsyncResultNotOwned, "IAsyncResult", "BeginGetRunspace"); } grsAsyncResult.EndInvoke(); return grsAsyncResult.Runspace; } /// <summary> /// Opens the runspacepool synchronously / asynchronously. /// Runspace pool must be opened before it can be used. /// </summary> /// <param name="isAsync"> /// true to open asynchronously /// </param> /// <param name="callback"> /// A AsyncCallback to call once the BeginOpen completes. /// </param> /// <param name="asyncState"> /// A user supplied state to call the <paramref name="callback"/> /// with. /// </param> /// <returns> /// asyncResult object to monitor status of the async /// open operation. This is returned only if <paramref name="isAsync"/> /// is true. /// </returns> /// <exception cref="InvalidRunspacePoolStateException"> /// Cannot open RunspacePool because RunspacePool is not in /// the BeforeOpen state. /// </exception> /// <exception cref="OutOfMemoryException"> /// There is not enough memory available to start this asynchronously. /// </exception> protected virtual IAsyncResult CoreOpen(bool isAsync, AsyncCallback callback, object asyncState) { lock (syncObject) { AssertIfStateIsBeforeOpen(); stateInfo = new RunspacePoolStateInfo(RunspacePoolState.Opening, null); } // only one thread will reach here, so no // need to lock. RaiseStateChangeEvent(stateInfo); if (isAsync) { AsyncResult asyncResult = new RunspacePoolAsyncResult(instanceId, callback, asyncState, true); // Open pool in another thread ThreadPool.QueueUserWorkItem(new WaitCallback(OpenThreadProc), asyncResult); return asyncResult; } // open the runspace synchronously OpenHelper(); return null; } /// <summary> /// Creates a Runspace + opens it synchronously and /// pushes it into the stack. /// </summary> /// <remarks> /// Caller to make sure this is thread safe. /// </remarks> protected void OpenHelper() { try { PSEtwLog.SetActivityIdForCurrentThread(this.InstanceId); // Create a Runspace and store it in the pool // for future use. This will validate whether // a runspace can be created + opened successfully Runspace rs = CreateRunspace(); pool.Push(rs); } catch (Exception exception) { SetStateToBroken(exception); // rethrow the exception throw; } bool shouldRaiseEvents = false; // RunspacePool might be closed while we are still opening // we should not change state from closed to opened.. lock (syncObject) { if (stateInfo.State == RunspacePoolState.Opening) { // Change state to opened and notify the user. stateInfo = new RunspacePoolStateInfo(RunspacePoolState.Opened, null); shouldRaiseEvents = true; } } if (shouldRaiseEvents) { RaiseStateChangeEvent(stateInfo); } } private void SetStateToBroken(Exception reason) { bool shouldRaiseEvents = false; lock (syncObject) { if ((stateInfo.State == RunspacePoolState.Opening) || (stateInfo.State == RunspacePoolState.Opened) || (stateInfo.State == RunspacePoolState.Disconnecting) || (stateInfo.State == RunspacePoolState.Disconnected) || (stateInfo.State == RunspacePoolState.Connecting)) { stateInfo = new RunspacePoolStateInfo(RunspacePoolState.Broken, null); shouldRaiseEvents = true; } } if (shouldRaiseEvents) { RunspacePoolStateInfo stateInfo = new RunspacePoolStateInfo(this.stateInfo.State, reason); RaiseStateChangeEvent(stateInfo); } } /// <summary> /// Starting point for asynchronous thread. /// </summary> /// <remarks> /// asyncResult object /// </remarks> protected void OpenThreadProc(object o) { Dbg.Assert(o is AsyncResult, "OpenThreadProc expects AsyncResult"); // Since this is an internal method, we can safely cast the // object to AsyncResult object. AsyncResult asyncObject = (AsyncResult)o; // variable to keep track of exceptions. Exception exception = null; try { OpenHelper(); } catch (Exception e) { // report non-severe exceptions to the user via the // asyncresult object exception = e; } finally { asyncObject.SetAsCompleted(exception); } } /// <summary> /// Closes the runspacepool synchronously / asynchronously. /// </summary> /// <param name="isAsync"> /// true to close asynchronously /// </param> /// <param name="callback"> /// A AsyncCallback to call once the BeginClose completes. /// </param> /// <param name="asyncState"> /// A user supplied state to call the <paramref name="callback"/> /// with. /// </param> /// <returns> /// asyncResult object to monitor status of the async /// open operation. This is returned only if <paramref name="isAsync"/> /// is true. /// </returns> private IAsyncResult CoreClose(bool isAsync, AsyncCallback callback, object asyncState) { lock (syncObject) { if ((stateInfo.State == RunspacePoolState.Closed) || (stateInfo.State == RunspacePoolState.Broken) || (stateInfo.State == RunspacePoolState.Closing) || (stateInfo.State == RunspacePoolState.Disconnecting) || (stateInfo.State == RunspacePoolState.Disconnected)) { if (isAsync) { RunspacePoolAsyncResult asyncResult = new RunspacePoolAsyncResult(instanceId, callback, asyncState, false); asyncResult.SetAsCompleted(null); return asyncResult; } else { return null; } } stateInfo = new RunspacePoolStateInfo(RunspacePoolState.Closing, null); } // only one thread will reach here. RaiseStateChangeEvent(stateInfo); if (isAsync) { RunspacePoolAsyncResult asyncResult = new RunspacePoolAsyncResult(instanceId, callback, asyncState, false); // Open pool in another thread ThreadPool.QueueUserWorkItem(new WaitCallback(CloseThreadProc), asyncResult); return asyncResult; } // open the runspace synchronously CloseHelper(); return null; } private void CloseHelper() { try { InternalClearAllResources(); } finally { stateInfo = new RunspacePoolStateInfo(RunspacePoolState.Closed, null); RaiseStateChangeEvent(stateInfo); } } private void CloseThreadProc(object o) { Dbg.Assert(o is AsyncResult, "CloseThreadProc expects AsyncResult"); // Since this is an internal method, we can safely cast the // object to AsyncResult object. AsyncResult asyncObject = (AsyncResult)o; // variable to keep track of exceptions. Exception exception = null; try { CloseHelper(); } catch (Exception e) { // report non-severe exceptions to the user via the // asyncresult object exception = e; } finally { asyncObject.SetAsCompleted(exception); } } #endregion #region Private Methods /// <summary> /// Raise state changed event based on the StateInfo /// object. /// </summary> /// <param name="stateInfo">State information object.</param> protected void RaiseStateChangeEvent(RunspacePoolStateInfo stateInfo) { StateChanged.SafeInvoke(this, new RunspacePoolStateChangedEventArgs(stateInfo)); } /// <summary> /// Checks if the Pool is open to honour requests. /// If not throws an exception. /// </summary> /// <exception cref="InvalidRunspacePoolStateException"> /// Cannot perform operation because RunspacePool is /// not in the opened state. /// </exception> internal void AssertPoolIsOpen() { lock (syncObject) { if (stateInfo.State != RunspacePoolState.Opened) { string message = StringUtil.Format(RunspacePoolStrings.InvalidRunspacePoolState, RunspacePoolState.Opened, stateInfo.State); throw new InvalidRunspacePoolStateException(message, stateInfo.State, RunspacePoolState.Opened); } } } /// <summary> /// Creates a new Runspace and initializes it by calling Open() /// </summary> /// <returns> /// An opened Runspace. /// </returns> /// <remarks> /// TODO: Exceptions thrown here need to be documented. /// </remarks> protected Runspace CreateRunspace() { Dbg.Assert(_initialSessionState != null, "_initialSessionState should not be null"); // TODO: exceptions thrown here need to be documented // runspace.Open() did not document all the exceptions. Runspace result = RunspaceFactory.CreateRunspaceFromSessionStateNoClone(host, _initialSessionState); result.ThreadOptions = this.ThreadOptions == PSThreadOptions.Default ? PSThreadOptions.ReuseThread : this.ThreadOptions; result.ApartmentState = this.ApartmentState; this.PropagateApplicationPrivateData(result); result.Open(); // Enforce the system lockdown policy if one is defined. Utils.EnforceSystemLockDownLanguageMode(result.ExecutionContext); result.Events.ForwardEvent += OnRunspaceForwardEvent; // this must be done after open since open initializes the ExecutionContext lock (runspaceList) { runspaceList.Add(result); totalRunspaces = runspaceList.Count; } // Start/Reset the cleanup timer to release idle runspaces in the pool. lock (this.syncObject) { _cleanupTimer.Change(CleanupInterval, CleanupInterval); } // raise the RunspaceCreated event and let callers handle it. RunspaceCreated.SafeInvoke(this, new RunspaceCreatedEventArgs(result)); return result; } /// <summary> /// Cleans/Closes the runspace. /// </summary> /// <param name="runspace"> /// Runspace to be closed/cleaned /// </param> protected void DestroyRunspace(Runspace runspace) { Dbg.Assert(runspace != null, "Runspace cannot be null"); runspace.Events.ForwardEvent -= OnRunspaceForwardEvent; // this must be done after open since open initializes the ExecutionContext runspace.Close(); runspace.Dispose(); lock (runspaceList) { runspaceList.Remove(runspace); totalRunspaces = runspaceList.Count; } } /// <summary> /// Cleans the pool closing the runspaces that are idle. /// This method is called as part of a timer callback. /// This method will make sure atleast minPoolSz number /// of Runspaces are active. /// </summary> /// <param name="state"></param> protected void CleanupCallback(object state) { Dbg.Assert((this.stateInfo.State != RunspacePoolState.Disconnected && this.stateInfo.State != RunspacePoolState.Disconnecting && this.stateInfo.State != RunspacePoolState.Connecting), "Local RunspacePool cannot be in disconnect/connect states"); bool isCleanupTimerChanged = false; // Clean up the pool only if more runspaces // than minimum requested are present. while (totalRunspaces > minPoolSz) { // if the pool is closing just return.. if (this.stateInfo.State == RunspacePoolState.Closing) { return; } // This is getting run on a threadpool thread // it is ok to take the hit on locking and unlocking. // this will release request threads depending // on thread scheduling Runspace runspaceToDestroy = null; lock (pool) { if (pool.Count <= 0) { break; // break from while } runspaceToDestroy = pool.Pop(); } // Stop the clean up timer only when we are about to clean runspaces. // It will be restarted when a new runspace is created. if (!isCleanupTimerChanged) { lock (this.syncObject) { _cleanupTimer.Change(Timeout.Infinite, Timeout.Infinite); isCleanupTimerChanged = true; } } // destroy runspace outside of the lock DestroyRunspace(runspaceToDestroy); continue; } } /// <summary> /// Close all the runspaces in the pool. /// </summary> private void InternalClearAllResources() { string message = StringUtil.Format(RunspacePoolStrings.InvalidRunspacePoolState, RunspacePoolState.Opened, stateInfo.State); Exception invalidStateException = new InvalidRunspacePoolStateException(message, stateInfo.State, RunspacePoolState.Opened); GetRunspaceAsyncResult runspaceRequester; // clear the request queue first..this way waiting threads // are immediately notified. lock (runspaceRequestQueue) { while (runspaceRequestQueue.Count > 0) { runspaceRequester = runspaceRequestQueue.Dequeue(); runspaceRequester.SetAsCompleted(invalidStateException); } } lock (ultimateRequestQueue) { while (ultimateRequestQueue.Count > 0) { runspaceRequester = ultimateRequestQueue.Dequeue(); runspaceRequester.SetAsCompleted(invalidStateException); } } // close all the runspaces List<Runspace> runspaceListCopy = new List<Runspace>(); lock (runspaceList) { runspaceListCopy.AddRange(runspaceList); runspaceList.Clear(); } // Start from the most recent runspace. for (int index = runspaceListCopy.Count - 1; index >= 0; index--) { // close runspaces suppress exceptions try { // this will release pipelines executing in the // runspace. runspaceListCopy[index].Close(); runspaceListCopy[index].Dispose(); } catch (InvalidRunspaceStateException) { } } lock (pool) { pool.Clear(); } // dont release pool/runspacelist/runspaceRequestQueue/ultimateRequestQueue as they // might be accessed in lock() statements from another thread. } /// <summary> /// If <paramref name="requestToEnqueue"/> is not null, enqueues the request. /// Checks if a thread pool thread is queued to service pending requests /// for runspace. If a thread is not queued, queues one. /// </summary> /// <param name="requestToEnqueue"> /// Used by calling threads to queue a request before checking and starting /// servicing thread. /// </param> /// <param name="useCallingThread"> /// uses calling thread to assign available runspaces (if any) to runspace /// requesters. /// </param> protected void EnqueueCheckAndStartRequestServicingThread(GetRunspaceAsyncResult requestToEnqueue, bool useCallingThread) { bool shouldStartServicingInSameThread = false; lock (runspaceRequestQueue) { if (requestToEnqueue != null) { runspaceRequestQueue.Enqueue(requestToEnqueue); } // if a thread is already servicing requests..just return. if (isServicingRequests) { return; } if ((runspaceRequestQueue.Count + ultimateRequestQueue.Count) > 0) { // we have requests pending..check if a runspace is available to // service the requests. lock (pool) { if ((pool.Count > 0) || (totalRunspaces < maxPoolSz)) { isServicingRequests = true; if ((useCallingThread) && (ultimateRequestQueue.Count == 0)) { shouldStartServicingInSameThread = true; } else { // release a async result object using a thread pool thread. // this way the calling thread will not block. ThreadPool.QueueUserWorkItem(new WaitCallback(ServicePendingRequests), false); } } } } } // only one thread will be here if any.. // This will allow us to release lock. if (shouldStartServicingInSameThread) { ServicePendingRequests(true); } } /// <summary> /// Releases any readers in the reader queue waiting for /// Runspace. /// </summary> /// <param name="useCallingThreadState"> /// This is of type object..because this method is called from a ThreadPool /// Thread. /// true, if calling thread should be used to assign a runspace. /// </param> protected void ServicePendingRequests(object useCallingThreadState) { // Check if the pool is closed or closing..if so return. if ((stateInfo.State == RunspacePoolState.Closed) || (stateInfo.State == RunspacePoolState.Closing)) { return; } Dbg.Assert((this.stateInfo.State != RunspacePoolState.Disconnected && this.stateInfo.State != RunspacePoolState.Disconnecting && this.stateInfo.State != RunspacePoolState.Connecting), "Local RunspacePool cannot be in disconnect/connect states"); bool useCallingThread = (bool)useCallingThreadState; GetRunspaceAsyncResult runspaceRequester = null; try { do { lock (ultimateRequestQueue) { while (ultimateRequestQueue.Count > 0) { // if the pool is closing just return.. if (this.stateInfo.State == RunspacePoolState.Closing) { return; } Runspace result; lock (pool) { if (pool.Count > 0) { result = pool.Pop(); } else if (totalRunspaces >= maxPoolSz) { // no runspace is available.. return; } else { // TODO: how to handle exceptions if runspace // creation fails. // Create a new runspace..since the max limit is // not reached. result = CreateRunspace(); } } // Dequeue a runspace request runspaceRequester = ultimateRequestQueue.Dequeue(); // if the runspace is not active send the runspace back to // the pool and process other requests if (!runspaceRequester.IsActive) { lock (pool) { pool.Push(result); } // release the runspace requester runspaceRequester.Release(); continue; } // release readers waiting for runspace on a thread pool // thread. runspaceRequester.Runspace = result; // release the async operation on a thread pool thread. if (useCallingThread) { // call DoComplete outside of the lock..as the // DoComplete handler may handle the runspace // in the same thread thereby blocking future // servicing requests. goto endOuterWhile; } else { ThreadPool.QueueUserWorkItem(new WaitCallback(runspaceRequester.DoComplete)); } } } lock (runspaceRequestQueue) { if (runspaceRequestQueue.Count == 0) { break; } // copy requests from one queue to another and start // processing the other queue while (runspaceRequestQueue.Count > 0) { ultimateRequestQueue.Enqueue(runspaceRequestQueue.Dequeue()); } } } while (true); endOuterWhile:; } finally { lock (runspaceRequestQueue) { isServicingRequests = false; // check if any new runspace request has arrived.. EnqueueCheckAndStartRequestServicingThread(null, false); } } if ((useCallingThread) && (runspaceRequester != null)) { // call DoComplete outside of the lock and finally..as the // DoComplete handler may handle the runspace in the same // thread thereby blocking future servicing requests. runspaceRequester.DoComplete(null); } } /// <summary> /// Throws an exception if the runspace state is not /// BeforeOpen. /// </summary> protected void AssertIfStateIsBeforeOpen() { if (stateInfo.State != RunspacePoolState.BeforeOpen) { // Call fails if RunspacePoolState is not BeforeOpen. InvalidRunspacePoolStateException e = new InvalidRunspacePoolStateException ( StringUtil.Format(RunspacePoolStrings.CannotOpenAgain, new object[] { stateInfo.State.ToString() } ), stateInfo.State, RunspacePoolState.BeforeOpen ); throw e; } } /// <summary> /// Raises the ForwardEvent event. /// </summary> protected virtual void OnForwardEvent(PSEventArgs e) { EventHandler<PSEventArgs> eh = this.ForwardEvent; if (eh != null) { eh(this, e); } } /// <summary> /// Forward runspace events to the pool's event queue. /// </summary> private void OnRunspaceForwardEvent(object sender, PSEventArgs e) { if (e.ForwardEvent) { OnForwardEvent(e); } } #endregion } }
37.169369
144
0.524407
[ "MIT" ]
3pe2/PowerShell
src/System.Management.Automation/engine/hostifaces/RunspacePoolInternal.cs
61,887
C#
using System; using System.Threading.Tasks; namespace Vibrant.InfluxDB.Client.SimpleSample { public class Program { static void Main( string[] args ) => MainAsync( args ).GetAwaiter().GetResult(); static async Task MainAsync( string[] args ) { const string influxHost = "http://ipv4.fiddler:8086"; // "http://localhost:8086"; const string databaseName = "mydb"; var client = new InfluxClient( new Uri( influxHost ) ); await client.CreateDatabaseAsync( databaseName ); await Should_Write_Typed_Rows_To_Database( databaseName, client ); await Should_Query_And_Display_Typed_Data( databaseName, client ); await Should_Query_With_Parameters_And_Display_Typed_Data( databaseName, client ); await client.DropDatabaseAsync( databaseName ); Console.WriteLine( "Press any key to exit..." ); Console.ReadKey(); } public static async Task Should_Write_Typed_Rows_To_Database( string db, InfluxClient client ) { var infos = CreateTypedRowsStartingAt( new DateTime( 2010, 1, 1, 1, 1, 1, DateTimeKind.Utc ), 500 ); await client.WriteAsync( db, "myMeasurementName", infos ); } public static async Task Should_Query_And_Display_Typed_Data( string db, InfluxClient client ) { var resultSet = await client.ReadAsync<ComputerInfo>( db, "SELECT * FROM myMeasurementName" ); // resultSet will contain 1 result in the Results collection (or multiple if you execute multiple queries at once) var result = resultSet.Results[ 0 ]; // result will contain 1 series in the Series collection (or potentially multiple if you specify a GROUP BY clause) var series = result.Series[ 0 ]; Console.WriteLine( $"{"Timestamp",10}{"Region",15}{"Host",20}{"CPU",20}{"RAM",15}" ); // series.Rows will be the list of ComputerInfo that you queried for foreach( var row in series.Rows ) { Console.WriteLine( $"{row.Timestamp,10}{row.Region,15}{row.Host,20}{row.CPU,20}{row.RAM,15}" ); } } public static async Task Should_Query_With_Parameters_And_Display_Typed_Data( string db, InfluxClient client ) { var resultSet = await client.ReadAsync<ComputerInfo>( db, "SELECT * FROM myMeasurementName WHERE time >= $myParam", new { myParam = new DateTime( 2010, 1, 1, 1, 1, 3, DateTimeKind.Utc ) } ); // resultSet will contain 1 result in the Results collection (or multiple if you execute multiple queries at once) var result = resultSet.Results[ 0 ]; // result will contain 1 series in the Series collection (or potentially multiple if you specify a GROUP BY clause) var series = result.Series[ 0 ]; Console.WriteLine( $"{"Timestamp",10}{"Region",15}{"Host",20}{"CPU",20}{"RAM",15}" ); // series.Rows will be the list of ComputerInfo that you queried for foreach( var row in series.Rows ) { Console.WriteLine( $"{row.Timestamp,10}{row.Region,15}{row.Host,20}{row.CPU,20}{row.RAM,15}" ); } } private static ComputerInfo[] CreateTypedRowsStartingAt( DateTime start, int rows ) { var rng = new Random(); var regions = new[] { "west-eu", "north-eu", "west-us", "east-us", "asia" }; var hosts = new[] { "some-host", "some-other-host" }; var timestamp = start; var infos = new ComputerInfo[ rows ]; for( int i = 0 ; i < rows ; i++ ) { long ram = rng.Next( int.MaxValue ); double cpu = rng.NextDouble(); string region = regions[ rng.Next( regions.Length ) ]; string host = hosts[ rng.Next( hosts.Length ) ]; var info = new ComputerInfo { Timestamp = timestamp, CPU = cpu, RAM = ram, Host = host, Region = region }; infos[ i ] = info; timestamp = timestamp.AddSeconds( 1 ); } return infos; } } }
40.039216
124
0.619001
[ "MIT" ]
Enegia/InfluxDB.Client
samples/Vibrant.InfluxDB.Client.SimpleSample/Program.cs
4,086
C#
using EasyNetQ; using EasyNetQ.ConnectionString; using EasyNetQ.Internals; using EasyNetQ.Topology; using MailerQ.Conventions; using Microsoft.Extensions.Options; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace MailerQ { /// <summary> /// A queue manager /// </summary> /// <remarks>Implemented with EasyNetQ</remarks> public class QueueManager : IQueueManager, IQueueDeclarer { private readonly IAdvancedBus bus; private readonly MailerQConfiguration configuration; /// <summary> /// Initializes a new instance of QueueManager /// </summary> /// <param name="configuration">The MailerQ configuration</param> public QueueManager(MailerQConfiguration configuration) { this.configuration = configuration; var connectionConfiguration = new ConnectionStringParser().Parse(configuration.RabbitConnectionString); if (!string.IsNullOrWhiteSpace(configuration.RabbitPassword)) { connectionConfiguration.Password = configuration.RabbitPassword; } bus = RabbitHutch.CreateBus(connectionConfiguration, x => { }).Advanced; } /// <summary> /// Initializes a new instance of QueueManager /// </summary> /// <param name="options">The MailerQ configuration as Option pattern</param> public QueueManager(IOptions<MailerQConfiguration> options) : this(options.Value) { } /// <inheritdoc/> public void DeclareDeadLetterQueueForPublish( string name, bool addQueueNamePrefix = true, bool durable = true, int messageTtl = 10, int maxPriority = (int)Priority.High, string deadLetterExchange = "", string deadLetterRoutingKey = QueueName.Outbox) { if (addQueueNamePrefix) { name = $"{configuration.QueuesNamePrefix}{name}"; } bus.QueueDeclare(name: name, config => { config .AsDurable(true) .WithMessageTtl(new TimeSpan(0, 0, 0, 0, messageTtl)) .WithMaxPriority(maxPriority) .WithDeadLetterExchange(new Exchange(deadLetterExchange)) .WithDeadLetterRoutingKey(deadLetterRoutingKey); }); } /// <inheritdoc/> public void Publish(OutgoingMessage outgoingMessage, string queueName = QueueName.Outbox) { var message = CreateMessage(outgoingMessage); bus.Publish(Exchange.GetDefault(), queueName, false, message); } /// <inheritdoc/> public async Task PublishAsync(OutgoingMessage outgoingMessage, string queueName = QueueName.Outbox) { var message = CreateMessage(outgoingMessage); await bus.PublishAsync(Exchange.GetDefault(), queueName, false, message); } /// <inheritdoc/> public void Publish(IEnumerable<OutgoingMessage> outgoingMessages, string queueName = QueueName.Outbox) { foreach (var outgoingMessage in outgoingMessages) { Publish(outgoingMessage, queueName); } } /// <inheritdoc/> public async Task PublishAsync(IEnumerable<OutgoingMessage> outgoingMessages, string queueName = QueueName.Outbox) { foreach (var outgoingMessage in outgoingMessages) { await PublishAsync(outgoingMessage, queueName); } } private static Message<OutgoingMessage> CreateMessage(OutgoingMessage outgoingMessage) { var message = new Message<OutgoingMessage>(outgoingMessage); if (outgoingMessage.Priority.HasValue) { message.Properties.Priority = (byte)outgoingMessage.Priority; } return message; } /// <inheritdoc/> public IDisposable Subscribe<T>(Action<T> action) where T : OutgoingMessage { var queueName = GetQueueName<T>(); return Subscribe(action, queueName); } /// <inheritdoc/> public IDisposable Subscribe<T>(Action<T> action, string queueName) where T : OutgoingMessage { var queue = bus.QueueDeclare(queueName); return bus.Consume(queue, (body, properties, info) => { var jsonMessage = Encoding.UTF8.GetString(body); var resultMessage = JsonConvert.DeserializeObject<T>(jsonMessage); action.Invoke(resultMessage); }); } /// <inheritdoc/> public IDisposable SubscribeAsync<T>(Func<T, Task> action) where T : OutgoingMessage { var queueName = GetQueueName<T>(); return SubscribeAsync(action, queueName); } /// <inheritdoc/> public IDisposable SubscribeAsync<T>(Func<T, Task> action, string queueName) where T : OutgoingMessage { var queue = bus.QueueDeclare(queueName); return bus.Consume(queue, async (body, properties, info) => { var jsonMessage = Encoding.UTF8.GetString(body); var resultMessage = JsonConvert.DeserializeObject<T>(jsonMessage); await action.Invoke(resultMessage); }); } private string GetQueueName<T>() { var queueName = typeof(T).GetAttribute<QueueAttribute>().QueueName; return $"{configuration.QueuesNamePrefix}{queueName}"; } /// <inheritdoc/> public void Dispose() { bus.Dispose(); } } }
35.569697
122
0.595843
[ "MIT" ]
MakingSense/mailerq-dotnet-sdk
MailerQ/Core/QueueManager.cs
5,871
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace XnaCraft.Engine.World { public interface IChunkVertexBuilder { void BeginBlock(Vector3 position, BlockDescriptor descriptor, int[, ,] neighbours); void AddFrontFace(); void AddBackFace(); void AddTopFace(); void AddBottomFace(); void AddLeftFace(); void AddRightFace(); VertexBuffer Build(); } }
22.625
91
0.679558
[ "MIT" ]
romanov/XnaCraft
XnaCraft.Engine/World/IChunkVertexBuilder.cs
545
C#
/* * Copyright 2020 New Relic Corporation. All rights reserved. * SPDX-License-Identifier: Apache-2.0 */ using System; using System.Collections.Concurrent; using System.Collections.Generic; using NewRelic.Reflection; namespace NewRelic.Providers.Wrapper.RestSharp { public class RestSharpHelper { private const string RestSharpAssemblyName = "RestSharp"; private static Func<object, string> _getParameterName; private static Func<object, object> _getParameterValue; private static Func<object, Enum> _getMethod; private static Func<object, object, Uri> _buildUri; private static ConcurrentDictionary<Type, Func<object, object>> _getRestResponseFromGeneric = new ConcurrentDictionary<Type, Func<object, object>>(); private static ConcurrentDictionary<Type, Func<object, object>> _getHeadersFromInterface = new ConcurrentDictionary<Type, Func<object, object>>(); private static ConcurrentDictionary<Type, Func<object, object>> _getListElementsFromGeneric = new ConcurrentDictionary<Type, Func<object, object>>(); private static ConcurrentDictionary<Type, Func<object, object>> _getStatusCodeFromInterface = new ConcurrentDictionary<Type, Func<object, object>>(); public static Func<object, Enum> GetMethod => _getMethod ?? (_getMethod = VisibilityBypasser.Instance.GeneratePropertyAccessor<Enum>(RestSharpAssemblyName, "RestSharp.RestRequest", "Method")); //RestSharp is not strongly signed so type load fails if reference directly for .NET Framework applications public static Func<object, object, Uri> BuildUri => _buildUri ?? (_buildUri = VisibilityBypasser.Instance.GenerateOneParameterMethodCaller<Uri>(RestSharpAssemblyName, "RestSharp.RestClient", "BuildUri", "RestSharp.IRestRequest")); public static List<KeyValuePair<string, string>> GetResponseHeaders(object restResponse) { var headersToReturn = new List<KeyValuePair<string, string>>(); var restResponseHeaders = GetHeadersFromInterface(restResponse); var items = GetListElementsAsArray(restResponseHeaders); foreach (var parameter in items) { headersToReturn.Add(new KeyValuePair<string, string>(GetParameterName(parameter), GetParameterValue(parameter))); } return headersToReturn; } public static object GetRestResponse(object responseTask) { var getResponse = _getRestResponseFromGeneric.GetOrAdd(responseTask.GetType(), t => VisibilityBypasser.Instance.GeneratePropertyAccessor<object>(t, "Result")); return getResponse(responseTask); } public static int GetResponseStatusCode(object restResponse) { var getStatusCode = _getStatusCodeFromInterface.GetOrAdd(restResponse.GetType(), t => VisibilityBypasser.Instance.GeneratePropertyAccessor<object>(RestSharpAssemblyName, "RestSharp.RestResponse", "StatusCode")); return (int)getStatusCode(restResponse); } private static object[] GetListElementsAsArray(object owner) { var ownerType = owner.GetType(); var getElementsInList = _getListElementsFromGeneric.GetOrAdd(ownerType, t => VisibilityBypasser.Instance.GenerateFieldReadAccessor<object>(ownerType, "_items")); return (object[])getElementsInList(owner); } private static string GetParameterName(object parameter) { var getParameterName = _getParameterName ?? (_getParameterName = VisibilityBypasser.Instance.GeneratePropertyAccessor<string>(RestSharpAssemblyName, "RestSharp.Parameter", "Name")); return getParameterName(parameter); } private static string GetParameterValue(object parameter) { var getParameterValue = _getParameterValue ?? (_getParameterValue = VisibilityBypasser.Instance.GeneratePropertyAccessor<object>(RestSharpAssemblyName, "RestSharp.Parameter", "Value")); return (string)getParameterValue(parameter); } private static object GetHeadersFromInterface(object restResponse) { var getHeaders = _getHeadersFromInterface.GetOrAdd(restResponse.GetType(), t => VisibilityBypasser.Instance.GeneratePropertyAccessor<object>(RestSharpAssemblyName, "RestSharp.RestResponse", "Headers")); return getHeaders(restResponse); } } }
52.411765
238
0.72211
[ "Apache-2.0" ]
Faithlife/newrelic-dotnet-agent
src/Agent/NewRelic/Agent/Extensions/Providers/Wrapper/RestSharp/RestSharpHelper.cs
4,455
C#
/**************************************************************************** * Copyright (c) 2018.3 布鞋 827922094@qq.com * * http://qframework.io * https://github.com/liangxiegame/QFramework * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ****************************************************************************/ using UnityEngine; namespace QFramework { public class NodeExample : MonoBehaviour { void Start() { this.Sequence() .Until(() => { return Input.GetKeyDown(KeyCode.Space); }) .Delay(2.0f) .Event(() => { Debug.Log("延迟两秒"); }) .Delay(1f) .Event(() => { Debug.Log("延迟一秒"); }) .Until(() => { return Input.GetKeyDown(KeyCode.A); }) .Event(() => { this.Repeat() .Delay(0.5f) .Event(() => { Debug.Log("0.5s"); }) .Begin() .DisposeWhen(() => { return Input.GetKeyDown(KeyCode.S); }) .OnDisposed(() => { Debug.Log("结束"); }); }) .Begin() .DisposeWhenFinished(); } #region Update的情况 //private float m_CurrentTime; //private bool isSpace = true; //private bool isBegin = false; //private bool isCanA = false; //private bool isA = false; //private bool isRepeatS = false; //private void Start() //{ // m_CurrentTime = Time.time; //} //private void Update() //{ // if (isSpace && Input.GetKeyDown(KeyCode.Space)) // { // isSpace = false; // isBegin = true; // m_CurrentTime = Time.time; // } // if (isA && Input.GetKeyDown(KeyCode.A)) // { // isA = false; // isRepeatS = true; // m_CurrentTime = Time.time; // } // if (isRepeatS) // { // if (Time.time - m_CurrentTime > 0.5f) // { // m_CurrentTime = Time.time; // Debug.Log("0.5s"); // } // if (Input.GetKeyDown(KeyCode.S)) // { // Debug.Log("结束"); // isRepeatS = false; // } // } // if (isBegin) // { // if (Time.time - m_CurrentTime > 2) // { // Debug.Log("延迟两秒"); // isBegin = false; // isCanA = true; // m_CurrentTime = Time.time; // } // } // if (isCanA) // { // if (Time.time - m_CurrentTime > 1) // { // Debug.Log("延迟一秒"); // isCanA = false; // isA = true; // } // } //} #endregion } }
33.204724
81
0.446052
[ "MIT" ]
Bian-Sh/QFramework
Assets/QFramework/Framework/1.ActionKit/Example/NodeExample.cs
4,269
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 cloudformation-2010-05-15.normal.json service model. */ using System; using System.Net; using Amazon.Runtime; namespace Amazon.CloudFormation.Model { ///<summary> /// CloudFormation exception /// </summary> #if !PCL && !CORECLR [Serializable] #endif public class AlreadyExistsException : AmazonCloudFormationException { /// <summary> /// Constructs a new AlreadyExistsException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public AlreadyExistsException(string message) : base(message) {} /// <summary> /// Construct instance of AlreadyExistsException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public AlreadyExistsException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Construct instance of AlreadyExistsException /// </summary> /// <param name="innerException"></param> public AlreadyExistsException(Exception innerException) : base(innerException) {} /// <summary> /// Construct instance of AlreadyExistsException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public AlreadyExistsException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, requestId, statusCode) {} /// <summary> /// Construct instance of AlreadyExistsException /// </summary> /// <param name="message"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public AlreadyExistsException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, requestId, statusCode) {} #if !PCL && !CORECLR /// <summary> /// Constructs a new instance of the AlreadyExistsException class with serialized data. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception> protected AlreadyExistsException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } #endif } }
42.876289
178
0.647992
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/CloudFormation/Generated/Model/AlreadyExistsException.cs
4,159
C#
using System; using System.Linq; using System.Windows.Forms; namespace CaravelEditor { public partial class AddComponentForm : Form { public AddComponentForm(string[] components, string[] entityComponents) { InitializeComponent(); addButton.Enabled = false; foreach (var comp in components) { if (!entityComponents.Contains(comp)) { comboBox.Items.Add(comp); } } } public string GetSelectedComponent() { return (string) comboBox.SelectedItem; } public void comboBox_OnSelectedIndexChanged(object sender, EventArgs eventArgs) { if (comboBox.SelectedIndex != -1) { addButton.Enabled = true; } else { addButton.Enabled = false; } } } }
23.02381
87
0.505688
[ "MIT" ]
jocamar/CaravelEditor
AddComponentForm.cs
969
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable namespace Azure.Analytics.Synapse.Artifacts.Models { /// <summary> The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location. </summary> public partial class ProxyResource : Resource { /// <summary> Initializes a new instance of ProxyResource. </summary> public ProxyResource() { } /// <summary> Initializes a new instance of ProxyResource. </summary> /// <param name="id"> Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. </param> /// <param name="name"> The name of the resource. </param> /// <param name="type"> The type of the resource. E.g. &quot;Microsoft.Compute/virtualMachines&quot; or &quot;Microsoft.Storage/storageAccounts&quot;. </param> internal ProxyResource(string id, string name, string type) : base(id, name, type) { } } }
43.592593
225
0.685641
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/synapse/Azure.Analytics.Synapse.Artifacts/src/Generated/Models/ProxyResource.cs
1,177
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace PAYE.Models { public class UserOutputModel { public double BasicSalary { get; set; } public double TotalPayeTax { get; set; } public double EmployerPensionContribution_Tier_One { get; set; } public double EmployeePensionAmount_Tier_One { get; set; } public double EmployerPensionContribution_Tier_Two { get; set; } public double EmployeePensionAmount_Tier_Two { get; set; } public double EmployerPensionContribution_Tier_Three { get; set; } public double EmployeePensionAmount_Tier_Three { get; set; } public double GrossSalary { get; set; } public object Deductions { get; set; } public double TotalAllowances { get; set; } } }
36.434783
74
0.696897
[ "MIT" ]
DerrickYeb/PAYE
PAYE/Models/UserOutputModel.cs
840
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class UCP : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if ((string)Session["username"] == null) { Response.Redirect("Home.aspx"); } else { btnLogout.Visible = true; } lblName.Text = ((string)Session["firstName"]) + " " + ((string)Session["lastName"]); if ((string)Session["lastLogin"] == "0") { lblTime.Text = "NEW MEMBER"; } else { lblTime.Text = (string)Session["lastLogin"]; } } protected void btnLogout_Click(object sender, EventArgs e) { Session.Abandon(); Response.Redirect("Home.aspx"); } void Page_PreInit(object sender, EventArgs e) { if ((Convert.ToInt32(Session["theme"])) == 0) { MasterPageFile = "~/MasterPage.master"; } else if ((Convert.ToInt32(Session["theme"])) == 1) { MasterPageFile = "~/SecondMasterPage.master"; } } protected void btnDonateHistory_Click(object sender, EventArgs e) { Response.Redirect("DonateHistory.aspx"); } }
26.403846
93
0.544064
[ "Unlicense" ]
Darren-Lim-School-Project/ESE3006
UCP.aspx.cs
1,375
C#
using System; using System.Collections.Generic; namespace Comments.Models { public partial class Location { public int LocationId { get; set; } public string SourceURI { get; set; } public string HtmlElementID { get; set; } public string RangeStart { get; set; } public int? RangeStartOffset { get; set; } public string RangeEnd { get; set; } public int? RangeEndOffset { get; set; } public string Quote { get; set; } public string Order { get; set; } public string SectionHeader { get; set; } public string SectionNumber { get; set; } public ICollection<Comment> Comment { get; set; } public ICollection<OrganisationAuthorisation> OrganisationAuthorisation { get; set; } public ICollection<Question> Question { get; set; } } }
32.52
93
0.667897
[ "MIT" ]
nhsevidence/consultations
Comments/Models/EF/Location.cs
815
C#
using NUnit.Framework; namespace UnitTestProject1 { [TestFixture] public class UnitTest1 { [Category("NormalRun")] [Test] public void TestMethod1() { Assert.That(0, Is.EqualTo(1)); } // [Test] public void TestMethod2() { Assert.That(1, Is.EqualTo(1)); } } }
16.565217
42
0.48294
[ "MIT" ]
gastart/integtest
UnitTestProjects/UnitTestProject1/UnitTest1.cs
383
C#
using System; namespace Salgu.Networking { // 특별한 기능은 없다. 단순히 필드나 메소드에 붙여서 가독성을 높이기 위함. /// <summary> /// 리플렉션으로 호출되는 메소드나 값이 변경되는 필드는 디버깅이 어려우므로 /// 이 어트리뷰트를 붙여서 구분해 놓는것이 좋다. /// </summary> public class RMPAttribute : Attribute { } /// <summary> /// 서버에서만 사용될 메소드나 필드 /// </summary> public class ServerOnlyAttribute : Attribute { } /// <summary> /// 클라이언트에서만 사용될 메소드나 필드 /// </summary> public class ClientOnlyAttribute : Attribute { } /// <summary> /// 값이 동기화 되는 필드 /// </summary> public class SyncAttribute : Attribute { } /// <summary> /// 값이 동기화 되지 않는 필드 /// </summary> public class NoSyncAttribute : Attribute { } }
19.176471
49
0.636503
[ "MIT" ]
chickeningot/multiplayer-unity
Assets/Salgu/Networking/Scripts/RMP/RMPAttributes.cs
918
C#
// Copyright (c) 2008-2020, Hazelcast, Inc. 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. using Hazelcast.Core; using NUnit.Framework; namespace Hazelcast.Tests.Core { [TestFixture] public class SequenceTests { [Test] public void Int32Sequence() { ISequence<int> sequence = new Int32Sequence(); for (var i = 0; i < 100; i++) Assert.That(sequence.GetNext(), Is.EqualTo(i+1)); } [Test] public void Int64Sequence() { ISequence<long> sequence = new Int64Sequence(); for (var i = 0; i < 100; i++) Assert.That(sequence.GetNext(), Is.EqualTo(i+1)); } } }
29.595238
75
0.633146
[ "Apache-2.0" ]
BigYellowHammer/hazelcast-csharp-client
src/Hazelcast.Net.Tests/Core/SequenceTests.cs
1,245
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using RimWorld; using Verse; namespace MoreGraphs.Wealth { class HistoryAutoRecorderWorker_MoreGraphsWealthFood : HistoryAutoRecorderWorker_MoreGraphsWealthCategoryBase { public HistoryAutoRecorderWorker_MoreGraphsWealthFood() : base(WealthCategory.Food) { } } }
22.764706
113
0.767442
[ "MIT" ]
nnieman/more-graphs
Source/MoreGraphs/MoreGraphs/Wealth/HistoryAutoRecorderWorker_MoreGraphsWealthFood.cs
389
C#
#region Using using System; using System.Data; using System.Linq; using System.Text; using FiscalCode.Models.PersonViewModel; #endregion namespace FiscalCode.Models.FiscalCode { /// <summary> /// Classe per la gestione delle funzioni per il calcolo del codice fiscale /// </summary> public class FunctionFiscalCode { /// <summary> /// DB per il calcolo del codice fiscale /// </summary> private readonly DataSet _data; /// <summary> /// Vocali per il calcolo /// </summary> private readonly string _vowel = "AEIOU"; /// <summary> /// Consonanti per il calcolo /// </summary> private readonly string _consonant = "BCDFGHJKLMNPQRSTVWXYZ"; /// <summary> /// Costruttore per la gestione del codice fiscale /// </summary> public FunctionFiscalCode(DataSet data) => _data = data; /// <summary> /// Funzione per il check del carattere di controllo /// </summary> /// <param name="partialCode">Codice fiscale senza carattere di controllo</param> /// <returns></returns> public string GetCIN(string partialCode) { int somma = 0; for (int i = 0; i < partialCode.Length; i++) { string tableName; if ((i + 1) % 2 == 1) tableName = "CINDispari"; else tableName = "CINPari"; somma += _data.Tables[tableName].Select($"Carattere = '{partialCode[i]}'")[0].Field<int>("Valore"); } return _data.Tables["CINResto"].Select($"Resto = {(somma % 26)}")[0].Field<string>("Valore"); } /// <summary> /// Restituisce il codice Omocodia in base alla lettera /// </summary> /// <param name="letter">Lettera </param> /// <returns></returns> public int GetOmocodice(string letter) { DataRow[] foundRows = _data.Tables["Omocodia"].Select($"Lettera = '{letter}'"); if (!foundRows.Any()) throw new Exception($"Lettera {letter} non trovata"); return foundRows[0].Field<int>("Cifra"); } /// <summary> /// Restituisce la lettera in base al codice Omocodia /// </summary> /// <param name="number">Codice Omocodia</param> /// <returns></returns> public string GetOmocodice(int number) { DataRow[] foundRows = _data.Tables["Omocodia"].Select($"Cifra = {number}"); if (!foundRows.Any()) throw new Exception($"Codice {number} non trovato"); return foundRows[0].Field<string>("Lettera"); } /// <summary> /// Ritorna la data di nascita a partiee dal codice fiscale normalizzato /// </summary> /// <param name="fiscalCodeNormalized">Codice fiscale normalizzato</param> /// <returns></returns> public DateTime GetDate(string fiscalCodeNormalized) { int aYear = int.Parse(fiscalCodeNormalized.Substring(6, 2)); int thisYear = DateTime.Now.Year; thisYear -= ((thisYear / 100) * 100); if (aYear > thisYear) aYear += 1900; else aYear += 2000; int aMonth = GetMonth(fiscalCodeNormalized.Substring(8, 1)); int aDay = int.Parse(fiscalCodeNormalized.Substring(9, 2)); if (aDay > 40) aDay -= 40; // Donna tolgo 40 return new DateTime(aYear, aMonth, aDay); } /// <summary> /// Converte il codice nel numero di mese /// </summary> /// <param name="code">Codice del comune</param> /// <returns></returns> public int GetMonth(string code) { DataRow[] foundRows = _data.Tables["Mesi"].Select($"Lettera = '{code}'"); if (!foundRows.Any()) throw new ArgumentException("codice mese non trovato"); DataRow meseRow = foundRows[0]; return meseRow.Field<int>("Mese"); } /// <summary> /// Restituisce il codice a partire dal mese /// </summary> /// <param name="month">Mese in numero</param> /// <returns></returns> public string GetMonth(int month) { DataRow[] foundRows = _data.Tables["Mesi"].Select($"Mese = {month}"); if (!foundRows.Any()) throw new ArgumentException("Mese non trovato"); DataRow monthRow = foundRows[0]; return monthRow.Field<string>("Lettera"); } /// <summary> /// Calcola il codice del nome/cognome a partire da esso. /// </summary> /// <param name="name">nome/cognome da calcolare</param> /// <param name="isSurname"(Opzionale) se true effettua il calcolo per il cognome</param> /// <returns>Ritorna il codice di 3 cifre</returns> public string CalcCodeFromName(string name, bool isSurname = false) { bool consonantRemove = false; StringBuilder tmpCode = new(4); foreach (char c in name.ToUpper()) if (_consonant.Contains(c)) { tmpCode.Append(c); if (!consonantRemove && !isSurname && tmpCode.Length == 4) { tmpCode.Remove(1, 1); consonantRemove = true; } } if (tmpCode.Length > 3) tmpCode.Remove(3, tmpCode.Length - 3); if (tmpCode.Length < 3) foreach (char c in name.ToUpper()) { if (_vowel.IndexOf(c) >= 0) tmpCode.Append(c); if (tmpCode.Length == 3) break; } if (tmpCode.Length < 3) { int missingChars = 3 - tmpCode.Length; tmpCode.Append(new string('X', missingChars)); } return tmpCode.ToString(); } /// <summary> /// Ritorna la città a partire dal codice del comune /// </summary> /// <param name="codeCity">Codice comune</param> /// <returns>I dati della Città</returns> public CityModel GetCity(string codeCity) { DataRow[] foundRows = _data.Tables["Comuni"].Select($"Codice = '{codeCity}'"); if (!foundRows.Any()) throw new ArgumentException("Codice città non trovato"); return GetCity(cityRow: foundRows[0]); } /// <summary> /// Ritorna la città a partire dal comune/provincia /// </summary> /// <param name="city">Comune</param> /// <param name="province">Porvincia</param> /// <returns>I dati della Città</returns> public CityModel GetCity(string city, string province) { string aCity = city.Replace("'", "''"); string aProvince = province.Replace("'", "''"); DataRow[] foundRows = _data.Tables["Comuni"].Select($"Nome = '{aCity}' And Provincia ='{aProvince}'"); if (!foundRows.Any()) throw new ArgumentException("Città o provincia non trovati"); return GetCity(cityRow: foundRows[0]); } /// <summary> /// Ritorna la città a partire dalla row del db /// </summary> /// <param name="cityRow">Data row del db</param> /// <returns></returns> private static CityModel GetCity(DataRow cityRow) { return new() { Code = cityRow.Field<string>("Codice"), Name = cityRow.Field<string>("Nome"), Province = cityRow.Field<string>("Provincia") }; } } }
33.190871
115
0.518065
[ "BSD-2-Clause" ]
milikatot/FiscalCode
FiscalCode/Models/FiscalCode/FunctionFiscalCode.cs
8,008
C#
using MvvmCross.Binding.BindingContext; using MvvmCross.iOS.Views; using ProductPriceCalc.Core.ViewModels; using System.Drawing; using UIKit; namespace ProductPriceCalc.iOS.Views { public partial class FirstView : MvxViewController<FirstViewModel> { public FirstView() : base("FirstView", null) { } public override void ViewDidLoad() { base.ViewDidLoad(); var labelRetail = new UILabel(new RectangleF(10, 10, 300, 40)); labelRetail.Text = "Retail price"; Add(labelRetail); var retailPriceField = new UITextField(new Rectangle(10, 50, 300, 40)); Add(retailPriceField); var label1 = new UILabel(new RectangleF(10, 90, 300, 40)); label1.Text = "Tax"; Add(label1); var sliderTax = new UISlider(new Rectangle(10, 130, 300, 40)); sliderTax.MinValue = 0; sliderTax.MaxValue = 100; Add(sliderTax); var labelTax = new UILabel(new RectangleF(10, 170, 300, 40)); Add(labelTax); var label2 = new UILabel(new RectangleF(10, 210, 300, 40)); label2.Text = "Profit"; Add(label2); var sliderProfit = new UISlider(new Rectangle(10, 250, 300, 40)); sliderProfit.MinValue = 0; sliderProfit.MaxValue = 100; Add(sliderProfit); var labelProfit = new UILabel(new RectangleF(10, 290, 300, 40)); Add(labelProfit); var labelTotal = new UILabel(new RectangleF(10, 330, 300, 40)); Add(labelTotal); var set = this.CreateBindingSet<FirstView, Core.ViewModels.FirstViewModel>(); set.Bind(retailPriceField).To(vm => vm.RetailPrice); set.Bind(sliderTax).To(vm => vm.Tax); set.Bind(labelTax).To(vm => vm.Tax); set.Bind(sliderProfit).To(vm => vm.Profit); set.Bind(labelProfit).To(vm => vm.Profit); set.Bind(labelTotal).To(vm => vm.TotalPrice); set.Apply(); } } }
32.921875
89
0.572852
[ "MIT" ]
mauricemarkvoort/ProductPriceCalc
ProductPriceCalc.Touch/Views/FirstView.cs
2,107
C#
namespace MoiteRecepti.Web.Areas.Administration.Controllers { using Microsoft.AspNetCore.Mvc; using MoiteRecepti.Services.Data; using MoiteRecepti.Web.ViewModels.Administration.Dashboard; public class DashboardController : AdministrationController { private readonly ISettingsService settingsService; public DashboardController(ISettingsService settingsService) { this.settingsService = settingsService; } public IActionResult Index() { var viewModel = new IndexViewModel { SettingsCount = this.settingsService.GetCount(), }; return this.View(viewModel); } } }
29.608696
100
0.688693
[ "MIT" ]
TeodorLevakov/MoiteRecepti
MoiteRecepti/Web/MoiteRecepti.Web/Areas/Administration/Controllers/DashboardController.cs
683
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ConsoleApp1")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ConsoleApp1")] [assembly: AssemblyCopyright("Copyright © 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("bef62fe1-26d8-4639-b1df-2682e7d4e1d3")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.567568
84
0.747482
[ "MIT" ]
JaxSoder/StartMenuCleanUp1.0
ConsoleApp1/Properties/AssemblyInfo.cs
1,393
C#
using System.Collections.Generic; using System.Linq; using UnityEngine; namespace UnityEditor.VFX.Block { [VFXInfo(category = "Position")] class PositionCone : PositionBase { public enum HeightMode { Base, Volume } [VFXSetting, Tooltip("Controls whether particles are spawned on the base of the cone, or throughout the entire volume.")] public HeightMode heightMode; public override string name { get { return "Position (Cone)"; } } protected override float thicknessDimensions { get { return 2.0f; } } public class InputProperties { [Tooltip("The cone used for positioning particles.")] public ArcCone Cone = new ArcCone() { radius0 = 0.0f, radius1 = 1.0f, height = 0.5f, arc = Mathf.PI * 2.0f }; } public class CustomProperties { [Range(0, 1), Tooltip("When using customized emission, control the position along the height to emit particles from.")] public float HeightSequencer = 0.0f; [Range(0, 1), Tooltip("When using customized emission, control the position around the arc to emit particles from.")] public float ArcSequencer = 0.0f; } public override IEnumerable<VFXNamedExpression> parameters { get { foreach (var p in GetExpressionsFromSlots(this).Where(e => e.name != "Thickness")) yield return p; yield return new VFXNamedExpression(CalculateVolumeFactor(positionMode, 0, 1), "volumeFactor"); VFXExpression radius0 = inputSlots[0][1].GetExpression(); VFXExpression radius1 = inputSlots[0][2].GetExpression(); VFXExpression height = inputSlots[0][3].GetExpression(); VFXExpression tanSlope = (radius1 - radius0) / height; VFXExpression slope = new VFXExpressionATan(tanSlope); if (spawnMode == SpawnMode.Randomized) yield return new VFXNamedExpression(radius1 / tanSlope, "fullConeHeight"); yield return new VFXNamedExpression(new VFXExpressionCombine(new VFXExpression[] { new VFXExpressionSin(slope), new VFXExpressionCos(slope) }), "sincosSlope"); } } protected override bool needDirectionWrite { get { return true; } } public override string source { get { string outSource = ""; if (spawnMode == SpawnMode.Randomized) outSource += @"float theta = Cone_arc * RAND;"; else outSource += @"float theta = Cone_arc * ArcSequencer;"; outSource += @" float rNorm = sqrt(volumeFactor + (1 - volumeFactor) * RAND); float2 sincosTheta; sincos(theta, sincosTheta.x, sincosTheta.y); float2 pos = (sincosTheta * rNorm); "; if (heightMode == HeightMode.Base) { outSource += @" float hNorm = 0.0f; float3 base = float3(pos * Cone_radius0, 0.0f); "; } else if (spawnMode == SpawnMode.Randomized) { outSource += @" float heightFactor = pow(Cone_radius0 / Cone_radius1, 3.0f); float hNorm = pow(heightFactor + (1 - heightFactor) * RAND, 1.0f / 3.0f); float3 base = float3(0.0f, 0.0f, Cone_height - fullConeHeight); "; } else { outSource += @" float hNorm = HeightSequencer; float3 base = float3(0.0f, 0.0f, 0.0f); "; } outSource += @" direction.xzy = normalize(float3(pos * sincosSlope.x, sincosSlope.y)); position.xzy += lerp(base, float3(pos * Cone_radius1, Cone_height), hNorm) + Cone_center.xzy; "; return outSource; } } } }
33.728814
175
0.564322
[ "BSD-2-Clause" ]
1-10/VisualEffectGraphSample
GitHub/com.unity.visualeffectgraph/Editor/Models/Blocks/Implementations/Position/PositionCone.cs
3,980
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the databrew-2017-07-25.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.GlueDataBrew.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.GlueDataBrew.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for Project Object /// </summary> public class ProjectUnmarshaller : IUnmarshaller<Project, XmlUnmarshallerContext>, IUnmarshaller<Project, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> Project IUnmarshaller<Project, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public Project Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; Project unmarshalledObject = new Project(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("AccountId", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.AccountId = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("CreateDate", targetDepth)) { var unmarshaller = DateTimeUnmarshaller.Instance; unmarshalledObject.CreateDate = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("CreatedBy", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.CreatedBy = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("DatasetName", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.DatasetName = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("LastModifiedBy", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.LastModifiedBy = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("LastModifiedDate", targetDepth)) { var unmarshaller = DateTimeUnmarshaller.Instance; unmarshalledObject.LastModifiedDate = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Name", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Name = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("OpenDate", targetDepth)) { var unmarshaller = DateTimeUnmarshaller.Instance; unmarshalledObject.OpenDate = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("OpenedBy", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.OpenedBy = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("RecipeName", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.RecipeName = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("ResourceArn", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.ResourceArn = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("RoleArn", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.RoleArn = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Sample", targetDepth)) { var unmarshaller = SampleUnmarshaller.Instance; unmarshalledObject.Sample = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Tags", targetDepth)) { var unmarshaller = new DictionaryUnmarshaller<string, string, StringUnmarshaller, StringUnmarshaller>(StringUnmarshaller.Instance, StringUnmarshaller.Instance); unmarshalledObject.Tags = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static ProjectUnmarshaller _instance = new ProjectUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static ProjectUnmarshaller Instance { get { return _instance; } } } }
41.441176
181
0.556707
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/GlueDataBrew/Generated/Model/Internal/MarshallTransformations/ProjectUnmarshaller.cs
7,045
C#
using System.Text.RegularExpressions; namespace TESVSnip.UI.Docking { using System.Windows.Forms; using TESVSnip.Domain.Model; using TESVSnip.Framework.Services; using TESVSnip.Properties; public partial class OutputTextContent : BaseDockContent { System.Text.RegularExpressions.Regex reWhiteSpace = new Regex("\r?\n"); public OutputTextContent() { this.InitializeComponent(); } public System.Windows.Forms.TextBox TextBox { get { return this.textBox; } } public void UpdateText(string text) { this.textBox.Text = reWhiteSpace.Replace(text, "\r\n"); } public void SetText(string text) { this.textBox.Text = reWhiteSpace.Replace(text, "\r\n"); } public void ClearText() { this.textBox.Text = ""; } public void AppendText(string text) { this.textBox.AppendText( reWhiteSpace.Replace(text, "\r\n") ); } } }
23.020833
79
0.556561
[ "MIT" ]
TESnip-Skyrim-Edition/tesvsnip
Application/UI/Docking/OutputTextContent.cs
1,107
C#
using System; namespace SharpGlyph { public class JstfPriority { } }
12
28
0.736111
[ "MIT" ]
hikipuro/SharpGlyph
SharpGlyph/SharpGlyph/Tables/JSTF/JstfPriority.cs
74
C#
using Core.Entities; using System.Collections.Generic; namespace Core.Abstractions.Repositories { public interface IPersonRepository { int AddPerson(Person person); void EditPerson(Person person); void DeletePerson(int personID); Person GetByName(string name); IEnumerable<Person> GetAll(); } }
23.266667
40
0.687679
[ "MIT" ]
mladjonis/clean-architecture-boilerplate
Core/Abstractions/Repositories/IPersonRepository.cs
351
C#
using Content.Server.Administration; using Content.Shared.Administration; using Content.Shared.Popups; using Robust.Shared.Console; using Robust.Shared.GameObjects; namespace Content.Server.Popups { [AdminCommand(AdminFlags.Debug)] public class PopupMsgCommand : IConsoleCommand { public string Command => "srvpopupmsg"; public string Description => ""; public string Help => ""; public void Execute(IConsoleShell shell, string argStr, string[] args) { var source = EntityUid.Parse(args[0]); var viewer = EntityUid.Parse(args[1]); var msg = args[2]; source.PopupMessage(viewer, msg); } } }
27.153846
78
0.645892
[ "MIT" ]
A-Box-12/space-station-14
Content.Server/Popups/PopupMsgCommand.cs
708
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace CSharp.CSharp8 { class DefaultInterfaceImplementation : IRunner { public string Name => "Default Interface Implementation"; public async Task Run() { (this as IRunner).WriteRunnerName(); await Task.Delay(10); // just to delete the warning var interfaceImplementor = new InterfaceImplentor(); interfaceImplementor.ImplementThis(); InterfaceWithDefault interfaceWithDefault = interfaceImplementor; interfaceWithDefault.DoDefault(); } interface InterfaceWithDefault { public void DoDefault() => Console.WriteLine("Default Impl Called!"); public void ImplementThis(); } class InterfaceImplentor : InterfaceWithDefault { // Can be extended // public void DoDefault() => Console.WriteLine("Default extended and Called!"); public void ImplementThis() => Console.WriteLine("Implemented method Called!"); } } }
29.564103
92
0.625325
[ "Apache-2.0" ]
anaselhajjaji/csharp-examples
CSharp8/DefaultInterfaceImplementation.cs
1,155
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; namespace LabSwparkWs1 { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } }
23.48
62
0.58092
[ "MIT" ]
tlaothong/lab-swp-ws-kiatnakin
LabWsKiatnakin/LabSwparkWs1/App_Start/WebApiConfig.cs
589
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Gov.Jag.PillPressRegistry.Interfaces { using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for Lkbcgovcecontactcreatedby. /// </summary> public static partial class LkbcgovcecontactcreatedbyExtensions { /// <summary> /// Get lk_bcgov_cecontact_createdby from systemusers /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='ownerid'> /// key: ownerid of systemuser /// </param> /// <param name='top'> /// </param> /// <param name='skip'> /// </param> /// <param name='search'> /// </param> /// <param name='filter'> /// </param> /// <param name='count'> /// </param> /// <param name='orderby'> /// Order items by property values /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> public static MicrosoftDynamicsCRMbcgovCecontactCollection Get(this ILkbcgovcecontactcreatedby operations, string ownerid, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>)) { return operations.GetAsync(ownerid, top, skip, search, filter, count, orderby, select, expand).GetAwaiter().GetResult(); } /// <summary> /// Get lk_bcgov_cecontact_createdby from systemusers /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='ownerid'> /// key: ownerid of systemuser /// </param> /// <param name='top'> /// </param> /// <param name='skip'> /// </param> /// <param name='search'> /// </param> /// <param name='filter'> /// </param> /// <param name='count'> /// </param> /// <param name='orderby'> /// Order items by property values /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<MicrosoftDynamicsCRMbcgovCecontactCollection> GetAsync(this ILkbcgovcecontactcreatedby operations, string ownerid, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(ownerid, top, skip, search, filter, count, orderby, select, expand, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get lk_bcgov_cecontact_createdby from systemusers /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='ownerid'> /// key: ownerid of systemuser /// </param> /// <param name='bcgovCecontactid'> /// key: bcgov_cecontactid of bcgov_cecontact /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> public static MicrosoftDynamicsCRMbcgovCecontact CreatedbyByKey(this ILkbcgovcecontactcreatedby operations, string ownerid, string bcgovCecontactid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>)) { return operations.CreatedbyByKeyAsync(ownerid, bcgovCecontactid, select, expand).GetAwaiter().GetResult(); } /// <summary> /// Get lk_bcgov_cecontact_createdby from systemusers /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='ownerid'> /// key: ownerid of systemuser /// </param> /// <param name='bcgovCecontactid'> /// key: bcgov_cecontactid of bcgov_cecontact /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<MicrosoftDynamicsCRMbcgovCecontact> CreatedbyByKeyAsync(this ILkbcgovcecontactcreatedby operations, string ownerid, string bcgovCecontactid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreatedbyByKeyWithHttpMessagesAsync(ownerid, bcgovCecontactid, select, expand, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
45.315068
508
0.550635
[ "Apache-2.0" ]
GeorgeWalker/jag-pill-press-registry
pill-press-interfaces/Dynamics-Autorest/LkbcgovcecontactcreatedbyExtensions.cs
6,616
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.Runtime.InteropServices; namespace Microsoft.AspNetCore.Testing { [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = true)] public class OSSkipConditionAttribute : Attribute, ITestCondition { private readonly OperatingSystems _excludedOperatingSystem; private readonly OperatingSystems _osPlatform; public OSSkipConditionAttribute(OperatingSystems operatingSystem) : this(operatingSystem, GetCurrentOS()) { } [Obsolete("Use the Minimum/MaximumOSVersionAttribute for version checks.", error: true)] public OSSkipConditionAttribute(OperatingSystems operatingSystem, params string[] versions) : this(operatingSystem, GetCurrentOS()) { } // to enable unit testing internal OSSkipConditionAttribute(OperatingSystems operatingSystem, OperatingSystems osPlatform) { _excludedOperatingSystem = operatingSystem; _osPlatform = osPlatform; } public bool IsMet { get { var skip = (_excludedOperatingSystem & _osPlatform) == _osPlatform; // Since a test would be excuted only if 'IsMet' is true, return false if we want to skip return !skip; } } public string SkipReason { get; set; } = "Test cannot run on this operating system."; static private OperatingSystems GetCurrentOS() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return OperatingSystems.Windows; } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { return OperatingSystems.Linux; } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { return OperatingSystems.MacOSX; } throw new PlatformNotSupportedException(); } } }
35.52381
120
0.635836
[ "MIT" ]
AlecPapierniak/tye
test/Test.Infrastructure/xunit/OSSkipConditionAttribute.cs
2,240
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.MySql.Cmdlets { using static Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Extensions; /// <summary>Lists all of the available REST API operations.</summary> /// <remarks> /// [OpenAPI] Operations_List=>GET:"/providers/Microsoft.DBforMySQL/operations" /// </remarks> [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.InternalExport] [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzMySqlOperation_List")] [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IOperation))] [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Description(@"Lists all of the available REST API operations.")] [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Generated] public partial class GetAzMySqlOperation_List : global::System.Management.Automation.PSCmdlet, Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener { /// <summary>A unique id generatd for the this cmdlet when it is instantiated.</summary> private string __correlationId = System.Guid.NewGuid().ToString(); /// <summary>A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet)</summary> private global::System.Management.Automation.InvocationInfo __invocationInfo; /// <summary>A unique id generatd for the this cmdlet when ProcessRecord() is called.</summary> private string __processRecordId; /// <summary> /// The <see cref="global::System.Threading.CancellationTokenSource" /> for this operation. /// </summary> private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); /// <summary>Wait for .NET debugger to attach</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter Break { get; set; } /// <summary>The reference to the client API class.</summary> public Microsoft.Azure.PowerShell.Cmdlets.MySql.MySql Client => Microsoft.Azure.PowerShell.Cmdlets.MySql.Module.Instance.ClientAPI; /// <summary> /// The credentials, account, tenant, and subscription used for communication with Azure /// </summary> [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] [global::System.Management.Automation.ValidateNotNull] [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Azure)] public global::System.Management.Automation.PSObject DefaultProfile { get; set; } /// <summary>SendAsync Pipeline Steps to be appended to the front of the pipeline</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] [global::System.Management.Automation.ValidateNotNull] [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Runtime)] public Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; } /// <summary>SendAsync Pipeline Steps to be prepended to the front of the pipeline</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")] [global::System.Management.Automation.ValidateNotNull] [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Runtime)] public Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } /// <summary>Accessor for our copy of the InvocationInfo.</summary> public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } /// <summary> /// <see cref="IEventListener" /> cancellation delegate. Stops the cmdlet when called. /// </summary> global::System.Action Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; /// <summary><see cref="IEventListener" /> cancellation token.</summary> global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener.Token => _cancellationTokenSource.Token; /// <summary> /// The instance of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.HttpPipeline" /> that the remote call will use. /// </summary> private Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.HttpPipeline Pipeline { get; set; } /// <summary>The URI for the proxy server to use</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Runtime)] public global::System.Uri Proxy { get; set; } /// <summary>Credentials for a proxy server to use for the remote call</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")] [global::System.Management.Automation.ValidateNotNull] [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Runtime)] public global::System.Management.Automation.PSCredential ProxyCredential { get; set; } /// <summary>Use the default credentials for the proxy</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")] [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } /// <summary> /// <c>overrideOnOk</c> will be called before the regular onOk has been processed, allowing customization of what happens /// on that response. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IOperationListResult" /// /> from the remote call</param> /// <param name="returnNow">/// Determines if the rest of the onOk method should be processed, or if the method should return /// immediately (set to true to skip further processing )</param> partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IOperationListResult> response, ref global::System.Threading.Tasks.Task<bool> returnNow); /// <summary> /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) /// </summary> protected override void BeginProcessing() { Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); if (Break) { Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.AttachDebugger.Break(); } ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } /// <summary>Performs clean-up after the command execution</summary> protected override void EndProcessing() { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } /// <summary> /// Intializes a new instance of the <see cref="GetAzMySqlOperation_List" /> cmdlet class. /// </summary> public GetAzMySqlOperation_List() { } /// <summary>Handles/Dispatches events during the call to the REST service.</summary> /// <param name="id">The message id</param> /// <param name="token">The message cancellation token. When this call is cancelled, this should be <c>true</c></param> /// <param name="messageData">Detailed message data for the message event.</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the message is completed. /// </returns> async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func<Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.EventData> messageData) { using( NoSynchronizationContext ) { if (token.IsCancellationRequested) { return ; } switch ( id ) { case Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.Verbose: { WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.Warning: { WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.Information: { var data = messageData(); WriteInformation(data, new[] { data.Message }); return ; } case Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.Debug: { WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.Error: { WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); return ; } } await Microsoft.Azure.PowerShell.Cmdlets.MySql.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); if (token.IsCancellationRequested) { return ; } WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); } } /// <summary>Performs execution of the command.</summary> protected override void ProcessRecord() { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } __processRecordId = System.Guid.NewGuid().ToString(); try { // work using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token) ) { asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token); } } catch (global::System.AggregateException aggregateException) { // unroll the inner exceptions to get the root cause foreach( var innerException in aggregateException.Flatten().InnerExceptions ) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } // Write exception out to error channel. WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); } } catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } // Write exception out to error channel. WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); } finally { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletProcessRecordEnd).Wait(); } } /// <summary>Performs execution of the command, working asynchronously if required.</summary> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed. /// </returns> protected async global::System.Threading.Tasks.Task ProcessRecordAsync() { using( NoSynchronizationContext ) { await ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } await ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MySql.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); if (null != HttpPipelinePrepend) { Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); } if (null != HttpPipelineAppend) { Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); } // get the client instance try { await ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } await this.Client.OperationsList(onOk, this, Pipeline); await ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } catch (Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.UndeclaredResponseException urexception) { WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) { ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } }); } finally { await ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletProcessRecordAsyncEnd); } } } /// <summary>Interrupts currently running code within the command.</summary> protected override void StopProcessing() { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Cancel(); base.StopProcessing(); } /// <summary>a delegate that is called when the remote service returns 200 (OK).</summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IOperationListResult" /// /> from the remote call</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed. /// </returns> private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IOperationListResult> response) { using( NoSynchronizationContext ) { var _returnNow = global::System.Threading.Tasks.Task<bool>.FromResult(false); overrideOnOk(responseMessage, response, ref _returnNow); // if overrideOnOk has returned true, then return right away. if ((null != _returnNow && await _returnNow)) { return ; } // onOk - response for 200 / application/json // response should be returning an array of some kind. +Pageable // nested-array / value / <none> WriteObject((await response).Value, true); } } } }
72.511785
451
0.669948
[ "MIT" ]
Arsasana/azure-powershell
src/MySql/generated/cmdlets/GetAzMySqlOperation_List.cs
21,240
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the location-2020-11-19.normal.json service model. */ using System; using System.Collections.Generic; using System.Text; using System.Collections; using System.Threading; using System.Threading.Tasks; using Amazon.Runtime; namespace Amazon.LocationService.Model { /// <summary> /// Base class for ListRouteCalculators paginators. /// </summary> internal sealed partial class ListRouteCalculatorsPaginator : IPaginator<ListRouteCalculatorsResponse>, IListRouteCalculatorsPaginator { private readonly IAmazonLocationService _client; private readonly ListRouteCalculatorsRequest _request; private int _isPaginatorInUse = 0; /// <summary> /// Enumerable containing all full responses for the operation /// </summary> public IPaginatedEnumerable<ListRouteCalculatorsResponse> Responses => new PaginatedResponse<ListRouteCalculatorsResponse>(this); /// <summary> /// Enumerable containing all of the Entries /// </summary> public IPaginatedEnumerable<ListRouteCalculatorsResponseEntry> Entries => new PaginatedResultKeyResponse<ListRouteCalculatorsResponse, ListRouteCalculatorsResponseEntry>(this, (i) => i.Entries); internal ListRouteCalculatorsPaginator(IAmazonLocationService client, ListRouteCalculatorsRequest request) { this._client = client; this._request = request; } #if BCL IEnumerable<ListRouteCalculatorsResponse> IPaginator<ListRouteCalculatorsResponse>.Paginate() { if (Interlocked.Exchange(ref _isPaginatorInUse, 1) != 0) { throw new System.InvalidOperationException("Paginator has already been consumed and cannot be reused. Please create a new instance."); } PaginatorUtils.SetUserAgentAdditionOnRequest(_request); var nextToken = _request.NextToken; ListRouteCalculatorsResponse response; do { _request.NextToken = nextToken; response = _client.ListRouteCalculators(_request); nextToken = response.NextToken; yield return response; } while (!string.IsNullOrEmpty(nextToken)); } #endif #if AWS_ASYNC_ENUMERABLES_API async IAsyncEnumerable<ListRouteCalculatorsResponse> IPaginator<ListRouteCalculatorsResponse>.PaginateAsync(CancellationToken cancellationToken = default) { if (Interlocked.Exchange(ref _isPaginatorInUse, 1) != 0) { throw new System.InvalidOperationException("Paginator has already been consumed and cannot be reused. Please create a new instance."); } PaginatorUtils.SetUserAgentAdditionOnRequest(_request); var nextToken = _request.NextToken; ListRouteCalculatorsResponse response; do { _request.NextToken = nextToken; response = await _client.ListRouteCalculatorsAsync(_request, cancellationToken).ConfigureAwait(false); nextToken = response.NextToken; cancellationToken.ThrowIfCancellationRequested(); yield return response; } while (!string.IsNullOrEmpty(nextToken)); } #endif } }
41.268041
162
0.676992
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/LocationService/Generated/Model/_bcl45+netstandard/ListRouteCalculatorsPaginator.cs
4,003
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using DotNetCheck.Models; using Microsoft.NET.Sdk.WorkloadManifestReader; using NuGet.Versioning; using DotNetCheck.DotNet; using DotNetCheck.Solutions; namespace DotNetCheck.Checkups { public class DotNetPacksCheckup : Checkup { public DotNetPacksCheckup(string sdkVersion, Manifest.DotNetSdkPack[] requiredPacks, params string[] nugetPackageSources) : base() { SdkVersion = sdkVersion; RequiredPacks = requiredPacks; NuGetPackageSources = nugetPackageSources; dotnet = new DotNetSdk(); SdkRoot = dotnet.DotNetSdkLocation.FullName; workloadManager = new DotNetWorkloadManager(SdkRoot, SdkVersion, NuGetPackageSources); } readonly DotNetSdk dotnet; readonly DotNetWorkloadManager workloadManager; public readonly string SdkRoot; public readonly string SdkVersion; public readonly string[] NuGetPackageSources; public readonly Manifest.DotNetSdkPack[] RequiredPacks; public override IEnumerable<CheckupDependency> Dependencies => new List<CheckupDependency> { new CheckupDependency("dotnetworkloads") }; public override string Id => "dotnetpacks"; public override string Title => $".NET SDK - Packs ({SdkVersion})"; public override async Task<DiagnosticResult> Examine(SharedState history) { var sdkPacks = workloadManager.GetAllInstalledWorkloadPacks(); var missingPacks = new List<Manifest.DotNetSdkPack>(); var requiredPacks = new List<Manifest.DotNetSdkPack>(); requiredPacks.AddRange(RequiredPacks); if (history.TryGetState<WorkloadResolver.PackInfo[]>("dotnetworkloads", "required_packs", out var p) && p.Any()) requiredPacks.AddRange(p.Select(pi => new Manifest.DotNetSdkPack { Id = pi.Id, Version = pi.Version })); var uniqueRequiredPacks = requiredPacks .GroupBy(p => p.Id + p.Version.ToString()) .Select(g => g.First()); foreach (var rp in uniqueRequiredPacks) { if (!sdkPacks.Any(sp => sp.Id == rp.Id && sp.Version == rp.Version)) { ReportStatus($"{rp.Id} ({rp.Version}) not installed.", Status.Warning); missingPacks.Add(rp); } else { ReportStatus($"{rp.Id} ({rp.Version}) installed.", Status.Ok); } } if (!missingPacks.Any()) return DiagnosticResult.Ok(this); var remedies = missingPacks .Select(ms => new DotNetPackInstallSolution(SdkRoot, SdkVersion, ms, NuGetPackageSources)); return new DiagnosticResult( Status.Error, this, new Suggestion("Install Missing SDK Packs", remedies.ToArray())); } } }
30.857143
132
0.731096
[ "MIT" ]
davidortinau/dotnet-maui-check
MauiCheck/Checkups/DotNetPacksCheckup.cs
2,594
C#
// ------------------------------------------------------------------------------ // <auto-generated> // Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL) // <NameSpace>Mim.V6301</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields> // </auto-generated> // ------------------------------------------------------------------------------ namespace Mim.V6301 { using System; using System.Diagnostics; using System.Xml.Serialization; using System.Collections; using System.Xml.Schema; using System.ComponentModel; using System.IO; using System.Text; [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")] [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="urn:hl7-org:v3")] public partial class UKCT_MT144040UK01Reason3PersonalPreference { private IINPfITuuidmandatory idField; private string classCodeField; private string moodCodeField; private static System.Xml.Serialization.XmlSerializer serializer; public UKCT_MT144040UK01Reason3PersonalPreference() { this.classCodeField = "OBS"; this.moodCodeField = "EVN"; } public IINPfITuuidmandatory id { get { return this.idField; } set { this.idField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string classCode { get { return this.classCodeField; } set { this.classCodeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string moodCode { get { return this.moodCodeField; } set { this.moodCodeField = value; } } private static System.Xml.Serialization.XmlSerializer Serializer { get { if ((serializer == null)) { serializer = new System.Xml.Serialization.XmlSerializer(typeof(UKCT_MT144040UK01Reason3PersonalPreference)); } return serializer; } } #region Serialize/Deserialize /// <summary> /// Serializes current UKCT_MT144040UK01Reason3PersonalPreference object into an XML document /// </summary> /// <returns>string XML value</returns> public virtual string Serialize() { System.IO.StreamReader streamReader = null; System.IO.MemoryStream memoryStream = null; try { memoryStream = new System.IO.MemoryStream(); Serializer.Serialize(memoryStream, this); memoryStream.Seek(0, System.IO.SeekOrigin.Begin); streamReader = new System.IO.StreamReader(memoryStream); return streamReader.ReadToEnd(); } finally { if ((streamReader != null)) { streamReader.Dispose(); } if ((memoryStream != null)) { memoryStream.Dispose(); } } } /// <summary> /// Deserializes workflow markup into an UKCT_MT144040UK01Reason3PersonalPreference object /// </summary> /// <param name="xml">string workflow markup to deserialize</param> /// <param name="obj">Output UKCT_MT144040UK01Reason3PersonalPreference object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool Deserialize(string xml, out UKCT_MT144040UK01Reason3PersonalPreference obj, out System.Exception exception) { exception = null; obj = default(UKCT_MT144040UK01Reason3PersonalPreference); try { obj = Deserialize(xml); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool Deserialize(string xml, out UKCT_MT144040UK01Reason3PersonalPreference obj) { System.Exception exception = null; return Deserialize(xml, out obj, out exception); } public static UKCT_MT144040UK01Reason3PersonalPreference Deserialize(string xml) { System.IO.StringReader stringReader = null; try { stringReader = new System.IO.StringReader(xml); return ((UKCT_MT144040UK01Reason3PersonalPreference)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader)))); } finally { if ((stringReader != null)) { stringReader.Dispose(); } } } /// <summary> /// Serializes current UKCT_MT144040UK01Reason3PersonalPreference object into file /// </summary> /// <param name="fileName">full path of outupt xml file</param> /// <param name="exception">output Exception value if failed</param> /// <returns>true if can serialize and save into file; otherwise, false</returns> public virtual bool SaveToFile(string fileName, out System.Exception exception) { exception = null; try { SaveToFile(fileName); return true; } catch (System.Exception e) { exception = e; return false; } } public virtual void SaveToFile(string fileName) { System.IO.StreamWriter streamWriter = null; try { string xmlString = Serialize(); System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName); streamWriter = xmlFile.CreateText(); streamWriter.WriteLine(xmlString); streamWriter.Close(); } finally { if ((streamWriter != null)) { streamWriter.Dispose(); } } } /// <summary> /// Deserializes xml markup from file into an UKCT_MT144040UK01Reason3PersonalPreference object /// </summary> /// <param name="fileName">string xml file to load and deserialize</param> /// <param name="obj">Output UKCT_MT144040UK01Reason3PersonalPreference object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool LoadFromFile(string fileName, out UKCT_MT144040UK01Reason3PersonalPreference obj, out System.Exception exception) { exception = null; obj = default(UKCT_MT144040UK01Reason3PersonalPreference); try { obj = LoadFromFile(fileName); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool LoadFromFile(string fileName, out UKCT_MT144040UK01Reason3PersonalPreference obj) { System.Exception exception = null; return LoadFromFile(fileName, out obj, out exception); } public static UKCT_MT144040UK01Reason3PersonalPreference LoadFromFile(string fileName) { System.IO.FileStream file = null; System.IO.StreamReader sr = null; try { file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read); sr = new System.IO.StreamReader(file); string xmlString = sr.ReadToEnd(); sr.Close(); file.Close(); return Deserialize(xmlString); } finally { if ((file != null)) { file.Dispose(); } if ((sr != null)) { sr.Dispose(); } } } #endregion #region Clone method /// <summary> /// Create a clone of this UKCT_MT144040UK01Reason3PersonalPreference object /// </summary> public virtual UKCT_MT144040UK01Reason3PersonalPreference Clone() { return ((UKCT_MT144040UK01Reason3PersonalPreference)(this.MemberwiseClone())); } #endregion } }
44.489083
1,358
0.593934
[ "MIT" ]
Kusnaditjung/MimDms
src/Mim.V6301/Generated/UKCT_MT144040UK01Reason3PersonalPreference.cs
10,188
C#
namespace FSS.Omnius.Modules.Migrations.MSSQL { using System; using System.Data.Entity.Migrations; public partial class Overviewconnections : DbMigration { public override void Up() { CreateTable( "dbo.TapestryDesigner_Properties", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(), Value = c.String(), TapestryDesignerItem_Id = c.Int(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.TapestryDesigner_Items", t => t.TapestryDesignerItem_Id) .Index(t => t.TapestryDesignerItem_Id); CreateTable( "dbo.TapestryDesigner_MetablocksConnections", c => new { Id = c.Int(nullable: false, identity: true), SourceType = c.Int(nullable: false), TargetType = c.Int(nullable: false), SourceId = c.Int(), TargetId = c.Int(), TapestryDesignerMetablock_Id = c.Int(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.TapestryDesigner_Metablocks", t => t.TapestryDesignerMetablock_Id) .Index(t => t.TapestryDesignerMetablock_Id); } public override void Down() { DropForeignKey("dbo.TapestryDesigner_MetablocksConnections", "TapestryDesignerMetablock_Id", "dbo.TapestryDesigner_Metablocks"); DropForeignKey("dbo.TapestryDesigner_Properties", "TapestryDesignerItem_Id", "dbo.TapestryDesigner_Items"); DropIndex("dbo.TapestryDesigner_MetablocksConnections", new[] { "TapestryDesignerMetablock_Id" }); DropIndex("dbo.TapestryDesigner_Properties", new[] { "TapestryDesignerItem_Id" }); DropTable("dbo.TapestryDesigner_MetablocksConnections"); DropTable("dbo.TapestryDesigner_Properties"); } } }
42.54902
140
0.533641
[ "MIT" ]
simplifate/omnius
application/FSS.Omnius.Modules/Migrations/MSSQL/201601131603195_Overview-connections.cs
2,170
C#
using System; using System.Linq; namespace AmqpTestConsole { public class MessageGenerator { private readonly Random random = new Random(); public string RandomString(int length) { const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; return new string(Enumerable.Repeat(chars, length) .Select(s => s[random.Next(s.Length)]).ToArray()); } } }
25.647059
72
0.623853
[ "MIT" ]
jeroenmaes/amqp-test-console
src/MessageGenerator.cs
438
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using MailCheck.Common.Messaging.Abstractions; using MailCheck.Common.Util; using CommonContracts = MailCheck.Common.Contracts.Messaging; namespace MailCheck.Spf.Entity.Seeding.DomainCreated { internal interface ISeeder { Task SeedDomainCreated(); } internal class Seeder : ISeeder { private readonly IDomainDao _domainDao; private readonly ISqsPublisher _publisher; private readonly ISeederConfig _config; public Seeder(IDomainDao domainDao, ISqsPublisher publisher, ISeederConfig config) { _domainDao = domainDao; _publisher = publisher; _config = config; } public async Task SeedDomainCreated() { List<Domain> domains = await _domainDao.GetDomains(); List<CommonContracts.DomainCreated> domainCreateds = domains.Select(_ => new CommonContracts.DomainCreated(_.Name, _.CreatedBy, _.CreatedDate)).ToList(); int count = 0; foreach (IEnumerable<CommonContracts.DomainCreated> domainCreated in domainCreateds.Batch(10)) { List<Message> messages = domainCreated.Cast<Message>().ToList(); await _publisher.Publish(messages, _config.SnsTopicToSeedArn); Console.WriteLine($"Processed {count += messages.Count} events."); } } } }
32.673913
116
0.657352
[ "Apache-2.0" ]
ukncsc/MailCheck.Public.Spf
src/MailCheck.Spf.Entity/Seeding/DomainCreated/Seeder.cs
1,505
C#
using System; using System.IO; using System.Reflection; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using PlaywrightSharp; using PlaywrightSharp.Tests.Helpers; using PlaywrightSharp.TestServer; using PlaywrightSharp.Transport.Channels; using Xunit.Abstractions; namespace PlaywrightSharp.Tests.BaseTests { /// <summary> /// This base tests setup logging and http servers /// </summary> public class PlaywrightSharpBaseTest : IDisposable { private readonly XunitLoggerProvider _loggerProvider; private readonly ILogger<SimpleServer> _httpLogger; internal IPlaywright Playwright => PlaywrightSharpBrowserLoaderFixture.Playwright; internal string BaseDirectory { get; set; } internal IBrowserType BrowserType => Playwright[TestConstants.Product]; internal SimpleServer Server => PlaywrightSharpLoader.Server; internal SimpleServer HttpsServer => PlaywrightSharpLoader.HttpsServer; internal PlaywrightSharpBaseTest(ITestOutputHelper output) { BaseDirectory = Path.Combine(Directory.GetCurrentDirectory(), "workspace"); var dirInfo = new DirectoryInfo(BaseDirectory); if (!dirInfo.Exists) { dirInfo.Create(); } Initialize(); _loggerProvider = new XunitLoggerProvider(output); _httpLogger = TestConstants.LoggerFactory.CreateLogger<SimpleServer>(); TestConstants.LoggerFactory.AddProvider(_loggerProvider); Server.RequestReceived += Server_RequestReceived; HttpsServer.RequestReceived += Server_RequestReceived; output.WriteLine($"Running {GetDisplayName(output)}"); } private void Server_RequestReceived(object sender, RequestReceivedEventArgs e) { _httpLogger.LogInformation($"Incoming request: {e.Request.Path}"); } private static string GetDisplayName(ITestOutputHelper output) { var type = output.GetType(); var testMember = type.GetField("test", BindingFlags.Instance | BindingFlags.NonPublic); var test = (ITest)testMember.GetValue(output); return test.DisplayName; } internal void Initialize() { Server.Reset(); HttpsServer.Reset(); } internal async Task<IPage> NewPageAsync(IBrowser browser, BrowserContextOptions options = null) { await using var context = await browser.NewContextAsync(options); return await context.NewPageAsync(); } /// <inheritdoc/> public virtual void Dispose() { Server.RequestReceived -= Server_RequestReceived; HttpsServer.RequestReceived -= Server_RequestReceived; _loggerProvider.Dispose(); } } }
35.5
104
0.644869
[ "MIT" ]
KoditkarVedant/playwright-sharp
src/PlaywrightSharp.Tests/BaseTests/PlaywrightSharpBaseTest.cs
2,982
C#
#pragma warning disable 108 // new keyword hiding #pragma warning disable 114 // new keyword hiding namespace Windows.ApplicationModel { #if false || false || false || false || false || false || false [global::Uno.NotImplemented] #endif public partial struct PackageVersion { // Forced skipping of method Windows.ApplicationModel.PackageVersion.PackageVersion() // Skipping already declared field Windows.ApplicationModel.PackageVersion.Major // Skipping already declared field Windows.ApplicationModel.PackageVersion.Minor // Skipping already declared field Windows.ApplicationModel.PackageVersion.Build // Skipping already declared field Windows.ApplicationModel.PackageVersion.Revision } }
41.823529
87
0.793249
[ "Apache-2.0" ]
AbdalaMask/uno
src/Uno.UWP/Generated/3.0.0.0/Windows.ApplicationModel/PackageVersion.cs
711
C#
namespace RuleEngine.Interfaces.Rules { public interface IActionBlockRule<in T> { void Execute(T param); } public interface IFuncBlockRule<in TIn, out TOut> { TOut Execute(TIn param); } }
19.083333
53
0.633188
[ "MIT" ]
reazhaq/DynamicRule
src/RuleEngine/Interfaces/Rules/IBlockRules.cs
231
C#
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ using Xunit; namespace React.Tests.Core { public class FileSystemExtensionsTests { [Theory] [InlineData("*.txt", true)] [InlineData("foo?.js", true)] [InlineData("first\\second\\third\\*.js", true)] [InlineData("lol.js", false)] [InlineData("", false)] [InlineData("hello\\world.js", false)] public void IsGlobPattern(string input, bool expected) { Assert.Equal(expected, input.IsGlobPattern()); } } }
23.37037
66
0.66878
[ "MIT" ]
AlaminJust/React.NET
tests/React.Tests/Core/FileSystemExtensionsTest.cs
633
C#
using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using System.Windows.Threading; using ARKBreedingStats.Ark; using ARKBreedingStats.Library; using ARKBreedingStats.NamePatterns; using ARKBreedingStats.Properties; using ARKBreedingStats.species; using ARKBreedingStats.uiControls; using ARKBreedingStats.utils; namespace ARKBreedingStats { public partial class CreatureInfoInput : UserControl { public event Action<CreatureInfoInput> Add2LibraryClicked; public event Action<CreatureInfoInput> Save2LibraryClicked; public event Action<CreatureInfoInput> ParentListRequested; public event Form1.SetMessageLabelTextEventHandler SetMessageLabelText; /// <summary> /// Check for existing color id of the given region is requested. if the region is -1, all regions are requested. /// </summary> public event Action<CreatureInfoInput> ColorsChanged; public delegate void RequestCreatureDataEventHandler(CreatureInfoInput sender, bool openPatternEditor, bool updateInheritance, bool showDuplicateNameWarning, int namingPatternIndex); public event RequestCreatureDataEventHandler CreatureDataRequested; private Sex _sex; private CreatureFlags _creatureFlags; public Guid CreatureGuid; public bool ArkIdImported; private CreatureStatus _creatureStatus; public bool parentListValid; // TODO change to parameter, if set to false, show n/a in the comboBoxes private Species _selectedSpecies; private readonly ToolTip _tt; private bool _updateMaturation; private Creature[] _sameSpecies; public List<string> NamesOfAllCreatures; private string[] _ownersTribes; private byte[] _regionColorIDs; private byte[] _colorIdsAlsoPossible; private bool _tribeLock, _ownerLock; public long MotherArkId, FatherArkId; // is only used when importing creatures with set parents. these ids are set externally after the creature data is set in the info input /// <summary> /// True if creature is new, false if creature already exists /// </summary> private bool _isNewCreature; private readonly Debouncer _parentsChangedDebouncer = new Debouncer(); /// <summary> /// The pictureBox that displays the colored species dependent on the selected region colors. /// </summary> public PictureBox PbColorRegion; /// <summary> /// If false, the visualization of the colors and the image are not updated. /// </summary> public bool DontUpdateVisuals; /// <summary> /// Displays the parents and inherited stats. /// </summary> public ParentInheritance ParentInheritance; private Button[] ButtonsNamingPattern => new[] { btnGenerateUniqueName, btNamingPattern2, btNamingPattern3, btNamingPattern4, btNamingPattern5, btNamingPattern6 }; public CreatureInfoInput() { InitializeComponent(); _selectedSpecies = null; textBoxName.Text = string.Empty; parentComboBoxMother.naLabel = " - " + Loc.S("Mother") + " n/a"; parentComboBoxMother.Items.Add(" - " + Loc.S("Mother") + " n/a"); parentComboBoxFather.naLabel = " - " + Loc.S("Father") + " n/a"; parentComboBoxFather.Items.Add(" - " + Loc.S("Father") + " n/a"); parentComboBoxMother.SelectedIndex = 0; parentComboBoxFather.SelectedIndex = 0; _updateMaturation = true; _regionColorIDs = new byte[Species.ColorRegionCount]; CooldownUntil = new DateTime(2000, 1, 1); GrowingUntil = new DateTime(2000, 1, 1); NamesOfAllCreatures = new List<string>(); var namingPatternButtons = ButtonsNamingPattern; for (int bi = 0; bi < namingPatternButtons.Length; bi++) { int localIndex = bi; // apply naming pattern namingPatternButtons[bi].Click += (s, e) => { if (_selectedSpecies != null) { CreatureDataRequested?.Invoke(this, false, false, true, localIndex); } }; // open naming pattern editor namingPatternButtons[bi].MouseDown += (s, e) => { if (e.Button == MouseButtons.Right) { CreatureDataRequested?.Invoke(this, true, false, false, localIndex); } }; } // set tooltips _tt = new ToolTip(); _tt.SetToolTip(LbArkId, "The real Ark id of the creature, not directly shown in game.\nEach creature has its id stored in two 32 bit integers (id1, id2), this value is created by (id1 << 32) | id2"); _tt.SetToolTip(LbArkIdIngame, "The id of the creature like it is shown in game.\nIt is created by the game by two 32 bit integers which are concatenated as strings."); regionColorChooser1.RegionColorChosen += UpdateRegionColorImage; } /// <summary> /// Updates the displayed colors of the creature. /// </summary> private void UpdateRegionColorImage() { ParentInheritance?.UpdateColors(RegionColors); ColorsChanged?.Invoke(this); PbColorRegion?.SetImageAndDisposeOld(CreatureColored.GetColoredCreature(RegionColors, _selectedSpecies, regionColorChooser1.ColorRegionsUseds, 256, onlyImage: true, creatureSex: CreatureSex)); } internal void UpdateParentInheritances(Creature creature) { if (ParentInheritance == null) return; SetCreatureData(creature); ParentInheritance.SetCreatures(creature, Mother, Father); } private void buttonAdd2Library_Click(object sender, EventArgs e) { Add2LibraryClicked?.Invoke(this); } private void buttonSaveChanges_Click(object sender, EventArgs e) { Save2LibraryClicked?.Invoke(this); } public string CreatureName { get => textBoxName.Text; set { textBoxName.Text = value; textBoxName.BackColor = SystemColors.Window; } } public string CreatureOwner { get => textBoxOwner.Text; set => textBoxOwner.Text = value; } public string CreatureTribe { get => textBoxTribe.Text; set => textBoxTribe.Text = value; } public Sex CreatureSex { get => _sex; set { _sex = value; buttonSex.Text = Utils.SexSymbol(_sex); buttonSex.BackColor = Utils.SexColor(_sex); _tt.SetToolTip(buttonSex, $"{Loc.S("Sex")}: {Loc.S(_sex.ToString())}"); cbNeutered.Text = Loc.S(_sex == Sex.Female ? "Spayed" : "Neutered"); if (value == Sex.Female) { _creatureFlags |= CreatureFlags.Female; _creatureFlags &= ~CreatureFlags.Male; } else if (value == Sex.Male) { _creatureFlags |= CreatureFlags.Male; _creatureFlags &= ~CreatureFlags.Female; } } } public CreatureStatus CreatureStatus { get => _creatureStatus; set { _creatureStatus = value; buttonStatus.Text = Utils.StatusSymbol(_creatureStatus); _tt.SetToolTip(buttonStatus, $"{Loc.S("Status")}: {Utils.StatusText(_creatureStatus)}"); } } public string CreatureServer { get => cbServer.Text; set => cbServer.Text = value; } public Creature Mother { get => parentComboBoxMother.SelectedParent; set { parentComboBoxMother.PreselectedCreatureGuid = value?.guid ?? Guid.Empty; MotherArkId = 0; } } public Creature Father { get => parentComboBoxFather.SelectedParent; set { parentComboBoxFather.PreselectedCreatureGuid = value?.guid ?? Guid.Empty; FatherArkId = 0; } } public string CreatureNote { get => textBoxNote.Text; set => textBoxNote.Text = value; } private void buttonSex_Click(object sender, EventArgs e) { CreatureSex = Utils.NextSex(_sex); } private void buttonStatus_Click(object sender, EventArgs e) { CreatureStatus = Utils.NextStatus(_creatureStatus); } public Creature[] CreaturesOfSameSpecies { set => _sameSpecies = value; } public List<Creature>[] Parents { set { if (value == null) return; parentComboBoxMother.ParentList = value[0]; parentComboBoxFather.ParentList = value[1]; } } public List<int>[] ParentsSimilarities { set { if (value == null) return; parentComboBoxMother.parentsSimilarity = value[0]; parentComboBoxFather.parentsSimilarity = value[1]; } } public bool ButtonEnabled { set { btAdd2Library.Enabled = value; SetAdd2LibColor(value); } } public bool ShowSaveButton { set { btSaveChanges.Visible = value; btAdd2Library.Size = new Size((value ? 120 : 250), 37); btAdd2Library.Location = new Point(value ? 136 : 6, btAdd2Library.Location.Y); } } private void groupBox1_Enter(object sender, EventArgs e) { if (!parentListValid) ParentListRequested?.Invoke(this); } //private void dhmsInputGrown_ValueChanged(object sender, TimeSpan ts) //{ // if (_updateMaturation && _selectedSpecies != null) // { // _updateMaturation = false; // double maturation = 0; // if (_selectedSpecies.breeding != null && _selectedSpecies.breeding.maturationTimeAdjusted > 0) // { // maturation = 1 - dhmsInputGrown.Timespan.TotalSeconds / _selectedSpecies.breeding.maturationTimeAdjusted; // if (maturation < 0) maturation = 0; // if (maturation > 1) maturation = 1; // } // nudMaturation.Value = (decimal)maturation * 100; // _updateMaturation = true; // } //} private void nudMaturation_ValueChanged(object sender, EventArgs e) { if (_updateMaturation) { _updateMaturation = false; if (_selectedSpecies.breeding != null) { dhmsInputGrown.Timespan = new TimeSpan(0, 0, (int)(_selectedSpecies.breeding.maturationTimeAdjusted * (1 - (double)nudMaturation.Value / 100))); dhmsInputGrown.changed = true; } else dhmsInputGrown.Timespan = TimeSpan.Zero; _updateMaturation = true; } } /// <summary> /// DateTime when the cooldown of the creature is finished. /// </summary> public DateTime? CooldownUntil { get => dhmsInputCooldown.changed ? DateTime.Now.Add(dhmsInputCooldown.Timespan) : default(DateTime?); set { if (value.HasValue) { dhmsInputCooldown.Timespan = value.Value - DateTime.Now; } } } /// <summary> /// DateTime when the creature is mature. /// </summary> public DateTime? GrowingUntil { get => dhmsInputGrown.changed ? DateTime.Now.Add(dhmsInputGrown.Timespan) : default(DateTime?); set { if (value.HasValue) dhmsInputGrown.Timespan = value.Value - DateTime.Now; } } public void SetTimersToChanged() { dhmsInputCooldown.changed = true; dhmsInputGrown.changed = true; } public string[] AutocompleteOwnerList { set { var l = new AutoCompleteStringCollection(); l.AddRange(value); textBoxOwner.AutoCompleteCustomSource = l; } } public string[] AutocompleteTribeList { set { var l = new AutoCompleteStringCollection(); l.AddRange(value); textBoxTribe.AutoCompleteCustomSource = l; } } /// <summary> /// List of tribes of owners. /// </summary> public string[] OwnersTribes { set => _ownersTribes = value; } public string[] ServersList { set { if (value == null) return; var l = new AutoCompleteStringCollection(); l.AddRange(value); cbServer.AutoCompleteCustomSource = l; cbServer.Items.Clear(); cbServer.Items.AddRange(value); } } /// <summary> /// DateTime when the creature was domesticated. /// </summary> public DateTime? DomesticatedAt { get => dateTimePickerDomesticatedAt.Value; set { if (value.HasValue) dateTimePickerDomesticatedAt.Value = value.Value < dateTimePickerDomesticatedAt.MinDate ? dateTimePickerDomesticatedAt.MinDate : value.Value; else dateTimePickerDomesticatedAt.Value = dateTimePickerDomesticatedAt.MinDate; } } /// <summary> /// Flags of the creature, e.g. if the creature is neutered. /// </summary> public CreatureFlags CreatureFlags { get { if (cbNeutered.Checked) _creatureFlags |= CreatureFlags.Neutered; else _creatureFlags &= ~CreatureFlags.Neutered; if (CbMutagen.Checked) _creatureFlags |= CreatureFlags.MutagenApplied; else _creatureFlags &= ~CreatureFlags.MutagenApplied; return _creatureFlags; } set { _creatureFlags = value; cbNeutered.Checked = _creatureFlags.HasFlag(CreatureFlags.Neutered); CbMutagen.Checked = _creatureFlags.HasFlag(CreatureFlags.MutagenApplied); } } public int MutationCounterMother { get => (int)nudMutationsMother.Value; set => nudMutationsMother.ValueSave = value; } public int MutationCounterFather { get => (int)nudMutationsFather.Value; set => nudMutationsFather.ValueSave = value; } public void SetArkId(long arkId, bool arkIdImported) { ArkIdImported = arkIdImported; if (arkIdImported) { TbArkIdIngame.Text = Utils.ConvertImportedArkIdToIngameVisualization(arkId); TbArkId.Text = arkId.ToString(); } else { TbArkIdIngame.Text = arkId.ToString(); } // if the creature is imported, the id is considered to be correct and the user should not change it. TbArkIdIngame.ReadOnly = arkIdImported; LbArkId.Visible = arkIdImported; TbArkId.Visible = arkIdImported; } public long ArkId { get { long.TryParse(ArkIdImported ? TbArkId.Text : TbArkIdIngame.Text, out long result); return result; } } public byte[] RegionColors { get => DontUpdateVisuals ? _regionColorIDs : regionColorChooser1.ColorIds; set { if (_selectedSpecies == null) return; _regionColorIDs = (byte[])value?.Clone() ?? new byte[Species.ColorRegionCount]; if (DontUpdateVisuals) return; regionColorChooser1.SetSpecies(_selectedSpecies, _regionColorIDs); UpdateRegionColorImage(); } } public byte[] ColorIdsAlsoPossible { get { var arr = DontUpdateVisuals ? _colorIdsAlsoPossible : regionColorChooser1.ColorIdsAlsoPossible; if (arr == null) return null; // if array is empty, return null var isEmpty = true; for (int i = 0; i < arr.Length; i++) { if (arr[i] != 0) { isEmpty = false; break; } } return isEmpty ? null : arr; } set { if (_selectedSpecies == null) return; _colorIdsAlsoPossible = (byte[])value?.Clone() ?? new byte[Species.ColorRegionCount]; if (DontUpdateVisuals) return; regionColorChooser1.ColorIdsAlsoPossible = _colorIdsAlsoPossible; } } public Species SelectedSpecies { set { _selectedSpecies = value; if (DontUpdateVisuals) return; bool breedingPossible = _selectedSpecies.breeding != null; dhmsInputCooldown.Visible = breedingPossible; dhmsInputGrown.Visible = breedingPossible; nudMaturation.Visible = breedingPossible; lbGrownIn.Visible = breedingPossible; lbCooldown.Visible = breedingPossible; lbMaturationPerc.Visible = breedingPossible; if (!breedingPossible) { nudMaturation.Value = 0; dhmsInputGrown.Timespan = TimeSpan.Zero; dhmsInputCooldown.Timespan = TimeSpan.Zero; } RegionColors = null; } } private void parentComboBox_SelectedIndexChanged(object sender, EventArgs e) { UpdateMutations(); CalculateNewMutations(); if (ParentInheritance != null) _parentsChangedDebouncer.Debounce(100, ParentsChanged, Dispatcher.CurrentDispatcher); } private void ParentsChanged() => CreatureDataRequested?.Invoke(this, false, true, false, 0); /// <summary> /// It's assumed that if a parent has a higher mutation-count than the current set one, the set one is not valid and will be updated. /// </summary> private void UpdateMutations() { int? mutationsMo = parentComboBoxMother.SelectedParent?.Mutations; int? mutationsFa = parentComboBoxFather.SelectedParent?.Mutations; if (mutationsMo.HasValue && nudMutationsMother.Value > 0 && mutationsMo.Value > nudMutationsMother.Value) { nudMutationsMother.Value = mutationsMo.Value; } if (mutationsFa.HasValue && nudMutationsFather.Value > 0 && mutationsFa.Value > nudMutationsFather.Value) { nudMutationsFather.Value = mutationsFa.Value; } } private void btNamingPatternEditor_Click(object sender, EventArgs e) { CreatureDataRequested?.Invoke(this, true, false, false, 0); } /// <summary> /// Generates a creature name with a given pattern /// </summary> public void GenerateCreatureName(Creature creature, int[] speciesTopLevels, int[] speciesLowestLevels, Dictionary<string, string> customReplacings, bool showDuplicateNameWarning, int namingPatternIndex) { SetCreatureData(creature); CreatureName = NamePattern.GenerateCreatureName(creature, _sameSpecies, speciesTopLevels, speciesLowestLevels, customReplacings, showDuplicateNameWarning, namingPatternIndex, false); if (CreatureName.Length > 24) SetMessageLabelText?.Invoke("The generated name is longer than 24 characters, the name will look like this in game:\n" + CreatureName.Substring(0, 24), MessageBoxIcon.Error); } public void OpenNamePatternEditor(Creature creature, int[] speciesTopLevels, int[] speciesLowestLevels, Dictionary<string, string> customReplacings, int namingPatternIndex, Action<PatternEditor> reloadCallback) { if (!parentListValid) ParentListRequested?.Invoke(this); using (var pe = new PatternEditor(creature, _sameSpecies, speciesTopLevels, speciesLowestLevels, customReplacings, namingPatternIndex, reloadCallback)) { if (pe.ShowDialog() == DialogResult.OK) { var namingPatterns = Settings.Default.NamingPatterns ?? new string[6]; namingPatterns[namingPatternIndex] = pe.NamePattern; Settings.Default.NamingPatterns = namingPatterns; Settings.Default.PatternNameToClipboardAfterManualApplication = pe.PatternNameToClipboardAfterManualApplication; } (Settings.Default.PatternEditorFormRectangle, _) = Utils.GetWindowRectangle(pe); Settings.Default.PatternEditorSplitterDistance = pe.SplitterDistance; } } /// <summary> /// Sets the data of the given creature to the values of the controls. /// </summary> public void SetCreatureData(Creature cr) { cr.name = CreatureName; cr.sex = _sex; cr.owner = CreatureOwner; cr.tribe = CreatureTribe; cr.server = CreatureServer; cr.note = CreatureNote; cr.flags = CreatureFlags; cr.Status = CreatureStatus; cr.Mother = Mother; cr.Father = Father; cr.mutationsMaternal = MutationCounterMother; cr.mutationsPaternal = MutationCounterFather; cr.colors = RegionColors; cr.ColorIdsAlsoPossible = ColorIdsAlsoPossible; cr.cooldownUntil = CooldownUntil; cr.growingUntil = GrowingUntil; cr.domesticatedAt = DomesticatedAt; cr.ArkId = ArkId; cr.InitializeArkInGame(); } private void textBoxOwner_Leave(object sender, EventArgs e) { // if tribe is not yet given and player has a given tribe, set tribe if (textBoxTribe.Text.Length == 0) { int i = textBoxOwner.AutoCompleteCustomSource.IndexOf(textBoxOwner.Text); if (i >= 0 && i < _ownersTribes.Length) { textBoxTribe.Text = _ownersTribes[i]; } } } /// <summary> /// If true the OCR and import exported methods will not change the owner field. /// </summary> public bool OwnerLock { get => _ownerLock; set { _ownerLock = value; textBoxOwner.BackColor = value ? Color.LightGray : SystemColors.Window; } } private bool _lockServer; /// <summary> /// If true the importing will not change the server field. /// </summary> public bool LockServer { get => _lockServer; set { _lockServer = value; cbServer.BackColor = value ? Color.LightGray : SystemColors.Window; } } /// <summary> /// If true the OCR and import exported methods will not change the tribe field. /// </summary> public bool TribeLock { get => _tribeLock; set { _tribeLock = value; textBoxTribe.BackColor = value ? Color.LightGray : SystemColors.Window; } } /// <summary> /// If set to true, it's assumed the creature is already existing. /// </summary> public bool UpdateExistingCreature { set { btAdd2Library.Text = value ? Loc.S("btUpdateLibraryCreature") : Loc.S("btAdd2Library"); _isNewCreature = !value; SetAdd2LibColor(btAdd2Library.Enabled); } } /// <summary> /// Timestamp when the creature was added to the library. Only relevant when creatures are already have been added and are edited. /// </summary> public DateTime? AddedToLibraryAt { get; internal set; } private void SetAdd2LibColor(bool buttonEnabled) { btAdd2Library.BackColor = !buttonEnabled ? SystemColors.Control : _isNewCreature ? Color.LightGreen : Color.LightSkyBlue; } private void lblOwner_Click(object sender, EventArgs e) => OwnerLock = !OwnerLock; private void lbServer_Click(object sender, EventArgs e) => LockServer = !LockServer; private void lblName_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(textBoxName.Text)) Clipboard.SetText(textBoxName.Text); } private void btClearColors_Click(object sender, EventArgs e) { if (ModifierKeys == (Keys.Control | Keys.Shift)) regionColorChooser1.RandomColors(); else if ((ModifierKeys & Keys.Control) != 0) regionColorChooser1.RandomNaturalColors(_selectedSpecies); else ClearColors(); } private void ClearColors() { regionColorChooser1.Clear(); } private void lblTribe_Click(object sender, EventArgs e) { TribeLock = !TribeLock; } private void textBoxName_TextChanged(object sender, EventArgs e) { // feedback if name already exists if (!string.IsNullOrEmpty(textBoxName.Text) && NamesOfAllCreatures != null && NamesOfAllCreatures.Contains(textBoxName.Text)) { textBoxName.BackColor = Color.Khaki; } else { textBoxName.BackColor = SystemColors.Window; } } private void CalculateNewMutations() { int newMutations = 0; if (parentComboBoxMother.SelectedParent != null) newMutations += NewMutations(parentComboBoxMother.SelectedParent.Mutations, (int)nudMutationsMother.Value); if (parentComboBoxFather.SelectedParent != null) newMutations += NewMutations(parentComboBoxFather.SelectedParent.Mutations, (int)nudMutationsFather.Value); int NewMutations(int mutationCountParent, int mutationCountChild) { var newMutationsFromParent = mutationCountChild - mutationCountParent; if (newMutationsFromParent > 0 && newMutationsFromParent <= GameConstants.MutationRolls) return mutationCountChild - mutationCountParent; return 0; } lbNewMutations.Text = $"+{newMutations} mut"; lbNewMutations.BackColor = newMutations != 0 ? Utils.MutationColor : SystemColors.Control; } private void NudMutations_ValueChanged(object sender, EventArgs e) { CalculateNewMutations(); } private void BtSaveOTSPreset_Click(object sender, EventArgs e) { Settings.Default.DefaultOwnerName = CreatureOwner; Settings.Default.DefaultTribeName = CreatureTribe; Settings.Default.DefaultServerName = CreatureServer; } private void BtApplyOTSPreset_Click(object sender, EventArgs e) { CreatureOwner = Settings.Default.DefaultOwnerName; CreatureTribe = Settings.Default.DefaultTribeName; CreatureServer = Settings.Default.DefaultServerName; } /// <summary> /// Sets the background of the naming pattern buttons to indicate if they contain a pattern or are empty. /// </summary> internal void SetNamePatternButtons(string[] patterns) { if (patterns == null) return; var namingPatternButtons = ButtonsNamingPattern; var l = Math.Min(namingPatternButtons.Length, patterns.Length); for (int i = 0; i < namingPatternButtons.Length; i++) { namingPatternButtons[i].BackColor = (patterns?.Length ?? 0) > i && !string.IsNullOrWhiteSpace(patterns[i]) ? Color.FromArgb(150, 110, 255, 104) : Color.Transparent; } } internal void Clear(bool keepGeneralInfo = false) { textBoxName.Clear(); Mother = null; Father = null; MotherArkId = 0; FatherArkId = 0; parentComboBoxMother.Clear(); parentComboBoxFather.Clear(); textBoxNote.Clear(); CooldownUntil = DateTime.Now; GrowingUntil = DateTime.Now; MutationCounterMother = 0; MutationCounterFather = 0; CreatureSex = Sex.Unknown; CreatureFlags = CreatureFlags.None; ClearColors(); CreatureStatus = CreatureStatus.Available; ParentInheritance?.SetCreatures(); SetRegionColorsExisting(); if (!keepGeneralInfo) { textBoxOwner.Clear(); } } public void SetLocalizations() { Loc.ControlText(gbCreatureInfo); Loc.ControlText(lbName, "Name", _tt); Loc.ControlText(lbOwner, "Owner", _tt); Loc.ControlText(lbTribe, "Tribe", _tt); Loc.ControlText(lbServer, "Server", _tt); Loc.ControlText(lbMother, "Mother"); Loc.ControlText(lbFather, "Father"); Loc.ControlText(lbNote, "Note"); Loc.ControlText(lbCooldown, "cooldown"); Loc.ControlText(lbGrownIn, "grownIn"); lbMaturationPerc.Text = $"{Loc.S("Maturation")} [%]"; Loc.ControlText(lbMutations, "Mutations"); Loc.ControlText(lbSex, "Sex"); Loc.ControlText(cbNeutered, _sex == Sex.Female ? "Spayed" : "Neutered"); Loc.ControlText(lbStatus, "Status"); Loc.ControlText(btClearColors, "clearColors"); _tt.SetToolTip(btClearColors, Loc.S("clearColors") + "\n" + Loc.S("holdCtrlForRandomColors")); Loc.ControlText(btSaveChanges); Loc.ControlText(btAdd2Library); //tooltips Loc.SetToolTip(buttonSex, "Sex", _tt); Loc.SetToolTip(buttonStatus, "Status", _tt); Loc.SetToolTip(dateTimePickerDomesticatedAt, "domesticatedAt", _tt); Loc.SetToolTip(nudMutationsMother, "mutationCounter", _tt); Loc.SetToolTip(nudMutationsFather, "mutationCounter", _tt); Loc.ControlText(BtApplyOTSPreset, _tt); Loc.ControlText(BtSaveOTSPreset, _tt); var namingPatternButtons = new List<Button> { btnGenerateUniqueName, btNamingPattern2, btNamingPattern3, btNamingPattern4, btNamingPattern5, btNamingPattern6 }; for (int bi = 0; bi < namingPatternButtons.Count; bi++) _tt.SetToolTip(namingPatternButtons[bi], Loc.S("btnGenerateUniqueNameTT", false)); } internal (bool newInRegion, bool newInSpecies) SetRegionColorsExisting(CreatureCollection.ColorExisting[] colorAlreadyAvailable = null) { regionColorChooser1.SetRegionColorsExisting(colorAlreadyAvailable); LbColorNewInRegion.Visible = regionColorChooser1.ColorNewInRegion; LbColorNewInSpecies.Visible = regionColorChooser1.ColorNewInSpecies; return (regionColorChooser1.ColorNewInRegion, regionColorChooser1.ColorNewInSpecies); } } }
37.688562
218
0.563929
[ "MIT" ]
PiTi2k5/ARKStatsExtractor
ARKBreedingStats/CreatureInfoInput.cs
33,281
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 ShardCalculator.Properties { 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", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// 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("ShardCalculator.Properties.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; } } } }
43.640625
181
0.614393
[ "Apache-2.0" ]
Sirhic/ShardCalculator
Properties/Resources.Designer.cs
2,795
C#
namespace AzureMapsControl.Components.Tests.Layers { using System.Collections.Generic; using AzureMapsControl.Components.Layers; using AzureMapsControl.Components.Tests.Json; using Xunit; public class LayerOptionsJsonConverterTests : JsonConverterTests<LayerOptions> { #region BubbleLayerOptions public static object BubbleLayerOptions = new BubbleLayerOptions { Blur = new Components.Atlas.ExpressionOrNumber(1), Color = new Components.Atlas.ExpressionOrString("color"), Filter = new Components.Atlas.ExpressionOrString("filter"), MaxZoom = 2, MinZoom = 3, Opacity = new Components.Atlas.ExpressionOrNumber(4), PitchAlignment = Components.Atlas.PitchAlignment.Auto, Radius = new Components.Atlas.ExpressionOrNumber(5), Source = "source", SourceLayer = "sourceLayer", StrokeColor = new Components.Atlas.ExpressionOrString("strokeColor"), StrokeOpacity = new Components.Atlas.ExpressionOrNumber(6), StrokeWidth = new Components.Atlas.ExpressionOrNumber(7), Visible = true }; public static object BubbleLayerOptionsExpectedJson = "{" + "\"filter\":\"filter\"" + ",\"maxZoom\":2" + ",\"minZoom\":3" + ",\"visible\":true" + ",\"source\":\"source\"" + ",\"sourceLayer\":\"sourceLayer\"" + ",\"blur\":1" + ",\"color\":\"color\"" + ",\"opacity\":4" + ",\"pitchAlignment\":\"auto\"" + ",\"radius\":5" + ",\"strokeColor\":\"strokeColor\"" + ",\"strokeOpacity\":6" + ",\"strokeWidth\":7" + "}"; #endregion #region HeatmapLayerOptions public static object HeatmapLayerOptions = new HeatmapLayerOptions { Color = new Components.Atlas.ExpressionOrString("color"), Filter = new Components.Atlas.ExpressionOrString("filter"), Intensity = new Components.Atlas.ExpressionOrNumber(1), MaxZoom = 2, MinZoom = 3, Opacity = new Components.Atlas.ExpressionOrNumber(4), Radius = new Components.Atlas.ExpressionOrNumber(5), Source = "source", SourceLayer = "sourceLayer", Visible = true, Weight = new Components.Atlas.ExpressionOrNumber(6) }; public static object HeatmapLayerOptionsExpectedJson = "{" + "\"filter\":\"filter\"" + ",\"maxZoom\":2" + ",\"minZoom\":3" + ",\"visible\":true" + ",\"source\":\"source\"" + ",\"sourceLayer\":\"sourceLayer\"" + ",\"color\":\"color\"" + ",\"intensity\":1" + ",\"opacity\":4" + ",\"radius\":5" + ",\"weight\":6" + "}"; #endregion #region ImageLayerOptions public static object ImageLayerOptions = new ImageLayerOptions("url", new[] { new Components.Atlas.Position(1,2), new Components.Atlas.Position(12,13), }) { Contrast = 3, FadeDuration = 4, Filter = new Components.Atlas.ExpressionOrString("filter"), HueRotation = 5, MaxBrightness = 6, MinBrightness = 7, MaxZoom = 8, MinZoom = 9, Opacity = 10, Saturation = 11, Visible = true }; public static object ImageLayerOptionsExpectedJson = "{" + "\"filter\":\"filter\"" + ",\"maxZoom\":8" + ",\"minZoom\":9" + ",\"visible\":true" + ",\"contrast\":3" + ",\"fadeDuration\":4" + ",\"hueRotation\":5" + ",\"maxBrightness\":6" + ",\"minBrightness\":7" + ",\"opacity\":10" + ",\"saturation\":11" + ",\"url\":\"url\"" + ",\"coordinates\":[[1,2],[12,13]]" + "}"; #endregion #region HeatmapLayerOptions public static object PolygonExtrusionLayerOptions = new PolygonExtrusionLayerOptions { Base = new Components.Atlas.ExpressionOrNumber(1), FillColor = new Components.Atlas.ExpressionOrString("fillColor"), FillOpacity = 2, FillPattern = "fillPattern", Filter = new Components.Atlas.ExpressionOrString("filter"), Height = new Components.Atlas.ExpressionOrNumber(3), MaxZoom = 4, MinZoom = 5, Source = "source", SourceLayer = "sourceLayer", Translate = new Components.Atlas.Pixel(6, 7), TranslateAnchor = Components.Atlas.PitchAlignment.Auto, VerticalGradient = true, Visible = true }; public static object PolygonExtrusionLayerOptionsExpectedJson = "{" + "\"filter\":\"filter\"" + ",\"maxZoom\":4" + ",\"minZoom\":5" + ",\"visible\":true" + ",\"source\":\"source\"" + ",\"sourceLayer\":\"sourceLayer\"" + ",\"base\":1" + ",\"fillColor\":\"fillColor\"" + ",\"fillOpacity\":2" + ",\"fillPattern\":\"fillPattern\"" + ",\"height\":3" + ",\"translate\":[6,7]" + ",\"translateAnchor\":\"auto\"" + ",\"verticalGradient\":true" + "}"; #endregion #region SourceLayerOptions public static object SymbolLayerOptions = new SymbolLayerOptions { Filter = new Components.Atlas.ExpressionOrString("filter"), IconOptions = new IconOptions { AllowOverlap = true }, LineSpacing = new Components.Atlas.ExpressionOrNumber(1), MaxZoom = 2, MinZoom = 3, Placement = SymbolLayerPlacement.Line, Source = "source", SourceLayer = "sourceLayer", TextOptions = new TextOptions { AllowOverlap = true }, Visible = true }; public static object SymbolLayerOptionsExpectedJson = "{" + "\"filter\":\"filter\"" + ",\"maxZoom\":2" + ",\"minZoom\":3" + ",\"visible\":true" + ",\"source\":\"source\"" + ",\"sourceLayer\":\"sourceLayer\"" + ",\"iconOptions\":{" + "\"allowOverlap\":true" + "}" + ",\"lineSpacing\":1" + ",\"placement\":\"line\"" + ",\"textOptions\":{" + "\"allowOverlap\":true" + "}" + "}"; #endregion #region TileLayerOptions public static object TileLayerOptions = new TileLayerOptions { Bounds = new Components.Atlas.BoundingBox(1, 2, 3, 4), Contrast = 5, FadeDuration = 6, Filter = new Components.Atlas.ExpressionOrString("filter"), HueRotation = 7, IsTMS = true, MaxBrightness = 8, MaxSourceZoom = 9, MaxZoom = 10, MinBrightness = 11, MinSourceZoom = 12, MinZoom = 13, Opacity = 14, Saturation = 15, Subdomains = new[] { "subdomains" }, TileSize = 16, TileUrl = "tileUrl", Visible = true }; public static object TileLayerOptionsExpectedJson = "{" + "\"filter\":\"filter\"" + ",\"maxZoom\":10" + ",\"minZoom\":13" + ",\"visible\":true" + ",\"bounds\":[1,2,3,4]" + ",\"contrast\":5" + ",\"fadeDuration\":6" + ",\"hueRotation\":7" + ",\"isTMS\":true" + ",\"maxBrightness\":8" + ",\"maxSourceZoom\":9" + ",\"minBrightness\":11" + ",\"minSourceZoom\":12" + ",\"opacity\":14" + ",\"saturation\":15" + ",\"subdomains\":[\"subdomains\"]" + ",\"tileSize\":16" + ",\"tileUrl\":\"tileUrl\"" + "}"; #endregion #region Member Data public static IEnumerable<object[]> OptionsWithExpectedJson => new List<object[]> { new object[] {BubbleLayerOptions, BubbleLayerOptionsExpectedJson}, new object[] {HeatmapLayerOptions, HeatmapLayerOptionsExpectedJson}, new object[] {ImageLayerOptions, ImageLayerOptionsExpectedJson}, new object[] {PolygonExtrusionLayerOptions, PolygonExtrusionLayerOptionsExpectedJson}, new object[] {SymbolLayerOptions, SymbolLayerOptionsExpectedJson}, new object[] {TileLayerOptions, TileLayerOptionsExpectedJson} }; #endregion public LayerOptionsJsonConverterTests() : base(new LayerOptionsJsonConverter()) { } [Theory] [MemberData(nameof(OptionsWithExpectedJson))] public void Should_Write(LayerOptions options, string expectedJson) => TestAndAssertWrite(options, expectedJson); [Fact] public void Should_WriteNull() => TestAndAssertWrite(null, "null"); } }
37.457692
121
0.488859
[ "MIT" ]
ADefWebserver/AzureMapsControl.Components
tests/AzureMapsControl.Components.Tests/Layers/LayerOptions.cs
9,741
C#
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; using System.Linq; using CodeProbe; using CodeProbe.Sensing; using CodeProbe.Reporting; using Test.CodeProbe.utility; using System.Threading; using CodeProbe.Reporting.Reporters; using CodeProbe.Reporting.Statistics; using stat = CodeProbe.Reporting.Statistics; using CodeProbe.Reporting.Samplers; namespace Test.CodeProbe { public static class TestExtension { public static void Sample(this ProbeManager ext, string filter, AbstractSampler sampler) { foreach (AbstractProbe item in ext.MatchFilter(filter)) { sampler.Sample(item); } } } [TestClass] public class ProbeManagerTest { public ProbeManagerTest() { ProbeManager.Init(); } /// <summary> /// Clears all the current probes and prepare a set of common probes, simulating a standard sensing. /// 1 gauge -> 1 /// 1 histogram -> 1 /// 1 counter -> +1 /// 1 timer -> 100ms /// 1 meter -> 1/100ms /// </summary> [TestInitialize] public void SetUp() { ProbeManager.Ask().Clear(".*"); ProbeManager.Ask().Gauge("gauge_test", () => 1); ProbeManager.Ask().Histogram("histogram_test").Update(1); ProbeManager.Ask().Counter("counter_test").Increment(); for (int i = 0; i < 10; i++) { ProbeManager.Ask().Timer("test_timer").Time(() => Thread.Sleep(100)); ProbeManager.Ask().Meter("meter_test").Mark(); } } /// <summary> /// Perform a report iteration using a json reporter /// </summary> [TestCategory("Reporting")] [TestMethod] public void JsonReporterTest() { AbstractSampler sp = new BasicSampler("test", new HashSet<AbstractProbeStatistic>() { new stat.Gauge.ConstantStatistic(), new stat.Counter.ConstantStatistic() , new stat.Meter.ConstantStatistic() , new stat.Histogram.LinearMinStatistic(), new stat.Histogram.LinearMaxStatistic(), new stat.Histogram.LinearAvgStatistic() , new stat.Timer.ConstantRatioStatistic(), new stat.Timer.LinearMinStatistic(), new stat.Timer.LinearMaxStatistic(), new stat.Timer.LinearAvgStatistic() } ); JsonReporter sm = new JsonReporter("test",sp, @"..\..\test\test.json"); sm.Start(); sp.Begin(); foreach (AbstractProbe item in ProbeManager.Ask().MatchFilter(".*")) { sp.Sample(item); } sp.Complete(); sm.Stop(); } /// <summary> /// Verify fitering cababilities of the ProbeManager. /// starts with a set of probes, add and remove /// </summary> [TestCategory("Reporting")] [TestMethod] public void RegisterProbes() { DumperSampler tmp = new DumperSampler(); ProbeManager.Ask().Clear(".*"); string[] names = new string[] {"prova.gauge","prova.counter","prova.meter","prova.histogram" ,"prova.timer"}; ProbeManager.Ask().Gauge(names[0], () => 10); ProbeManager.Ask().Counter(names[1]); ProbeManager.Ask().Meter(names[2]); ProbeManager.Ask().Histogram(names[3], new SlidingWindowReservoir<IComparable>(10)); ProbeManager.Ask().Timer(names[4], new SlidingWindowReservoir<long>(10)); ProbeManager.Ask().Sample("^prova",tmp); CollectionAssert.AreEquivalent(names, tmp.NameDump); AbstractProbe probe; ProbeManager.Ask().Unregister(names[1],out probe); Assert.IsInstanceOfType(probe,typeof(CounterProbe)); tmp = new DumperSampler(); ProbeManager.Ask().Sample("^prova", tmp); CollectionAssert.AreEquivalent(names.Where((val,id)=>id!=1).ToList(), tmp.NameDump); } /// <summary> /// Verify fitering cababilities of the ProbeManager. /// starts with a set of probes, add and remove. Test more regex filters /// </summary> [TestCategory("Reporting")] [TestMethod] public void FilterProbes() { ProbeManager.Ask().Clear(".*"); string[] names = new string[] { "prova.gauge", "test.counter", "prova.meter", "test.histogram", "prova.counter" }; ProbeManager.Ask().Gauge(names[0], () => 10); ProbeManager.Ask().Counter(names[1]); ProbeManager.Ask().Meter(names[2]); ProbeManager.Ask().Histogram(names[3], new SlidingWindowReservoir<IComparable>(10)); ProbeManager.Ask().Timer(names[4], new SlidingWindowReservoir<long>(10)); DumperSampler tmp = new DumperSampler(); ProbeManager.Ask().Sample("prova", tmp); CollectionAssert.AreEquivalent(new string[] { "prova.gauge", "prova.meter", "prova.counter" }, tmp.NameDump); tmp = new DumperSampler(); ProbeManager.Ask().Sample("counter$", tmp); CollectionAssert.AreEquivalent(new string[] { "test.counter", "prova.counter" }, tmp.NameDump); } /// <summary> /// Verify fitering cababilities of the ProbeManager. /// starts with a set of probes, add and remove. Get one and use it. /// </summary> [TestCategory("Reporting")] [TestMethod] public void SenseProbes() { ProbeManager.Ask().Clear(".*"); string[] names = new string[] { "prova.gauge", "test.counter", "prova.meter", "test.histogram", "prova.counter" }; ProbeManager.Ask().Gauge(names[0], () => 10); CounterProbe probe=ProbeManager.Ask().Counter(names[1]); MeterProbe nprobe=ProbeManager.Ask().Meter(names[2]); ProbeManager.Ask().Histogram(names[3], new SlidingWindowReservoir<IComparable>(10)); TimerProbe tprobe = ProbeManager.Ask().Timer(names[4], new SlidingWindowReservoir<long>(10)); int tmp=0; ProbeManager.Ask().AddSenseHandler("counter", (p, a) => tmp++); nprobe.Mark(); Assert.AreEqual(0, tmp); probe.Increment(); Assert.AreEqual(1, tmp); tprobe.Time(() => { }); Assert.AreEqual(2, tmp); } } }
36.708791
171
0.566981
[ "MIT" ]
aliaslab-1984/CodeProbe
test/Test.CodeProbe/ProbeManagerTest.cs
6,683
C#
#region license // Copyright (c) 2004, Rodrigo B. de Oliveira (rbo@acm.org) // 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 Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections.Generic; using System.Reflection; using Boo.Lang.Compiler.TypeSystem.Core; using Boo.Lang.Compiler.TypeSystem.Services; using Boo.Lang.Compiler.Util; using Boo.Lang.Environments; namespace Boo.Lang.Compiler.TypeSystem.Reflection { public class ExternalType : IType { protected IReflectionTypeSystemProvider _provider; private readonly Type _type; private IType[] _interfaces; private IEntity[] _members; private Dictionary<string, List<IEntity>> _cache; private int _typeDepth = -1; private string _primitiveName; private string _fullName; private string _name; public ExternalType(IReflectionTypeSystemProvider tss, Type type) { if (null == type) throw new ArgumentException("type"); _provider = tss; _type = type; } public virtual string FullName { get { if (null != _fullName) return _fullName; return _fullName = BuildFullName(); } } internal string PrimitiveName { get { return _primitiveName; } set { _primitiveName = value; } } public virtual string Name { get { if (null != _name) return _name; return _name = TypeUtilities.TypeName(_type); } } public EntityType EntityType { get { return EntityType.Type; } } public IType Type { get { return this; } } public virtual bool IsFinal { get { return _type.IsSealed; } } public bool IsByRef { get { return _type.IsByRef; } } public virtual IEntity DeclaringEntity { get { return DeclaringType; } } public IType DeclaringType { get { var declaringType = _type.DeclaringType; return null != declaringType ? _provider.Map(declaringType) : null; } } public bool IsDefined(IType attributeType) { var type = attributeType as ExternalType; if (type == null) return false; return MetadataUtil.IsAttributeDefined(_type, type.ActualType); } public virtual IType ElementType { get { return _provider.Map(_type.GetElementType() ?? _type); } } public virtual bool IsClass { get { return _type.IsClass; } } public bool IsAbstract { get { return _type.IsAbstract; } } public bool IsInterface { get { return _type.IsInterface; } } public bool IsEnum { get { return _type.IsEnum; } } public virtual bool IsValueType { get { return _type.IsValueType; } } public bool IsArray { get { return false; } } public bool IsPointer { get { return _type.IsPointer; } } public virtual bool IsVoid { get { return false; } } public virtual IType BaseType { get { var baseType = _type.BaseType; return baseType == null ? null : _provider.Map(baseType); } } protected virtual MemberInfo[] GetDefaultMembers() { return ActualType.GetDefaultMembers(); } public IEntity GetDefaultMember() { return _provider.Map(GetDefaultMembers()); } public Type ActualType { get { return _type; } } public virtual bool IsSubclassOf(IType other) { var external = other as ExternalType; if (external == null) return false; return _type.IsSubclassOf(external._type) || (external.IsInterface && external._type.IsAssignableFrom(_type)); } public virtual bool IsAssignableFrom(IType other) { var external = other as ExternalType; if (null == external) { if (EntityType.Null == other.EntityType) { return !IsValueType; } if (other.ConstructedInfo != null && this.ConstructedInfo != null && ConstructedInfo.GenericDefinition == other.ConstructedInfo.GenericDefinition) { for (int i = 0; i < ConstructedInfo.GenericArguments.Length; ++i) { if (!ConstructedInfo.GenericArguments[i].IsAssignableFrom(other.ConstructedInfo.GenericArguments[i])) return false; } return true; } return other.IsSubclassOf(this); } if (other == _provider.Map(Types.Void)) { return false; } return _type.IsAssignableFrom(external._type); } public virtual IType[] GetInterfaces() { if (null == _interfaces) { Type[] interfaces = _type.GetInterfaces(); _interfaces = new IType[interfaces.Length]; for (int i=0; i<_interfaces.Length; ++i) { _interfaces[i] = _provider.Map(interfaces[i]); } } return _interfaces; } private void BuildCache() { _cache = new Dictionary<string, List<IEntity>>(); } public virtual IEnumerable<IEntity> GetMembers() { if (_members == null) { IEntity[] members = CreateMembers(); _members = members; BuildCache(); } return _members; } protected virtual IEntity[] CreateMembers() { var result = new List<IEntity>(); foreach (var member in DeclaredMembers()) result.Add(_provider.Map(member)); return result.ToArray(); } private MemberInfo[] DeclaredMembers() { return _type.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static); } public int GetTypeDepth() { if (-1 == _typeDepth) { _typeDepth = GetTypeDepth(_type); } return _typeDepth; } public virtual INamespace ParentNamespace { get { return null; } } private bool CachedResolve(string name, EntityType typesToConsider, ICollection<IEntity> resultingSet) { if (_cache == null) { GetMembers(); } if (!_cache.ContainsKey(name)) LoadCache(name); var list = _cache[name]; if (list != null) { var result = false; foreach (var entity in list) { if (Entities.IsFlagSet(typesToConsider, entity.EntityType)) { result = true; resultingSet.Add(entity); } } return result; } return false; } private void LoadCache(string name) { var matches = My<NameResolutionService>.Instance.EntityNameMatcher; var list = new List<IEntity>(); foreach (var member in _members) if (matches(member, name)) list.Add(member); if (list.Count == 0) list = null; _cache.Add(name, list); } public virtual bool Resolve(ICollection<IEntity> resultingSet, string name, EntityType typesToConsider) { bool found = CachedResolve(name, typesToConsider, resultingSet); //bool found = My<NameResolutionService>.Instance.Resolve(name, GetMembers(), typesToConsider, resultingSet); if (IsInterface) { if (_provider.Map(typeof(object)).Resolve(resultingSet, name, typesToConsider)) found = true; foreach (IType baseInterface in GetInterfaces()) found |= baseInterface.Resolve(resultingSet, name, typesToConsider); } else { if (!found || TypeSystemServices.ContainsMethodsOnly(resultingSet)) { IType baseType = BaseType; if (null != baseType) found |= baseType.Resolve(resultingSet, name, typesToConsider); } } return found; } public override string ToString() { return this.DisplayName(); } static int GetTypeDepth(Type type) { if (type.IsByRef) { return GetTypeDepth(type.GetElementType()); } if (type.IsInterface) { return GetInterfaceDepth(type); } return GetClassDepth(type); } static int GetClassDepth(Type type) { int depth = 0; Type objectType = Types.Object; while (type != null && type != objectType) { type = type.BaseType; ++depth; } return depth; } static int GetInterfaceDepth(Type type) { Type[] interfaces = type.GetInterfaces(); if (interfaces.Length > 0) { int current = 0; foreach (Type i in interfaces) { int depth = GetInterfaceDepth(i); if (depth > current) { current = depth; } } return 1+current; } return 1; } protected virtual string BuildFullName() { if (_primitiveName != null) return _primitiveName; // keep builtin names pretty ('ref int' instead of 'ref System.Int32') if (_type.IsByRef) return "ref " + ElementType.FullName; return TypeUtilities.GetFullName(_type); } ExternalGenericTypeInfo _genericTypeDefinitionInfo; public virtual IGenericTypeInfo GenericInfo { get { if (ActualType.IsGenericTypeDefinition) return _genericTypeDefinitionInfo ?? (_genericTypeDefinitionInfo = new ExternalGenericTypeInfo(_provider, this)); return null; } } ExternalConstructedTypeInfo _genericTypeInfo; public virtual IConstructedTypeInfo ConstructedInfo { get { if (ActualType.IsGenericType && !ActualType.IsGenericTypeDefinition) return _genericTypeInfo ?? (_genericTypeInfo = new ExternalConstructedTypeInfo(_provider, this)); return null; } } private ArrayTypeCache _arrayTypes; public IArrayType MakeArrayType(int rank) { if (null == _arrayTypes) _arrayTypes = new ArrayTypeCache(this); return _arrayTypes.MakeArrayType(rank); } public IType MakePointerType() { return _provider.Map(_type.MakePointerType()); } } }
25.231947
148
0.627959
[ "BSD-3-Clause" ]
Code-distancing/boo
src/Boo.Lang.Compiler/TypeSystem/Reflection/ExternalType.cs
11,531
C#
namespace SyncTool.FileSystem.Versioning.MetaFileSystem { /// <summary> /// Converter that takes a "meta file system" and retrieves the original file system stored in there /// </summary> public class MetaFileSystemToFileSystemConverter { public IDirectory Convert(IDirectory directory) => ConvertDynamic(null, directory); IDirectory Convert(IDirectory newParent, IDirectory toConvert) { // determine name of new directory var newDirectoryName = toConvert.Name; foreach (var file in toConvert.Files) { var name = GetDirectoryNameDynamic(file); if (name != null) { newDirectoryName = name; break; } } var newDirectory = new Directory(newParent, newDirectoryName); foreach (var childDirectory in toConvert.Directories) { var newChildDirectory = (IDirectory) ConvertDynamic(newDirectory, childDirectory); if (newChildDirectory != null) { newDirectory.Add(_ => newChildDirectory); } } foreach (var file in toConvert.Files) { var newFile = (IFile) ConvertDynamic(newDirectory, file); if (newFile != null) { newDirectory.Add(_ => newFile); } } return newDirectory; } IFile Convert(IDirectory newParent, FilePropertiesFile file) { // load file properties var newFile = new File(newParent, file.Content.Name) { LastWriteTime = file.Content.LastWriteTime, Length = file.Content.Length }; return newFile; } IFile Convert(IDirectory newParent, DirectoryPropertiesFile file) { // remove file from result return null; } IFile Convert(IDirectory newParent, IFile file) { // ignore file instances that are not instances of FilePropertiesFile or DirectoryPropertiesFile return null; } string GetDirectoryName(IFile file) => null; string GetDirectoryName(DirectoryPropertiesFile file) => file.Content.Name; dynamic ConvertDynamic(IDirectory newParent, dynamic toConvert) => ((dynamic) this).Convert(newParent, toConvert); string GetDirectoryNameDynamic(dynamic file) => ((dynamic)this).GetDirectoryName(file); } }
35.236842
155
0.557506
[ "MIT" ]
ap0llo/SyncTool
src/SyncTool.FileSystem.Versioning/main/MetaFileSystem/MetaFileSystemToFileSystemConverter.cs
2,680
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.ServiceProcess; using System.Text; using System.Threading; namespace DatAdmin { public partial class DatAdminService : ServiceBase { Thread m_thread; ManualResetEvent m_shutdownEvent; public DatAdminService() { InitializeComponent(); } protected override void OnStart(string[] args) { m_shutdownEvent = new ManualResetEvent(false); m_thread = new Thread(Run); m_thread.Start(); SystemLogTool.Info("DatAdmin Service started."); } protected override void OnStop() { m_shutdownEvent.Set(); m_thread.Join(10000); //m_thread.Abort(); base.OnStop(); SystemLogTool.Info("DatAdmin Service stopped."); } protected void Run() { while (true) { bool signaled = m_shutdownEvent.WaitOne(TimeSpan.FromMinutes(1), true); if (signaled == true) break; HJob.CallEveryMinute(); } } } }
23.716981
87
0.558473
[ "MIT" ]
dbgate/datadmin
DatAdminService/DatAdminService.cs
1,259
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.MachineLearningServices.V20200501Preview.Inputs { /// <summary> /// An Azure Machine Learning Model. /// </summary> public sealed class ModelArgs : Pulumi.ResourceArgs { /// <summary> /// The Model creation time (UTC). /// </summary> [Input("createdTime")] public Input<string>? CreatedTime { get; set; } [Input("datasets")] private InputList<Inputs.DatasetReferenceArgs>? _datasets; /// <summary> /// The list of datasets associated with the model. /// </summary> public InputList<Inputs.DatasetReferenceArgs> Datasets { get => _datasets ?? (_datasets = new InputList<Inputs.DatasetReferenceArgs>()); set => _datasets = value; } [Input("derivedModelIds")] private InputList<string>? _derivedModelIds; /// <summary> /// Models derived from this model /// </summary> public InputList<string> DerivedModelIds { get => _derivedModelIds ?? (_derivedModelIds = new InputList<string>()); set => _derivedModelIds = value; } /// <summary> /// The Model description text. /// </summary> [Input("description")] public Input<string>? Description { get; set; } /// <summary> /// The name of the experiment where this model was created. /// </summary> [Input("experimentName")] public Input<string>? ExperimentName { get; set; } /// <summary> /// The Model framework. /// </summary> [Input("framework")] public Input<string>? Framework { get; set; } /// <summary> /// The Model framework version. /// </summary> [Input("frameworkVersion")] public Input<string>? FrameworkVersion { get; set; } /// <summary> /// The Model Id. /// </summary> [Input("id")] public Input<string>? Id { get; set; } [Input("kvTags")] private InputMap<string>? _kvTags; /// <summary> /// The Model tag dictionary. Items are mutable. /// </summary> public InputMap<string> KvTags { get => _kvTags ?? (_kvTags = new InputMap<string>()); set => _kvTags = value; } /// <summary> /// The MIME type of Model content. For more details about MIME type, please open https://www.iana.org/assignments/media-types/media-types.xhtml /// </summary> [Input("mimeType", required: true)] public Input<string> MimeType { get; set; } = null!; /// <summary> /// The Model last modified time (UTC). /// </summary> [Input("modifiedTime")] public Input<string>? ModifiedTime { get; set; } /// <summary> /// The Model name. /// </summary> [Input("name", required: true)] public Input<string> Name { get; set; } = null!; /// <summary> /// The Parent Model Id. /// </summary> [Input("parentModelId")] public Input<string>? ParentModelId { get; set; } [Input("properties")] private InputMap<string>? _properties; /// <summary> /// The Model property dictionary. Properties are immutable. /// </summary> public InputMap<string> Properties { get => _properties ?? (_properties = new InputMap<string>()); set => _properties = value; } /// <summary> /// Resource requirements for the model /// </summary> [Input("resourceRequirements")] public Input<Inputs.ContainerResourceRequirementsArgs>? ResourceRequirements { get; set; } /// <summary> /// The RunId that created this model. /// </summary> [Input("runId")] public Input<string>? RunId { get; set; } /// <summary> /// Sample Input Data for the Model. A reference to a dataset in the workspace in the format aml://dataset/{datasetId} /// </summary> [Input("sampleInputData")] public Input<string>? SampleInputData { get; set; } /// <summary> /// Sample Output Data for the Model. A reference to a dataset in the workspace in the format aml://dataset/{datasetId} /// </summary> [Input("sampleOutputData")] public Input<string>? SampleOutputData { get; set; } /// <summary> /// Indicates whether we need to unpack the Model during docker Image creation. /// </summary> [Input("unpack")] public Input<bool>? Unpack { get; set; } /// <summary> /// The URL of the Model. Usually a SAS URL. /// </summary> [Input("url", required: true)] public Input<string> Url { get; set; } = null!; /// <summary> /// The Model version assigned by Model Management Service. /// </summary> [Input("version")] public Input<double>? Version { get; set; } public ModelArgs() { } } }
31.67052
152
0.555211
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/MachineLearningServices/V20200501Preview/Inputs/ModelArgs.cs
5,479
C#
// ================================================== // Copyright 2018(C) , DotLogix // File: PointAnimationHelper.cs // Author: Alexander Schill <alexander@schillnet.de>. // Created: 17.02.2018 // LastEdited: 01.08.2018 // ================================================== #region using System; using System.Windows; #endregion namespace DotLogix.UI.Animations { public class PointAnimationHelper : IAnimationHelper<Point> { #region IAnimationHelper public bool IsValidValue(Point value) { return DoubleAnimationHelper.IsValid(value.X) && DoubleAnimationHelper.IsValid(value.Y); } public Point GetZeroValue() { return new Point(); } public Point AddValues(Point value1, Point value2) { return new Point( value1.X + value2.X, value1.Y + value2.Y); } public Point SubtractValue(Point value1, Point value2) { return new Point( value1.X - value2.X, value1.Y - value2.Y); } public Point ScaleValue(Point value, double factor) { return new Point( value.X * factor, value.Y * factor); } public Point InterpolateValue(Point from, Point to, double progress) { return from + ((to - from) * progress); } public double GetSegmentLength(Point from, Point to) { return Math.Abs((to - from).Length); } public bool IsAccumulable => true; #endregion } }
30.090909
100
0.514199
[ "MIT" ]
dotlogix/DotlogixCore
UI/Animations/PointAnimationHelper.cs
1,655
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Graphics Benchmarks for PipBenchmarks")] [assembly: AssemblyDescription("Provides standard benchmarks to measure CPU, disk, video, database")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Conceptual Vision Consulting LLC")] [assembly: AssemblyProduct("Pip.Benchmark")] [assembly: AssemblyCopyright("Copyright © Conceptual Vision Consulting LLC 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f5f2a826-4a14-4303-a7e0-c7ac56c798f3")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
41.972973
101
0.757244
[ "MIT" ]
pip-benchmark/pip-benchmark-dotnet
src/PipBenchmark.Graphics.Net45/Properties/AssemblyInfo.cs
1,556
C#
using Newtonsoft.Json; using System; namespace ShopifySharp.Filters { /// <summary> /// Generic options for filtering objects that can be published (e.g. those with a PublishedAt, Published status). /// </summary> public class PublishableListFilter : ListFilter { /// <summary> /// Show objects published after date (format: 2008-12-31 03:00). /// </summary> [JsonProperty("published_at_min")] public DateTimeOffset? PublishedAtMin { get; set; } = null; /// <summary> /// Show objects published before date (format: 2008-12-31 03:00). /// </summary> [JsonProperty("published_at_max")] public DateTimeOffset? PublishedAtMax { get; set; } = null; /// <summary> /// Published Status. /// published - Show only published objects, unpublished - Show only unpublished objects, any - Show all objects(default) /// </summary> [JsonProperty("published_status")] public string PublishedStatus { get; set; } = null; } }
34.354839
129
0.61784
[ "MIT" ]
Matt-Kaminski/ShopifySharp
ShopifySharp/Filters/PublishableListFilter.cs
1,067
C#
 using NETCore.RedisKit.Core; using StackExchange.Redis; using System.Linq; using WanVet.Infrastructure.Read; using WanVet.Micro.PetManagement.Read.Domain.Model.PetModel.Queries; namespace WanVet.Micro.PetManagement.Read.Domain.Model.PetModel.QueryHandlers { public class GetPetQueryHandler : IQueryHandler<GetPetQuery, PetReadModel> { private readonly IRedisService _redisService; public GetPetQueryHandler(IRedisService redisService) { _redisService = redisService; } public PetReadModel Handle(GetPetQuery query) { var pet = new PetReadModel(); pet = _redisService.HashGet<PetReadModel>($"{pet.RedisKey}", $"{query.Id}", CommandFlags.PreferMaster); pet.Appointments = pet.Appointments.OrderBy(x => x.StartingTime).ToList(); return pet; } } }
31.321429
115
0.687571
[ "MIT" ]
alrazex/WanVet
src/WanVet.Micro.PetManagement.Read/Domain/Model/PetModel/QueryHandlers/GetPetQueryHandler.cs
879
C#
using System; using System.Collections.Generic; using System.Net.Http.Headers; using KeyPayV2.Sg.Models.Common; using Newtonsoft.Json.Converters; using Newtonsoft.Json; using KeyPayV2.Sg.Enums; namespace KeyPayV2.Sg.Models.Ess { public class EssUnavailabilityModel { public int Id { get; set; } public DateTime FromDate { get; set; } public DateTime? ToDate { get; set; } public DateTime? EndDate { get; set; } public string Reason { get; set; } public bool Recurring { get; set; } [JsonConverter(typeof(StringEnumConverter))] public DayOfWeek? RecurringDay { get; set; } public bool IsAllDay { get; set; } public bool ViewOnly { get; set; } } }
30.52
53
0.63827
[ "MIT" ]
KeyPay/keypay-dotnet-v2
src/keypay-dotnet/Sg/Models/Ess/EssUnavailabilityModel.cs
763
C#
/** * Copyright(C) 2017-2021 Sojatia Infocrafts Private Limited * * This file (QueryGenerator.cs) is part of dotEntity(https://github.com/RoastedBytes/dotentity). * * dotEntity is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * dotEntity is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the * GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with dotEntity.If not, see<http://www.gnu.org/licenses/>. * You can release yourself from the requirements of the AGPL license by purchasing * a commercial license (dotEntity Pro). Buying such a license is mandatory as soon as you * develop commercial activities involving the dotEntity software without * disclosing the source code of your own applications. The activites include: * shipping dotEntity with a closed source product, offering paid services to customers * as an Application Service Provider. * To know more about our commercial license email us at support@roastedbytes.com or * visit http://dotentity.net/licensing */ using System; using System.Collections; using System.Collections.Generic; using System.Dynamic; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Text.RegularExpressions; using DotEntity.Enumerations; using DotEntity.Extensions; namespace DotEntity { public abstract class QueryGenerator : IQueryGenerator { protected static Dictionary<JoinType, string> JoinMap = new Dictionary<JoinType, string> { { JoinType.Inner, "INNER JOIN" }, { JoinType.LeftOuter, "LEFT OUTER JOIN" }, { JoinType.RightOuter, "RIGHT OUTER JOIN" }, { JoinType.FullOuter, "FULL OUTER JOIN" } }; public virtual string GenerateInsert(string tableName, object entity, out IList<QueryInfo> parameters) { GetColumns(entity, out var keyColumn, out var excludeColumns); Dictionary<string, object> columnValueMap = QueryParserUtilities.ParseObjectKeyValues(entity, exclude: excludeColumns); var insertColumns = columnValueMap.Keys.ToArray(); var joinInsertString = string.Join(",", insertColumns.Select(x => x.ToEnclosed())); var joinValueString = "@" + string.Join(",@", insertColumns); ; parameters = ToQueryInfos(columnValueMap); var insertBuilder = new StringBuilder($"INSERT INTO {tableName.TableEnclosed()} ({joinInsertString})"); if(keyColumn != null) insertBuilder.Append($" OUTPUT inserted.{keyColumn.ToEnclosed()}"); insertBuilder.Append($" VALUES ({joinValueString});"); return insertBuilder.ToString(); } public virtual string GenerateInsert<T>(T entity, out IList<QueryInfo> parameters) where T : class { var tableName = DotEntityDb.GetTableNameForType<T>(); return GenerateInsert(tableName, entity, out parameters); } public virtual string GenerateBatchInsert<T>(T[] entities, out IList<QueryInfo> parameters) where T : class { Throw.IfEmptyBatch(entities.Length == 0); var queryBuilder = new StringBuilder(); var tableName = DotEntityDb.GetTableNameForType<T>(); parameters = new List<QueryInfo>(); const string pattern = "@([a-zA-Z0-9_]+)"; var regEx = new Regex(pattern); for (var i = 0; i < entities.Length; i++) { var e = entities[i]; var sql = GenerateInsert(tableName, e, out IList<QueryInfo> newParameters); parameters = MergeParameters(parameters, newParameters); if (i > 0) { sql = regEx.Replace(sql, "@${1}" + (i + 1)); } queryBuilder.Append(sql + Environment.NewLine); } return queryBuilder.ToString(); } public virtual string GenerateUpdate<T>(T entity, out IList<QueryInfo> queryParameters) where T : class { var tableName = DotEntityDb.GetTableNameForType<T>(); var deserializer = DataDeserializer<T>.Instance; var keyColumn = deserializer.GetKeyColumn(); var keyColumnValue = deserializer.GetPropertyAs<int>(entity, keyColumn); dynamic data = new ExpandoObject(); var dataDictionary = (IDictionary<string, object>)data; dataDictionary.Add(keyColumn, keyColumnValue); return GenerateUpdate(tableName, entity, dataDictionary, out queryParameters, keyColumn); } public virtual string GenerateUpdate(string tableName, object entity, object where, out IList<QueryInfo> queryParameters, params string[] exclude) { Dictionary<string, object> updateValueMap = QueryParserUtilities.ParseObjectKeyValues(entity, exclude); Dictionary<string, object> whereMap = QueryParserUtilities.ParseObjectKeyValues(where); queryParameters = ToQueryInfos(updateValueMap, whereMap); var updateString = string.Join(",", updateValueMap.Select(x => $"{x.Key.ToEnclosed()} = @{x.Key}")); //get the common keys var commonKeys = updateValueMap.Keys.Intersect(whereMap.Keys); var whereString = string.Join(" AND ", WrapWithBraces(whereMap.Select(x => { var prefix = commonKeys.Contains(x.Key) ? "2" : ""; return $"{x.Key.ToEnclosed()} = @{x.Key}{prefix}"; }))); return $"UPDATE {tableName.TableEnclosed()} SET {updateString} WHERE {whereString};"; } public virtual string GenerateUpdate<T>(object item, Expression<Func<T, bool>> where, out IList<QueryInfo> queryParameters) where T : class { var tableName = DotEntityDb.GetTableNameForType<T>(); var builder = new StringBuilder(); // convert the query parms into a SQL string and dynamic property object builder.Append("UPDATE "); builder.Append(tableName.TableEnclosed()); builder.Append(" SET "); Dictionary<string, object> updateValueMap = QueryParserUtilities.ParseObjectKeyValues(item); var updateString = string.Join(",", updateValueMap.Select(x => $"{x.Key.ToEnclosed()} = @{x.Key}")); builder.Append(updateString); var parser = new ExpressionTreeParser(); var whereString = parser.GetWhereString(where); queryParameters = parser.QueryInfoList; if (!string.IsNullOrEmpty(whereString)) { //update where string to handle common parameters var commonKeys = updateValueMap.Keys.Intersect(queryParameters.Select(x => x.PropertyName)); whereString = commonKeys.Aggregate(whereString, (current, ck) => current.Replace($"@{ck}", $"@{ck}2")); } queryParameters = MergeParameters(ToQueryInfos(updateValueMap), queryParameters); if (!string.IsNullOrEmpty(whereString)) { builder.Append(" WHERE " + whereString); } return builder.ToString().Trim() + ";"; } public virtual string GenerateDelete(string tableName, object where, out IList<QueryInfo> parameters) { Dictionary<string, object> whereMap = QueryParserUtilities.ParseObjectKeyValues(where); var whereString = string.Join(" AND ", WrapWithBraces(whereMap.Select(x => $"{x.Key.ToEnclosed()} = @{x.Key}"))); parameters = ToQueryInfos(whereMap); return $"DELETE FROM {tableName.TableEnclosed()} WHERE {whereString};"; } public virtual string GenerateDelete<T>(Expression<Func<T, bool>> where, out IList<QueryInfo> parameters) where T : class { var tableName = DotEntityDb.GetTableNameForType<T>(); var parser = new ExpressionTreeParser(); var whereString = parser.GetWhereString(where).Trim(); parameters = parser.QueryInfoList; return $"DELETE FROM {tableName.TableEnclosed()} WHERE {whereString};"; } public virtual string GenerateDelete<T>(T entity, out IList<QueryInfo> parameters) where T : class { var tableName = DotEntityDb.GetTableNameForType<T>(); var deserializer = DataDeserializer<T>.Instance; var keyColumn = deserializer.GetKeyColumn(); var keyColumnValue = deserializer.GetPropertyAs<int>(entity, keyColumn); dynamic data = new ExpandoObject(); var dataDictionary = (IDictionary<string, object>)data; dataDictionary.Add(keyColumn, keyColumnValue); return GenerateDelete(tableName, dataDictionary, out parameters); } public virtual string GenerateCount<T>(IList<Expression<Func<T, bool>>> @where, out IList<QueryInfo> parameters) where T : class { parameters = new List<QueryInfo>(); var tableName = DotEntityDb.GetTableNameForType<T>(); var whereString = ""; if (where != null && where.Any()) { var parser = new ExpressionTreeParser(); var whereStringBuilder = new List<string>(); foreach (var wh in where) { whereStringBuilder.Add(parser.GetWhereString(wh)); } parameters = parser.QueryInfoList; whereString = " WHERE " + string.Join(" AND ", WrapWithBraces(whereStringBuilder)).Trim(); } return $"SELECT COUNT(*) FROM {tableName.TableEnclosed()}{whereString};"; } public virtual string GenerateCount<T>(object @where, out IList<QueryInfo> parameters) { var tableName = DotEntityDb.GetTableNameForType<T>(); return GenerateCount(tableName, where, out parameters); } public virtual string GenerateCount(string tableName, object @where, out IList<QueryInfo> parameters) { Dictionary<string, object> whereMap = QueryParserUtilities.ParseObjectKeyValues(where); var whereString = string.Join(" AND ", WrapWithBraces(whereMap.Select(x => $"{x.Key} = @{x.Key}"))); parameters = ToQueryInfos(whereMap); return $"SELECT COUNT(*) FROM {tableName.TableEnclosed()} WHERE {whereString};"; } public virtual string GenerateSelect<T>(out IList<QueryInfo> parameters, List<Expression<Func<T, bool>>> where = null, Dictionary<Expression<Func<T, object>>, RowOrder> orderBy = null, int page = 1, int count = int.MaxValue, Dictionary<Type, IList<string>> excludeColumns = null) where T : class { parameters = new List<QueryInfo>(); var builder = new StringBuilder(); var tableName = DotEntityDb.GetTableNameForType<T>(); var whereString = ""; if (where != null) { var parser = new ExpressionTreeParser(); var whereStringBuilder = new List<string>(); foreach (var wh in where) { whereStringBuilder.Add(parser.GetWhereString(wh)); } parameters = parser.QueryInfoList; whereString = string.Join(" AND ", WrapWithBraces(whereStringBuilder)).Trim(); } var orderByStringBuilder = new List<string>(); var orderByString = ""; if (orderBy != null) { var parser = new ExpressionTreeParser(); foreach (var ob in orderBy) { orderByStringBuilder.Add(parser.GetOrderByString(ob.Key) + (ob.Value == RowOrder.Descending ? " DESC" : "")); } orderByString = string.Join(", ", orderByStringBuilder).Trim(','); } var paginatedSelect = PaginateOrderByString(orderByString, page, count, out string newWhereString); if (paginatedSelect != string.Empty) { paginatedSelect = "," + paginatedSelect; orderByString = string.Empty; } // make the query now builder.Append($"SELECT *{paginatedSelect} FROM "); builder.Append(tableName.TableEnclosed()); if (!string.IsNullOrEmpty(whereString)) { builder.Append(" WHERE " + whereString); } if (!string.IsNullOrEmpty(orderByString)) { builder.Append(" ORDER BY " + orderByString); } var query = builder.ToString().Trim(); if (paginatedSelect != string.Empty) { //wrap everything query = $"SELECT * FROM ({query}) AS __PAGINATEDRESULT__ WHERE {newWhereString};"; } else query = query + ";"; return query; } public virtual string GenerateSelectWithCustomSelection<T>(out IList<QueryInfo> parameters, string rawSelection, List<Expression<Func<T, bool>>> @where = null, Dictionary<Expression<Func<T, object>>, RowOrder> orderBy = null, int page = 1, int count = Int32.MaxValue) where T : class { parameters = new List<QueryInfo>(); var builder = new StringBuilder(); var tableName = DotEntityDb.GetTableNameForType<T>(); var whereString = ""; if (where != null) { var parser = new ExpressionTreeParser(); var whereStringBuilder = new List<string>(); foreach (var wh in where) { whereStringBuilder.Add(parser.GetWhereString(wh)); } parameters = parser.QueryInfoList; whereString = string.Join(" AND ", WrapWithBraces(whereStringBuilder)).Trim(); } var orderByStringBuilder = new List<string>(); var orderByString = ""; if (orderBy != null) { var parser = new ExpressionTreeParser(); foreach (var ob in orderBy) { orderByStringBuilder.Add(parser.GetOrderByString(ob.Key) + (ob.Value == RowOrder.Descending ? " DESC" : "")); } orderByString = string.Join(", ", orderByStringBuilder).Trim(','); } var paginatedSelect = PaginateOrderByString(orderByString, page, count, out string newWhereString); if (paginatedSelect != string.Empty) { paginatedSelect = "," + paginatedSelect; orderByString = string.Empty; } // make the query now builder.Append($"SELECT {rawSelection}{paginatedSelect} FROM "); builder.Append(tableName.TableEnclosed()); if (!string.IsNullOrEmpty(whereString)) { builder.Append(" WHERE " + whereString); } if (!string.IsNullOrEmpty(orderByString)) { builder.Append(" ORDER BY " + orderByString); } var query = builder.ToString().Trim(); if (paginatedSelect != string.Empty) { //wrap everything query = $"SELECT * FROM ({query}) AS __PAGINATEDRESULT__ WHERE {newWhereString};"; } else query = query + ";"; return query; } public virtual string GenerateSelectWithTotalMatchingCount<T>(out IList<QueryInfo> parameters, List<Expression<Func<T, bool>>> @where = null, Dictionary<Expression<Func<T, object>>, RowOrder> orderBy = null, int page = 1, int count = Int32.MaxValue, Dictionary<Type, IList<string>> excludeColumns = null) where T : class { parameters = new List<QueryInfo>(); var builder = new StringBuilder(); var tableName = DotEntityDb.GetTableNameForType<T>(); var whereString = ""; if (where != null) { var parser = new ExpressionTreeParser(); var whereStringBuilder = new List<string>(); foreach (var wh in where) { whereStringBuilder.Add(parser.GetWhereString(wh)); } parameters = parser.QueryInfoList; whereString = string.Join(" AND ", WrapWithBraces(whereStringBuilder)).Trim(); } var orderByStringBuilder = new List<string>(); var orderByString = ""; if (orderBy != null) { var parser = new ExpressionTreeParser(); foreach (var ob in orderBy) { orderByStringBuilder.Add(parser.GetOrderByString(ob.Key) + (ob.Value == RowOrder.Descending ? " DESC" : "")); } orderByString = string.Join(", ", orderByStringBuilder).Trim(','); } var paginatedSelect = PaginateOrderByString(orderByString, page, count, out string newWhereString); if (paginatedSelect != string.Empty) { paginatedSelect = "," + paginatedSelect; orderByString = string.Empty; } // make the query now builder.Append($"SELECT {QueryParserUtilities.GetSelectColumnString(new List<Type>() { typeof(T) }, null, excludeColumns)}{paginatedSelect} FROM "); builder.Append(tableName.TableEnclosed()); if (!string.IsNullOrEmpty(whereString)) { builder.Append(" WHERE " + whereString); } if (!string.IsNullOrEmpty(orderByString)) { builder.Append(" ORDER BY " + orderByString); } var query = builder.ToString().Trim(); if (paginatedSelect != string.Empty) { //wrap everything query = $"SELECT * FROM ({query}) AS __PAGINATEDRESULT__ WHERE {newWhereString};"; } //and the count query query = query + $"{Environment.NewLine}SELECT COUNT(*) FROM {tableName.TableEnclosed()}" + (string.IsNullOrEmpty(whereString) ? "" : $" WHERE {whereString}") + ";"; return query; } public virtual string GenerateJoin<T>(out IList<QueryInfo> parameters, List<IJoinMeta> joinMetas, List<LambdaExpression> @where = null, Dictionary<LambdaExpression, RowOrder> orderBy = null, int page = 1, int count = int.MaxValue, Dictionary<Type, IList<string>> excludeColumns = null) where T : class { parameters = new List<QueryInfo>(); var typedAliases = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase); var builder = new StringBuilder(); var tableName = DotEntityDb.GetTableNameForType<T>(); var parentAliasUsed = "t1"; var lastAliasUsed = parentAliasUsed; typedAliases.Add(tableName, new List<string>() { lastAliasUsed }); var joinBuilder = new StringBuilder(); foreach (var joinMeta in joinMetas) { var joinedTableName = DotEntityDb.GetTableNameForType(joinMeta.OnType); var newAlias = $"t{typedAliases.SelectMany(x => x.Value).Count() + 1}"; if (typedAliases.ContainsKey(joinedTableName)) typedAliases[joinedTableName].Add(newAlias); else { typedAliases.Add($"{joinedTableName}", new List<string>() { newAlias }); } var sourceAlias = lastAliasUsed; if (joinMeta.SourceColumn == SourceColumn.Parent) { sourceAlias = parentAliasUsed; } else if (joinMeta.SourceColumn == SourceColumn.Implicit) { var sourceTableName = DotEntityDb.GetTableNameForType(joinMeta.SourceColumnType); if (!typedAliases.TryGetValue(sourceTableName, out List<string> availableAliases)) { sourceAlias = lastAliasUsed; } else sourceAlias = availableAliases?[joinMeta.SourceColumnAppearanceOrder] ?? lastAliasUsed; } joinBuilder.Append( $"{JoinMap[joinMeta.JoinType]} {joinedTableName.TableEnclosed()} {newAlias} ON {sourceAlias}.{joinMeta.SourceColumnName.ToEnclosed()} = {newAlias}.{joinMeta.DestinationColumnName.ToEnclosed()} "); if (joinMeta.AdditionalJoinExpression != null) { var parser = new ExpressionTreeParser(typedAliases); var joinExpression = parser.GetWhereString(joinMeta.AdditionalJoinExpression); joinBuilder.Append($"AND {joinExpression} "); parameters = parameters.Concat(parser.QueryInfoList).ToList(); } lastAliasUsed = newAlias; } var whereStringBuilder = new List<string>(); var whereString = ""; var rootTypeWhereBuilder = new List<string>(); var rootTypeWhereString = ""; if (where != null) { var parser = new ExpressionTreeParser(typedAliases); foreach (var wh in where) { var wStr = parser.GetWhereString(wh); if (wh.Parameters[0].Type == typeof(T)) { rootTypeWhereBuilder.Add(wStr); } else { whereStringBuilder.Add(wStr); } } parameters = parameters?.Concat(parser.QueryInfoList).ToList() ?? parser.QueryInfoList; whereString = string.Join(" AND ", WrapWithBraces(whereStringBuilder)).Trim(); rootTypeWhereString = string.Join(" AND ", WrapWithBraces(rootTypeWhereBuilder)).Trim(); } var orderByStringBuilder = new List<string>(); var orderByString = ""; if (orderBy != null) { var parser = new ExpressionTreeParser(typedAliases); foreach (var ob in orderBy) { orderByStringBuilder.Add(parser.GetOrderByString(ob.Key) + (ob.Value == RowOrder.Descending ? " DESC" : "")); } orderByString = string.Join(", ", orderByStringBuilder).Trim(','); } var paginatedSelect = PaginateOrderByString(orderByString, page, count, out string newWhereString, true); if (paginatedSelect != string.Empty) { paginatedSelect = "," + paginatedSelect; } var allTypes = joinMetas.Select(x => x.OnType).Distinct().ToList(); allTypes.Add(typeof(T)); if (paginatedSelect != string.Empty) { // make the query now builder.Append($"SELECT * FROM ("); } builder.Append($"SELECT {QueryParserUtilities.GetSelectColumnString(allTypes, typedAliases, excludeColumns)}{paginatedSelect} FROM "); //some nested queries are required, let's get the column names (raw) for root table var columnNameString = QueryParserUtilities.GetSelectColumnString(new List<Type>() { typeof(T) }, null, excludeColumns); //make the internal query that'll perform the pagination based on root table builder.Append($"(SELECT {columnNameString} FROM "); if (!string.IsNullOrEmpty(rootTypeWhereString)) { rootTypeWhereString = $" WHERE {rootTypeWhereString} "; } if (!string.IsNullOrEmpty(newWhereString)) { newWhereString = $" WHERE {newWhereString} "; } builder.Append(tableName.TableEnclosed() + $" {parentAliasUsed}{rootTypeWhereString}) AS {parentAliasUsed} "); //join builder.Append(joinBuilder); if (!string.IsNullOrEmpty(whereString)) { builder.Append(" WHERE " + whereString); } if (paginatedSelect != string.Empty) builder.Append($") AS {parentAliasUsed}{newWhereString}"); else { if (!string.IsNullOrEmpty(orderByString)) { builder.Append(" ORDER BY " + orderByString); } } var query = builder.ToString().Trim(); return query + ";"; } public virtual string GenerateJoinWithTotalMatchingCount<T>(out IList<QueryInfo> parameters, List<IJoinMeta> joinMetas, List<LambdaExpression> @where = null, Dictionary<LambdaExpression, RowOrder> orderBy = null, int page = 1, int count = Int32.MaxValue, Dictionary<Type, IList<string>> excludeColumns = null) where T : class { parameters = new List<QueryInfo>(); var typedAliases = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase); var builder = new StringBuilder(); var tableName = DotEntityDb.GetTableNameForType<T>(); var parentAliasUsed = "t1"; var lastAliasUsed = parentAliasUsed; typedAliases.Add(tableName, new List<string>() { lastAliasUsed }); var joinBuilder = new StringBuilder(); foreach (var joinMeta in joinMetas) { var joinedTableName = DotEntityDb.GetTableNameForType(joinMeta.OnType); var newAlias = $"t{typedAliases.SelectMany(x => x.Value).Count() + 1}"; if (typedAliases.ContainsKey(joinedTableName)) typedAliases[joinedTableName].Add(newAlias); else { typedAliases.Add($"{joinedTableName}", new List<string>() { newAlias }); } var sourceAlias = lastAliasUsed; if (joinMeta.SourceColumn == SourceColumn.Parent) { sourceAlias = parentAliasUsed; } else if (joinMeta.SourceColumn == SourceColumn.Implicit) { var sourceTableName = DotEntityDb.GetTableNameForType(joinMeta.SourceColumnType); if (!typedAliases.TryGetValue(sourceTableName, out List<string> availableAliases)) { sourceAlias = lastAliasUsed; } else sourceAlias = availableAliases?[joinMeta.SourceColumnAppearanceOrder] ?? lastAliasUsed; } joinBuilder.Append( $"{JoinMap[joinMeta.JoinType]} {joinedTableName.TableEnclosed()} {newAlias} ON {sourceAlias}.{joinMeta.SourceColumnName.ToEnclosed()} = {newAlias}.{joinMeta.DestinationColumnName.ToEnclosed()} "); if (joinMeta.AdditionalJoinExpression != null) { var parser = new ExpressionTreeParser(typedAliases); var joinExpression = parser.GetWhereString(joinMeta.AdditionalJoinExpression); joinBuilder.Append($"AND {joinExpression} "); parameters = parameters.Concat(parser.QueryInfoList).ToList(); } lastAliasUsed = newAlias; } var whereStringBuilder = new List<string>(); var whereString = ""; var rootTypeWhereBuilder = new List<string>(); var rootTypeWhereString = ""; if (where != null) { var parser = new ExpressionTreeParser(typedAliases); foreach (var wh in where) { var wStr = parser.GetWhereString(wh); if (wh.Parameters[0].Type == typeof(T)) { rootTypeWhereBuilder.Add(wStr); } else { whereStringBuilder.Add(wStr); } } parameters = parameters?.Concat(parser.QueryInfoList).ToList() ?? parser.QueryInfoList; whereString = string.Join(" AND ", WrapWithBraces(whereStringBuilder)).Trim(); rootTypeWhereString = string.Join(" AND ", WrapWithBraces(rootTypeWhereBuilder)).Trim(); } var orderByStringBuilder = new List<string>(); var orderByString = ""; if (orderBy != null) { var parser = new ExpressionTreeParser(typedAliases); foreach (var ob in orderBy) { orderByStringBuilder.Add(parser.GetOrderByString(ob.Key) + (ob.Value == RowOrder.Descending ? " DESC" : "")); } orderByString = string.Join(", ", orderByStringBuilder).Trim(','); } var paginatedSelect = PaginateOrderByString(orderByString, page, count, out string newWhereString, true); if (paginatedSelect != string.Empty) { paginatedSelect = "," + paginatedSelect; } var allTypes = joinMetas.Select(x => x.OnType).Distinct().ToList(); allTypes.Add(typeof(T)); // make the query now if (paginatedSelect != string.Empty) { // make the query now builder.Append($"SELECT * FROM ("); } builder.Append($"SELECT {QueryParserUtilities.GetSelectColumnString(allTypes, typedAliases, excludeColumns)}{paginatedSelect} FROM "); //some nested queries are required, let's get the column names (raw) for root table var columnNameString = QueryParserUtilities.GetSelectColumnString(new List<Type>() { typeof(T) }, null, excludeColumns); //make the internal query that'll perform the pagination based on root table builder.Append($"(SELECT {columnNameString} FROM "); if (!string.IsNullOrEmpty(rootTypeWhereString)) { rootTypeWhereString = $" WHERE {rootTypeWhereString} "; } if (!string.IsNullOrEmpty(newWhereString)) { newWhereString = $" WHERE {newWhereString} "; } builder.Append(tableName.TableEnclosed() + $" {parentAliasUsed}{rootTypeWhereString}) AS {parentAliasUsed} "); //join builder.Append(joinBuilder); if (!string.IsNullOrEmpty(whereString)) { builder.Append(" WHERE " + whereString); } if (paginatedSelect != string.Empty) builder.Append($") AS {parentAliasUsed}{newWhereString}"); else { if (!string.IsNullOrEmpty(orderByString)) { builder.Append(" ORDER BY " + orderByString); } } //now thecount query builder.Append(";" + Environment.NewLine); var rootIdColumnName = $"{parentAliasUsed}.{typeof(T).GetKeyColumnName().ToEnclosed()}"; builder.Append( $"SELECT COUNT(DISTINCT {rootIdColumnName}) FROM (SELECT {columnNameString} FROM {tableName.TableEnclosed()} {parentAliasUsed} {rootTypeWhereString}) AS {parentAliasUsed} "); //join builder.Append(joinBuilder); //and other wheres if any if (!string.IsNullOrEmpty(whereString)) { builder.Append(" WHERE " + whereString); } var query = builder.ToString().Trim(); return query + ";"; } public virtual string GenerateJoinWithCustomSelection<T>(out IList<QueryInfo> parameters, string rawSelection, List<IJoinMeta> joinMetas, List<LambdaExpression> @where = null, Dictionary<LambdaExpression, RowOrder> orderBy = null, int page = 1, int count = Int32.MaxValue) where T : class { parameters = new List<QueryInfo>(); var typedAliases = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase); var builder = new StringBuilder(); var tableName = DotEntityDb.GetTableNameForType<T>(); var parentAliasUsed = "t1"; var lastAliasUsed = parentAliasUsed; typedAliases.Add(typeof(T).Name, new List<string>() { lastAliasUsed }); var joinBuilder = new StringBuilder(); foreach (var joinMeta in joinMetas) { var joinedTableName = DotEntityDb.GetTableNameForType(joinMeta.OnType); var newAlias = $"t{typedAliases.SelectMany(x => x.Value).Count() + 1}"; if (typedAliases.ContainsKey(joinedTableName)) typedAliases[joinedTableName].Add(newAlias); else { typedAliases.Add($"{joinedTableName}", new List<string>() { newAlias }); } var sourceAlias = lastAliasUsed; if (joinMeta.SourceColumn == SourceColumn.Parent) { sourceAlias = parentAliasUsed; } else if (joinMeta.SourceColumn == SourceColumn.Implicit) { var sourceTableName = DotEntityDb.GetTableNameForType(joinMeta.SourceColumnType); if (!typedAliases.TryGetValue(sourceTableName, out List<string> availableAliases)) { sourceAlias = lastAliasUsed; } else sourceAlias = availableAliases?[joinMeta.SourceColumnAppearanceOrder] ?? lastAliasUsed; } joinBuilder.Append( $"{JoinMap[joinMeta.JoinType]} {joinedTableName.TableEnclosed()} {newAlias} ON {sourceAlias}.{joinMeta.SourceColumnName.ToEnclosed()} = {newAlias}.{joinMeta.DestinationColumnName.ToEnclosed()} "); if (joinMeta.AdditionalJoinExpression != null) { var parser = new ExpressionTreeParser(typedAliases); var joinExpression = parser.GetWhereString(joinMeta.AdditionalJoinExpression); joinBuilder.Append($"AND {joinExpression} "); parameters = parameters.Concat(parser.QueryInfoList).ToList(); } lastAliasUsed = newAlias; } var whereStringBuilder = new List<string>(); var whereString = ""; var rootTypeWhereBuilder = new List<string>(); var rootTypeWhereString = ""; if (where != null) { var parser = new ExpressionTreeParser(typedAliases); foreach (var wh in where) { var wStr = parser.GetWhereString(wh); if (wh.Parameters[0].Type == typeof(T)) { rootTypeWhereBuilder.Add(wStr); } else { whereStringBuilder.Add(wStr); } } parameters = parameters?.Concat(parser.QueryInfoList).ToList() ?? parser.QueryInfoList; whereString = string.Join(" AND ", WrapWithBraces(whereStringBuilder)).Trim(); rootTypeWhereString = string.Join(" AND ", WrapWithBraces(rootTypeWhereBuilder)).Trim(); } var orderByStringBuilder = new List<string>(); var orderByString = ""; if (orderBy != null) { var parser = new ExpressionTreeParser(typedAliases); foreach (var ob in orderBy) { orderByStringBuilder.Add(parser.GetOrderByString(ob.Key) + (ob.Value == RowOrder.Descending ? " DESC" : "")); } orderByString = string.Join(", ", orderByStringBuilder).Trim(','); } var paginatedSelect = PaginateOrderByString(orderByString, page, count, out string newWhereString); if (paginatedSelect != string.Empty) { paginatedSelect = "," + paginatedSelect; orderByString = string.Empty; } var allTypes = joinMetas.Select(x => x.OnType).Distinct().ToList(); allTypes.Add(typeof(T)); // make the query now builder.Append($"SELECT {rawSelection} FROM "); builder.Append($"(SELECT {QueryParserUtilities.GetSelectColumnString(allTypes, typedAliases)} FROM "); //some nested queries are required, let's get the column names (raw) for root table var columnNameString = QueryParserUtilities.GetSelectColumnString(new List<Type>() { typeof(T) }); //make the internal query that'll perform the pagination based on root table builder.Append($"(SELECT {columnNameString} FROM (SELECT {columnNameString}{paginatedSelect} FROM "); if (!string.IsNullOrEmpty(rootTypeWhereString)) { rootTypeWhereString = $" WHERE {rootTypeWhereString} "; } if (!string.IsNullOrEmpty(newWhereString)) { newWhereString = $" WHERE {newWhereString} "; } builder.Append(tableName.TableEnclosed() + $" {parentAliasUsed}{rootTypeWhereString}) AS __PAGINATEDRESULT__ {newWhereString}) AS {parentAliasUsed} "); //join builder.Append(joinBuilder); if (!string.IsNullOrEmpty(whereString)) { builder.Append(" WHERE " + whereString); } if (!string.IsNullOrEmpty(orderByString)) { builder.Append(" ORDER BY " + orderByString); } builder.Append(") AS WrappedResult"); var query = builder.ToString().Trim(); return query + ";"; } public virtual string Query(string query, object inParameters, out IList<QueryInfo> parameters) { var columnValueMap = QueryParserUtilities.ParseObjectKeyValues(inParameters); parameters = ToQueryInfos(columnValueMap); return query; } protected static IList<QueryInfo> ToQueryInfos(params Dictionary<string, object>[] dict) { if (dict == null) return null; var queryParameters = new List<QueryInfo>(); foreach (var dictionary in dict) { if (dictionary == null) continue; foreach (var strObj in dictionary) { var propertyName = strObj.Key; var propertyValue = strObj.Value; var parameterName = propertyName; //do we have any property of same name, we'll have to rename parameters if that's the case if (queryParameters.Any(x => x.PropertyName == propertyName)) { parameterName = propertyName + (queryParameters.Count(x => x.PropertyName == propertyName) + 1); } queryParameters.Add(new QueryInfo(string.Empty, propertyName, propertyValue, string.Empty, parameterName)); } } return queryParameters; } protected static IList<QueryInfo> MergeParameters(IEnumerable<QueryInfo> baseList, params IList<QueryInfo>[] queryParameterList) { //update all the parameter names first var queryParameters = baseList as IList<QueryInfo> ?? baseList.ToList(); foreach (var list in queryParameterList) { foreach (var qp in list) { if (queryParameters.Any(x => x.PropertyName == qp.PropertyName)) { qp.ParameterName = qp.PropertyName + (queryParameters.Count(x => x.PropertyName == qp.PropertyName) + 1); } } //concat this queryParameters = queryParameters.Concat(list).ToList(); } return queryParameters; } private static string PaginateOrderByString(string orderByString, int page, int count, out string newWhereString, bool useDenseRank = false) { if (page > 1 || count < int.MaxValue) { //pagination is required const string rowNumVariable = "__ROW_NUM__"; var start = (page - 1) * count; //0 var end = start + count + 1; //16 newWhereString = $"{rowNumVariable} > {start} AND {rowNumVariable} < {end}"; //1-15 return (useDenseRank ? "DENSE_RANK()" : "ROW_NUMBER()") + $" OVER (ORDER BY {orderByString}) AS {rowNumVariable}"; } return newWhereString = string.Empty; } protected static IEnumerable<string> WrapWithBraces(IEnumerable<string> original) { return original.Select(x => "(" + x + ")"); } protected void GetColumns(object entity, out string keyColumn, out string[] excludeColumns) { var type = entity.GetType(); excludeColumns = null; try { keyColumn = type.GetKeyColumnName(out var keyColumnType); if (keyColumnType.PropertyType == typeof(int)) { //check if value is non-zero if ((int)keyColumnType.GetValue(entity) == 0) excludeColumns = new[] { keyColumn }; } } catch { keyColumn = null; } if (excludeColumns == null) excludeColumns = new string[0]; } } }
45.379347
303
0.562243
[ "MIT" ]
RoastedBytes/dotEntity
src/DotEntity/QueryGenerator.cs
43,067
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238 namespace JumpPoint.Uwp.Standalone { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class DeletePage : Page { public DeletePage() { this.InitializeComponent(); } } }
26.645161
95
0.726392
[ "MIT" ]
MarkIvanDev/JumpPoint
JumpPoint/JumpPoint.Uwp/Standalone/DeletePage.xaml.cs
828
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using FantasyData.Api.Client.Model.MLB; namespace FantasyData.Api.Client { public partial class MLBv3StatsClient : BaseClient { public MLBv3StatsClient(string apiKey) : base(apiKey) { } public MLBv3StatsClient(Guid apiKey) : base(apiKey) { } /// <summary> /// Get Are Games In Progress Asynchronous /// </summary> public Task<bool> GetAreAnyGamesInProgressAsync() { var parameters = new List<KeyValuePair<string, string>>(); return Task.Run<bool>(() => base.Get<bool>("/v3/mlb/stats/{format}/AreAnyGamesInProgress", parameters) ); } /// <summary> /// Get Are Games In Progress /// </summary> public bool GetAreAnyGamesInProgress() { return this.GetAreAnyGamesInProgressAsync().Result; } /// <summary> /// Get Batter vs. Pitcher Stats Asynchronous /// </summary> /// <param name="hitterid">Unique FantasyData Player ID. Example:<code>10000031</code>.</param> /// <param name="pitcherid">Unique FantasyData Player ID. Example:<code>10000618</code>.</param> public Task<List<PlayerSeason>> GetHitterVsPitcherAsync(int hitterid, int pitcherid) { var parameters = new List<KeyValuePair<string, string>>(); parameters.Add(new KeyValuePair<string, string>("hitterid", hitterid.ToString())); parameters.Add(new KeyValuePair<string, string>("pitcherid", pitcherid.ToString())); return Task.Run<List<PlayerSeason>>(() => base.Get<List<PlayerSeason>>("/v3/mlb/stats/{format}/HitterVsPitcher/{hitterid}/{pitcherid}", parameters) ); } /// <summary> /// Get Batter vs. Pitcher Stats /// </summary> /// <param name="hitterid">Unique FantasyData Player ID. Example:<code>10000031</code>.</param> /// <param name="pitcherid">Unique FantasyData Player ID. Example:<code>10000618</code>.</param> public List<PlayerSeason> GetHitterVsPitcher(int hitterid, int pitcherid) { return this.GetHitterVsPitcherAsync(hitterid, pitcherid).Result; } /// <summary> /// Get Box Score Asynchronous /// </summary> /// <param name="gameid">The GameID of an MLB game. GameIDs can be found in the Games API. Valid entries are <code>14620</code> or <code>16905</code></param> public Task<BoxScore> GetBoxScoreAsync(int gameid) { var parameters = new List<KeyValuePair<string, string>>(); parameters.Add(new KeyValuePair<string, string>("gameid", gameid.ToString())); return Task.Run<BoxScore>(() => base.Get<BoxScore>("/v3/mlb/stats/{format}/BoxScore/{gameid}", parameters) ); } /// <summary> /// Get Box Score /// </summary> /// <param name="gameid">The GameID of an MLB game. GameIDs can be found in the Games API. Valid entries are <code>14620</code> or <code>16905</code></param> public BoxScore GetBoxScore(int gameid) { return this.GetBoxScoreAsync(gameid).Result; } /// <summary> /// Get Box Scores by Date Asynchronous /// </summary> /// <param name="date">The date of the game(s). Examples: <code>2017-JUL-31</code>, <code>2017-SEP-01</code>.</param> public Task<List<BoxScore>> GetBoxScoresAsync(string date) { var parameters = new List<KeyValuePair<string, string>>(); parameters.Add(new KeyValuePair<string, string>("date", date.ToString())); return Task.Run<List<BoxScore>>(() => base.Get<List<BoxScore>>("/v3/mlb/stats/{format}/BoxScores/{date}", parameters) ); } /// <summary> /// Get Box Scores by Date /// </summary> /// <param name="date">The date of the game(s). Examples: <code>2017-JUL-31</code>, <code>2017-SEP-01</code>.</param> public List<BoxScore> GetBoxScores(string date) { return this.GetBoxScoresAsync(date).Result; } /// <summary> /// Get Box Scores by Date Delta Asynchronous /// </summary> /// <param name="date">The date of the game(s). Examples: <code>2017-JUL-31</code>, <code>2017-SEP-01</code>.</param> /// <param name="minutes">Only returns player statistics that have changed in the last X minutes. You specify how many minutes in time to go back. Valid entries are: <code>1</code>, <code>2</code> ... <code>all</code>.</param> public Task<List<BoxScore>> GetBoxScoresDeltaAsync(string date, string minutes) { var parameters = new List<KeyValuePair<string, string>>(); parameters.Add(new KeyValuePair<string, string>("date", date.ToString())); parameters.Add(new KeyValuePair<string, string>("minutes", minutes.ToString())); return Task.Run<List<BoxScore>>(() => base.Get<List<BoxScore>>("/v3/mlb/stats/{format}/BoxScoresDelta/{date}/{minutes}", parameters) ); } /// <summary> /// Get Box Scores by Date Delta /// </summary> /// <param name="date">The date of the game(s). Examples: <code>2017-JUL-31</code>, <code>2017-SEP-01</code>.</param> /// <param name="minutes">Only returns player statistics that have changed in the last X minutes. You specify how many minutes in time to go back. Valid entries are: <code>1</code>, <code>2</code> ... <code>all</code>.</param> public List<BoxScore> GetBoxScoresDelta(string date, string minutes) { return this.GetBoxScoresDeltaAsync(date, minutes).Result; } /// <summary> /// Get Current Season Asynchronous /// </summary> public Task<Season> GetCurrentSeasonAsync() { var parameters = new List<KeyValuePair<string, string>>(); return Task.Run<Season>(() => base.Get<Season>("/v3/mlb/stats/{format}/CurrentSeason", parameters) ); } /// <summary> /// Get Current Season /// </summary> public Season GetCurrentSeason() { return this.GetCurrentSeasonAsync().Result; } /// <summary> /// Get DFS Slates by Date Asynchronous /// </summary> /// <param name="date">The date of the slates. Examples: <code>2017-JUL-31</code>, <code>2017-SEP-01</code>.</param> public Task<List<DfsSlate>> GetDfsSlatesByDateAsync(string date) { var parameters = new List<KeyValuePair<string, string>>(); parameters.Add(new KeyValuePair<string, string>("date", date.ToString())); return Task.Run<List<DfsSlate>>(() => base.Get<List<DfsSlate>>("/v3/mlb/stats/{format}/DfsSlatesByDate/{date}", parameters) ); } /// <summary> /// Get DFS Slates by Date /// </summary> /// <param name="date">The date of the slates. Examples: <code>2017-JUL-31</code>, <code>2017-SEP-01</code>.</param> public List<DfsSlate> GetDfsSlatesByDate(string date) { return this.GetDfsSlatesByDateAsync(date).Result; } /// <summary> /// Get Games by Date Asynchronous /// </summary> /// <param name="date">The date of the game(s). Examples: <code>2017-JUL-31</code>, <code>2017-SEP-01</code>.</param> public Task<List<Game>> GetGamesByDateAsync(string date) { var parameters = new List<KeyValuePair<string, string>>(); parameters.Add(new KeyValuePair<string, string>("date", date.ToString())); return Task.Run<List<Game>>(() => base.Get<List<Game>>("/v3/mlb/stats/{format}/GamesByDate/{date}", parameters) ); } /// <summary> /// Get Games by Date /// </summary> /// <param name="date">The date of the game(s). Examples: <code>2017-JUL-31</code>, <code>2017-SEP-01</code>.</param> public List<Game> GetGamesByDate(string date) { return this.GetGamesByDateAsync(date).Result; } /// <summary> /// Get News Asynchronous /// </summary> public Task<List<News>> GetNewsAsync() { var parameters = new List<KeyValuePair<string, string>>(); return Task.Run<List<News>>(() => base.Get<List<News>>("/v3/mlb/stats/{format}/News", parameters) ); } /// <summary> /// Get News /// </summary> public List<News> GetNews() { return this.GetNewsAsync().Result; } /// <summary> /// Get News by Date Asynchronous /// </summary> /// <param name="date">The date of the news. Examples: <code>2017-JUL-31</code>, <code>2017-SEP-01</code>.</param> public Task<List<News>> GetNewsByDateAsync(string date) { var parameters = new List<KeyValuePair<string, string>>(); parameters.Add(new KeyValuePair<string, string>("date", date.ToString())); return Task.Run<List<News>>(() => base.Get<List<News>>("/v3/mlb/stats/{format}/NewsByDate/{date}", parameters) ); } /// <summary> /// Get News by Date /// </summary> /// <param name="date">The date of the news. Examples: <code>2017-JUL-31</code>, <code>2017-SEP-01</code>.</param> public List<News> GetNewsByDate(string date) { return this.GetNewsByDateAsync(date).Result; } /// <summary> /// Get News by Player Asynchronous /// </summary> /// <param name="playerid">Unique FantasyData Player ID. Example:<code>10000507</code>.</param> public Task<List<News>> GetNewsByPlayerIDAsync(int playerid) { var parameters = new List<KeyValuePair<string, string>>(); parameters.Add(new KeyValuePair<string, string>("playerid", playerid.ToString())); return Task.Run<List<News>>(() => base.Get<List<News>>("/v3/mlb/stats/{format}/NewsByPlayerID/{playerid}", parameters) ); } /// <summary> /// Get News by Player /// </summary> /// <param name="playerid">Unique FantasyData Player ID. Example:<code>10000507</code>.</param> public List<News> GetNewsByPlayerID(int playerid) { return this.GetNewsByPlayerIDAsync(playerid).Result; } /// <summary> /// Get Player Details by Active Asynchronous /// </summary> public Task<List<Player>> GetPlayersAsync() { var parameters = new List<KeyValuePair<string, string>>(); return Task.Run<List<Player>>(() => base.Get<List<Player>>("/v3/mlb/stats/{format}/Players", parameters) ); } /// <summary> /// Get Player Details by Active /// </summary> public List<Player> GetPlayers() { return this.GetPlayersAsync().Result; } /// <summary> /// Get Player Details by Free Agents Asynchronous /// </summary> public Task<List<Player>> GetFreeAgentsAsync() { var parameters = new List<KeyValuePair<string, string>>(); return Task.Run<List<Player>>(() => base.Get<List<Player>>("/v3/mlb/stats/{format}/FreeAgents", parameters) ); } /// <summary> /// Get Player Details by Free Agents /// </summary> public List<Player> GetFreeAgents() { return this.GetFreeAgentsAsync().Result; } /// <summary> /// Get Player Details by Player Asynchronous /// </summary> /// <param name="playerid">Unique FantasyData Player ID. Example:<code>10000507</code>.</param> public Task<Player> GetPlayerAsync(int playerid) { var parameters = new List<KeyValuePair<string, string>>(); parameters.Add(new KeyValuePair<string, string>("playerid", playerid.ToString())); return Task.Run<Player>(() => base.Get<Player>("/v3/mlb/stats/{format}/Player/{playerid}", parameters) ); } /// <summary> /// Get Player Details by Player /// </summary> /// <param name="playerid">Unique FantasyData Player ID. Example:<code>10000507</code>.</param> public Player GetPlayer(int playerid) { return this.GetPlayerAsync(playerid).Result; } /// <summary> /// Get Player Game Stats by Date Asynchronous /// </summary> /// <param name="date">The date of the game(s). Examples: <code>2017-JUL-31</code>, <code>2017-SEP-01</code>.</param> public Task<List<PlayerGame>> GetPlayerGameStatsByDateAsync(string date) { var parameters = new List<KeyValuePair<string, string>>(); parameters.Add(new KeyValuePair<string, string>("date", date.ToString())); return Task.Run<List<PlayerGame>>(() => base.Get<List<PlayerGame>>("/v3/mlb/stats/{format}/PlayerGameStatsByDate/{date}", parameters) ); } /// <summary> /// Get Player Game Stats by Date /// </summary> /// <param name="date">The date of the game(s). Examples: <code>2017-JUL-31</code>, <code>2017-SEP-01</code>.</param> public List<PlayerGame> GetPlayerGameStatsByDate(string date) { return this.GetPlayerGameStatsByDateAsync(date).Result; } /// <summary> /// Get Player Game Stats by Player Asynchronous /// </summary> /// <param name="date">The date of the game(s). Examples: <code>2017-JUL-31</code>, <code>2017-SEP-01</code>.</param> /// <param name="playerid">Unique FantasyData Player ID. Example:<code>10000507</code>.</param> public Task<PlayerGame> GetPlayerGameStatsByPlayerAsync(string date, int playerid) { var parameters = new List<KeyValuePair<string, string>>(); parameters.Add(new KeyValuePair<string, string>("date", date.ToString())); parameters.Add(new KeyValuePair<string, string>("playerid", playerid.ToString())); return Task.Run<PlayerGame>(() => base.Get<PlayerGame>("/v3/mlb/stats/{format}/PlayerGameStatsByPlayer/{date}/{playerid}", parameters) ); } /// <summary> /// Get Player Game Stats by Player /// </summary> /// <param name="date">The date of the game(s). Examples: <code>2017-JUL-31</code>, <code>2017-SEP-01</code>.</param> /// <param name="playerid">Unique FantasyData Player ID. Example:<code>10000507</code>.</param> public PlayerGame GetPlayerGameStatsByPlayer(string date, int playerid) { return this.GetPlayerGameStatsByPlayerAsync(date, playerid).Result; } /// <summary> /// Get Player Season Away Stats Asynchronous /// </summary> /// <param name="season">Year of the season. Examples: <code>2017</code>, <code>2018</code>.</param> public Task<List<PlayerSeason>> GetPlayerSeasonAwayStatsAsync(string season) { var parameters = new List<KeyValuePair<string, string>>(); parameters.Add(new KeyValuePair<string, string>("season", season.ToString())); return Task.Run<List<PlayerSeason>>(() => base.Get<List<PlayerSeason>>("/v3/mlb/stats/{format}/PlayerSeasonAwayStats/{season}", parameters) ); } /// <summary> /// Get Player Season Away Stats /// </summary> /// <param name="season">Year of the season. Examples: <code>2017</code>, <code>2018</code>.</param> public List<PlayerSeason> GetPlayerSeasonAwayStats(string season) { return this.GetPlayerSeasonAwayStatsAsync(season).Result; } /// <summary> /// Get Player Season Home Stats Asynchronous /// </summary> /// <param name="season">Year of the season. Examples: <code>2017</code>, <code>2018</code>.</param> public Task<List<PlayerSeason>> GetPlayerSeasonHomeStatsAsync(string season) { var parameters = new List<KeyValuePair<string, string>>(); parameters.Add(new KeyValuePair<string, string>("season", season.ToString())); return Task.Run<List<PlayerSeason>>(() => base.Get<List<PlayerSeason>>("/v3/mlb/stats/{format}/PlayerSeasonHomeStats/{season}", parameters) ); } /// <summary> /// Get Player Season Home Stats /// </summary> /// <param name="season">Year of the season. Examples: <code>2017</code>, <code>2018</code>.</param> public List<PlayerSeason> GetPlayerSeasonHomeStats(string season) { return this.GetPlayerSeasonHomeStatsAsync(season).Result; } /// <summary> /// Get Player Season Split Stats Asynchronous /// </summary> /// <param name="season">Year of the season. Examples: <code>2017</code>, <code>2018</code>.</param> /// <param name="split">The desired split of stats. Currently, we support vs. Left/Right/Switch handed pitchers/hitters. Possible values are: <code>L</code>, <code>R</code> and <code>S</code></param> public Task<List<PlayerSeason>> GetPlayerSeasonSplitStatsAsync(string season, string split) { var parameters = new List<KeyValuePair<string, string>>(); parameters.Add(new KeyValuePair<string, string>("season", season.ToString())); parameters.Add(new KeyValuePair<string, string>("split", split.ToString())); return Task.Run<List<PlayerSeason>>(() => base.Get<List<PlayerSeason>>("/v3/mlb/stats/{format}/PlayerSeasonSplitStats/{season}/{split}", parameters) ); } /// <summary> /// Get Player Season Split Stats /// </summary> /// <param name="season">Year of the season. Examples: <code>2017</code>, <code>2018</code>.</param> /// <param name="split">The desired split of stats. Currently, we support vs. Left/Right/Switch handed pitchers/hitters. Possible values are: <code>L</code>, <code>R</code> and <code>S</code></param> public List<PlayerSeason> GetPlayerSeasonSplitStats(string season, string split) { return this.GetPlayerSeasonSplitStatsAsync(season, split).Result; } /// <summary> /// Get Player Season Stats Asynchronous /// </summary> /// <param name="season">Year of the season. Examples: <code>2017</code>, <code>2018</code>.</param> public Task<List<PlayerSeason>> GetPlayerSeasonStatsAsync(string season) { var parameters = new List<KeyValuePair<string, string>>(); parameters.Add(new KeyValuePair<string, string>("season", season.ToString())); return Task.Run<List<PlayerSeason>>(() => base.Get<List<PlayerSeason>>("/v3/mlb/stats/{format}/PlayerSeasonStats/{season}", parameters) ); } /// <summary> /// Get Player Season Stats /// </summary> /// <param name="season">Year of the season. Examples: <code>2017</code>, <code>2018</code>.</param> public List<PlayerSeason> GetPlayerSeasonStats(string season) { return this.GetPlayerSeasonStatsAsync(season).Result; } /// <summary> /// Get Player Season Stats By Player Asynchronous /// </summary> /// <param name="season">Year of the season. Examples: <code>2017</code>, <code>2018</code>.</param> /// <param name="playerid">Unique FantasyData Player ID. Example:<code>10000507</code>.</param> public Task<PlayerSeason> GetPlayerSeasonStatsByPlayerAsync(string season, int playerid) { var parameters = new List<KeyValuePair<string, string>>(); parameters.Add(new KeyValuePair<string, string>("season", season.ToString())); parameters.Add(new KeyValuePair<string, string>("playerid", playerid.ToString())); return Task.Run<PlayerSeason>(() => base.Get<PlayerSeason>("/v3/mlb/stats/{format}/PlayerSeasonStatsByPlayer/{season}/{playerid}", parameters) ); } /// <summary> /// Get Player Season Stats By Player /// </summary> /// <param name="season">Year of the season. Examples: <code>2017</code>, <code>2018</code>.</param> /// <param name="playerid">Unique FantasyData Player ID. Example:<code>10000507</code>.</param> public PlayerSeason GetPlayerSeasonStatsByPlayer(string season, int playerid) { return this.GetPlayerSeasonStatsByPlayerAsync(season, playerid).Result; } /// <summary> /// Get Player Season Stats by Team Asynchronous /// </summary> /// <param name="season">Year of the season. Examples: <code>2017</code>, <code>2018</code>.</param> /// <param name="team">The abbreviation of the requested team. Examples: <code>SF</code>, <code>NYY</code>.</param> public Task<List<PlayerSeason>> GetPlayerSeasonStatsByTeamAsync(string season, string team) { var parameters = new List<KeyValuePair<string, string>>(); parameters.Add(new KeyValuePair<string, string>("season", season.ToString())); parameters.Add(new KeyValuePair<string, string>("team", team.ToString())); return Task.Run<List<PlayerSeason>>(() => base.Get<List<PlayerSeason>>("/v3/mlb/stats/{format}/PlayerSeasonStatsByTeam/{season}/{team}", parameters) ); } /// <summary> /// Get Player Season Stats by Team /// </summary> /// <param name="season">Year of the season. Examples: <code>2017</code>, <code>2018</code>.</param> /// <param name="team">The abbreviation of the requested team. Examples: <code>SF</code>, <code>NYY</code>.</param> public List<PlayerSeason> GetPlayerSeasonStatsByTeam(string season, string team) { return this.GetPlayerSeasonStatsByTeamAsync(season, team).Result; } /// <summary> /// Get Player Season Stats Split By Team Asynchronous /// </summary> /// <param name="season">Year of the season. Examples: <code>2017</code>, <code>2018</code>.</param> public Task<List<PlayerSeason>> GetPlayerSeasonStatsSplitByTeamAsync(string season) { var parameters = new List<KeyValuePair<string, string>>(); parameters.Add(new KeyValuePair<string, string>("season", season.ToString())); return Task.Run<List<PlayerSeason>>(() => base.Get<List<PlayerSeason>>("/v3/mlb/stats/{format}/PlayerSeasonStatsSplitByTeam/{season}", parameters) ); } /// <summary> /// Get Player Season Stats Split By Team /// </summary> /// <param name="season">Year of the season. Examples: <code>2017</code>, <code>2018</code>.</param> public List<PlayerSeason> GetPlayerSeasonStatsSplitByTeam(string season) { return this.GetPlayerSeasonStatsSplitByTeamAsync(season).Result; } /// <summary> /// Get Players by Team Asynchronous /// </summary> /// <param name="team">The abbreviation of the requested team. Examples: <code>SF</code>, <code>NYY</code>.</param> public Task<List<Player>> GetPlayersAsync(string team) { var parameters = new List<KeyValuePair<string, string>>(); parameters.Add(new KeyValuePair<string, string>("team", team.ToString())); return Task.Run<List<Player>>(() => base.Get<List<Player>>("/v3/mlb/stats/{format}/Players/{team}", parameters) ); } /// <summary> /// Get Players by Team /// </summary> /// <param name="team">The abbreviation of the requested team. Examples: <code>SF</code>, <code>NYY</code>.</param> public List<Player> GetPlayers(string team) { return this.GetPlayersAsync(team).Result; } /// <summary> /// Get Schedules Asynchronous /// </summary> /// <param name="season">Year of the season (with optional season type). Examples: <code>2018</code>, <code>2018PRE</code>, <code>2018POST</code>, <code>2018STAR</code>, <code>2019</code>, etc.</param> public Task<List<Game>> GetGamesAsync(string season) { var parameters = new List<KeyValuePair<string, string>>(); parameters.Add(new KeyValuePair<string, string>("season", season.ToString())); return Task.Run<List<Game>>(() => base.Get<List<Game>>("/v3/mlb/stats/{format}/Games/{season}", parameters) ); } /// <summary> /// Get Schedules /// </summary> /// <param name="season">Year of the season (with optional season type). Examples: <code>2018</code>, <code>2018PRE</code>, <code>2018POST</code>, <code>2018STAR</code>, <code>2019</code>, etc.</param> public List<Game> GetGames(string season) { return this.GetGamesAsync(season).Result; } /// <summary> /// Get Stadiums Asynchronous /// </summary> public Task<List<Stadium>> GetStadiumsAsync() { var parameters = new List<KeyValuePair<string, string>>(); return Task.Run<List<Stadium>>(() => base.Get<List<Stadium>>("/v3/mlb/stats/{format}/Stadiums", parameters) ); } /// <summary> /// Get Stadiums /// </summary> public List<Stadium> GetStadiums() { return this.GetStadiumsAsync().Result; } /// <summary> /// Get Standings Asynchronous /// </summary> /// <param name="season">Year of the season. Examples: <code>2017</code>, <code>2018</code>.</param> public Task<List<Standing>> GetStandingsAsync(string season) { var parameters = new List<KeyValuePair<string, string>>(); parameters.Add(new KeyValuePair<string, string>("season", season.ToString())); return Task.Run<List<Standing>>(() => base.Get<List<Standing>>("/v3/mlb/stats/{format}/Standings/{season}", parameters) ); } /// <summary> /// Get Standings /// </summary> /// <param name="season">Year of the season. Examples: <code>2017</code>, <code>2018</code>.</param> public List<Standing> GetStandings(string season) { return this.GetStandingsAsync(season).Result; } /// <summary> /// Get Team Game Stats by Date Asynchronous /// </summary> /// <param name="date">The date of the game(s). Examples: <code>2017-JUL-31</code>, <code>2017-SEP-01</code>.</param> public Task<List<TeamGame>> GetTeamGameStatsByDateAsync(string date) { var parameters = new List<KeyValuePair<string, string>>(); parameters.Add(new KeyValuePair<string, string>("date", date.ToString())); return Task.Run<List<TeamGame>>(() => base.Get<List<TeamGame>>("/v3/mlb/stats/{format}/TeamGameStatsByDate/{date}", parameters) ); } /// <summary> /// Get Team Game Stats by Date /// </summary> /// <param name="date">The date of the game(s). Examples: <code>2017-JUL-31</code>, <code>2017-SEP-01</code>.</param> public List<TeamGame> GetTeamGameStatsByDate(string date) { return this.GetTeamGameStatsByDateAsync(date).Result; } /// <summary> /// Get Team Hitting vs. Starting Pitcher Asynchronous /// </summary> /// <param name="gameid">The GameID of an MLB game. GameIDs can be found in the Games API. Valid entries are <code>14620</code> or <code>16905</code></param> /// <param name="team">The abbreviation of the requested team. Examples: <code>SF</code>, <code>NYY</code>.</param> public Task<List<PlayerSeason>> GetTeamHittersVsPitcherAsync(int gameid, string team) { var parameters = new List<KeyValuePair<string, string>>(); parameters.Add(new KeyValuePair<string, string>("gameid", gameid.ToString())); parameters.Add(new KeyValuePair<string, string>("team", team.ToString())); return Task.Run<List<PlayerSeason>>(() => base.Get<List<PlayerSeason>>("/v3/mlb/stats/{format}/TeamHittersVsPitcher/{gameid}/{team}", parameters) ); } /// <summary> /// Get Team Hitting vs. Starting Pitcher /// </summary> /// <param name="gameid">The GameID of an MLB game. GameIDs can be found in the Games API. Valid entries are <code>14620</code> or <code>16905</code></param> /// <param name="team">The abbreviation of the requested team. Examples: <code>SF</code>, <code>NYY</code>.</param> public List<PlayerSeason> GetTeamHittersVsPitcher(int gameid, string team) { return this.GetTeamHittersVsPitcherAsync(gameid, team).Result; } /// <summary> /// Get Team Season Stats Asynchronous /// </summary> /// <param name="season">Year of the season. Examples: <code>2017</code>, <code>2018</code>.</param> public Task<List<TeamSeason>> GetTeamSeasonStatsAsync(string season) { var parameters = new List<KeyValuePair<string, string>>(); parameters.Add(new KeyValuePair<string, string>("season", season.ToString())); return Task.Run<List<TeamSeason>>(() => base.Get<List<TeamSeason>>("/v3/mlb/stats/{format}/TeamSeasonStats/{season}", parameters) ); } /// <summary> /// Get Team Season Stats /// </summary> /// <param name="season">Year of the season. Examples: <code>2017</code>, <code>2018</code>.</param> public List<TeamSeason> GetTeamSeasonStats(string season) { return this.GetTeamSeasonStatsAsync(season).Result; } /// <summary> /// Get Teams (Active) Asynchronous /// </summary> public Task<List<Team>> GetTeamsAsync() { var parameters = new List<KeyValuePair<string, string>>(); return Task.Run<List<Team>>(() => base.Get<List<Team>>("/v3/mlb/stats/{format}/teams", parameters) ); } /// <summary> /// Get Teams (Active) /// </summary> public List<Team> GetTeams() { return this.GetTeamsAsync().Result; } /// <summary> /// Get Teams (All) Asynchronous /// </summary> public Task<List<Team>> GetAllTeamsAsync() { var parameters = new List<KeyValuePair<string, string>>(); return Task.Run<List<Team>>(() => base.Get<List<Team>>("/v3/mlb/stats/{format}/AllTeams", parameters) ); } /// <summary> /// Get Teams (All) /// </summary> public List<Team> GetAllTeams() { return this.GetAllTeamsAsync().Result; } } }
44.493724
234
0.581061
[ "MIT" ]
SebastianLng/fantasydata-api-csharp
FantasyData.Api.Client/Clients/MLB/MLBv3Stats.cs
31,904
C#
using Dashboard.Jenkins; namespace Dashboard.Azure.Builds { // TODO: Should use BoundBuildId public struct BuildKey { public BuildId BuildId { get; } public string Key { get; } public BuildKey(BuildId buildId) { BuildId = buildId; Key = GetKey(buildId); } public static string GetKey(BuildId buildId) => $"{buildId.Number}-{AzureUtil.NormalizeKey(buildId.JobName, '_')}"; } }
23.4
123
0.600427
[ "Apache-2.0" ]
jaredpar/jenkins
Dashboard.Storage/Azure/Builds/BuildKey.cs
470
C#
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System.Collections.Generic; using System.Runtime.CompilerServices; namespace Nez.Shadows { /// <summary> /// Point light that also casts shadows /// </summary> public class PolyLight : RenderableComponent { /// <summary> /// layer mask of all the layers this light should interact with. defaults to all layers. /// </summary> public int CollidesWithLayers = Physics.AllLayers; public override RectangleF Bounds { get { if( _areBoundsDirty ) { _bounds.CalculateBounds( Entity.Transform.Position, _localOffset, new Vector2( _radius, _radius ), Vector2.One, 0, _radius * 2f, _radius * 2f ); _areBoundsDirty = false; } return _bounds; } } /// <summary> /// Radius of influence of the light /// </summary> [Range( 0, 2000 )] public float Radius { get => _radius; set => SetRadius( value ); } /// <summary> /// Power of the light, from 0 (turned off) to 1 for maximum brightness /// </summary> [Range( 0, 50 )] public float Power; protected float _radius; protected VisibilityComputer _visibility; Effect _lightEffect; FastList<short> _indices = new FastList<short>( 50 ); FastList<VertexPositionTexture> _vertices = new FastList<VertexPositionTexture>( 20 ); // shared Collider cache used for querying for nearby geometry. Maxes out at 10 Colliders. static protected Collider[] _colliderCache = new Collider[10]; public PolyLight() : this( 400 ) {} public PolyLight( float radius ) : this( radius, Color.White ) { } public PolyLight( float radius, Color color ) : this( radius, color, 1.0f ) { } public PolyLight( float radius, Color color, float power ) { this.Radius = radius; this.Power = power; this.Color = color; ComputeTriangleIndices(); } #region Fluent setters public virtual PolyLight SetRadius( float radius ) { if( radius != _radius ) { _radius = radius; _areBoundsDirty = true; if( _lightEffect != null ) _lightEffect.Parameters["lightRadius"].SetValue( radius ); } return this; } public PolyLight SetPower( float power ) { this.Power = power; return this; } #endregion /// <summary> /// fetches any Colliders that should be considered for occlusion. Subclasses with a shape other than a circle can override this. /// </summary> /// <returns>The overlapped components.</returns> protected virtual int GetOverlappedColliders() { return Physics.OverlapCircleAll( Entity.Position + _localOffset, _radius, _colliderCache, CollidesWithLayers ); } /// <summary> /// override point for calling through to VisibilityComputer that allows subclasses to setup their visibility boundaries for /// different shaped lights. /// </summary> protected virtual void LoadVisibilityBoundaries() { _visibility.LoadRectangleBoundaries(); } #region Component and RenderableComponent public override void OnAddedToEntity() { _lightEffect = Entity.Scene.Content.LoadEffect<Effect>( "polygonLight", EffectResource.PolygonLightBytes ); _lightEffect.Parameters["lightRadius"].SetValue( Radius ); _visibility = new VisibilityComputer(); } public override void Render( Graphics graphics, Camera camera ) => RenderImpl( graphics, camera, false ); public override void DebugRender( Graphics graphics ) { // here, we just assume the Camera being used by the Renderer is the standard Scene Camera RenderImpl( Graphics.Instance, Entity.Scene.Camera, true ); // draw a square for our pivot/origin and draw our bounds graphics.Batcher.DrawPixel( Entity.Transform.Position + _localOffset, Debug.Colors.RenderableCenter, 4 ); graphics.Batcher.DrawHollowRect( Bounds, Debug.Colors.RenderableBounds ); } void RenderImpl( Graphics graphics, Camera camera, bool debugDraw ) { if( Power > 0 && IsVisibleFromCamera( camera ) ) { var totalOverlaps = GetOverlappedColliders(); // compute the visibility mesh _visibility.Begin( Entity.Transform.Position + _localOffset, _radius ); LoadVisibilityBoundaries(); for( var i = 0; i < totalOverlaps; i++ ) { if( !_colliderCache[i].IsTrigger ) _visibility.AddColliderOccluder( _colliderCache[i] ); } System.Array.Clear( _colliderCache, 0, totalOverlaps ); // generate a triangle list from the encounter points var encounters = _visibility.End(); GenerateVertsFromEncounters( encounters ); ListPool<Vector2>.Free( encounters ); var primitiveCount = _vertices.Length / 2; if( primitiveCount == 0 ) return; Core.GraphicsDevice.BlendState = BlendState.Additive; Core.GraphicsDevice.RasterizerState = RasterizerState.CullNone; if( debugDraw ) { var rasterizerState = new RasterizerState(); rasterizerState.FillMode = FillMode.WireFrame; rasterizerState.CullMode = CullMode.None; Core.GraphicsDevice.RasterizerState = rasterizerState; } // Apply the effect _lightEffect.Parameters["viewProjectionMatrix"].SetValue( camera.ViewProjectionMatrix ); _lightEffect.Parameters["lightSource"].SetValue( Entity.Transform.Position ); _lightEffect.Parameters["lightColor"].SetValue( Color.ToVector3() * Power ); _lightEffect.Techniques[0].Passes[0].Apply(); Core.GraphicsDevice.DrawUserIndexedPrimitives( PrimitiveType.TriangleList, _vertices.Buffer, 0, _vertices.Length, _indices.Buffer, 0, primitiveCount ); } } #endregion /// <summary> /// adds a vert to the list /// </summary> /// <param name="position">Position.</param> /// <param name="texCoord">Tex coordinate.</param> [MethodImpl( MethodImplOptions.AggressiveInlining )] void AddVert( Vector2 position ) { var index = _vertices.Length; _vertices.EnsureCapacity(); _vertices.Buffer[index].Position = position.ToVector3(); _vertices.Buffer[index].TextureCoordinate = position; _vertices.Length++; } void ComputeTriangleIndices( int totalTris = 20 ) { _indices.Reset(); // compute the indices to form triangles for( var i = 0; i < totalTris; i += 2 ) { _indices.Add( 0 ); _indices.Add( (short)( i + 2 ) ); _indices.Add( (short)( i + 1 ) ); } } void GenerateVertsFromEncounters( List<Vector2> encounters ) { _vertices.Reset(); // add a vertex for the center of the mesh AddVert( Entity.Transform.Position ); // add all the other encounter points as vertices storing their world position as UV coordinates for( var i = 0; i < encounters.Count; i++ ) AddVert( encounters[i] ); // if we dont have enough tri indices add enough for our encounter list var triIndices = _indices.Length / 3; if( encounters.Count > triIndices ) ComputeTriangleIndices( encounters.Count ); } } }
28.810924
155
0.698994
[ "Apache-2.0", "MIT" ]
v-karpov/Nez
Nez.Portable/ECS/Components/Renderables/PolygonLight/PolyLight.cs
6,859
C#
#region copyright // // Copyright (c) DOT Consulting scrl. All rights reserved. // Licensed under the provided EULA. See EULA file in the solution root for full license information. // #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; namespace Dotc.MQExplorerPlus.Core.Models.Parser { public sealed class ParsingResultNodeList : ObservableCollection<ParsingResultNode> { public void Reset() { foreach (var item in Items) { item.Reset(); } } public ParsingResultNodeList Clone() { var copy = new ParsingResultNodeList(); foreach (var node in this) { copy.Add(node.Clone()); } return copy; } public void AddRange(IEnumerable<ParsingResultNode> nodes) { if (nodes == null) throw new ArgumentNullException(nameof(nodes)); foreach (var node in nodes) { Add(node); } } } }
25.627907
103
0.566243
[ "MIT" ]
bgiot/mqexplorerplus
src/Dotc.MQExplorerPlus.Core/Models/Parser/ParsingResultNodeList.cs
1,104
C#
namespace CCode.Authentication.External { public class ExternalAuthUserInfo { public string ProviderKey { get; set; } public string Name { get; set; } public string EmailAddress { get; set; } public string Surname { get; set; } public string Provider { get; set; } } }
20.375
48
0.610429
[ "MIT" ]
AmayerGogh/CCode
aspnet-core/src/CCode.Web.Core/Authentication/External/ExternalAuthUserInfo.cs
328
C#
namespace Meziantou.Framework.Win32; public static class Privileges { public const string SE_ASSIGNPRIMARYTOKEN_NAME = "SeAssignPrimaryTokenPrivilege"; public const string SE_AUDIT_NAME = "SeAuditPrivilege"; public const string SE_BACKUP_NAME = "SeBackupPrivilege"; public const string SE_CHANGE_NOTIFY_NAME = "SeChangeNotifyPrivilege"; public const string SE_CREATE_GLOBAL_NAME = "SeCreateGlobalPrivilege"; public const string SE_CREATE_PAGEFILE_NAME = "SeCreatePagefilePrivilege"; public const string SE_CREATE_PERMANENT_NAME = "SeCreatePermanentPrivilege"; public const string SE_CREATE_SYMBOLIC_LINK_NAME = "SeCreateSymbolicLinkPrivilege"; public const string SE_CREATE_TOKEN_NAME = "SeCreateTokenPrivilege"; public const string SE_DEBUG_NAME = "SeDebugPrivilege"; public const string SE_ENABLE_DELEGATION_NAME = "SeEnableDelegationPrivilege"; public const string SE_IMPERSONATE_NAME = "SeImpersonatePrivilege"; public const string SE_INC_BASE_PRIORITY_NAME = "SeIncreaseBasePriorityPrivilege"; public const string SE_INCREASE_QUOTA_NAME = "SeIncreaseQuotaPrivilege"; public const string SE_INC_WORKING_SET_NAME = "SeIncreaseWorkingSetPrivilege"; public const string SE_LOAD_DRIVER_NAME = "SeLoadDriverPrivilege"; public const string SE_LOCK_MEMORY_NAME = "SeLockMemoryPrivilege"; public const string SE_MACHINE_ACCOUNT_NAME = "SeMachineAccountPrivilege"; public const string SE_MANAGE_VOLUME_NAME = "SeManageVolumePrivilege"; public const string SE_PROF_SINGLE_PROCESS_NAME = "SeProfileSingleProcessPrivilege"; public const string SE_RELABEL_NAME = "SeRelabelPrivilege"; public const string SE_REMOTE_SHUTDOWN_NAME = "SeRemoteShutdownPrivilege"; public const string SE_RESTORE_NAME = "SeRestorePrivilege"; public const string SE_SECURITY_NAME = "SeSecurityPrivilege"; public const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege"; public const string SE_SYNC_AGENT_NAME = "SeSyncAgentPrivilege"; public const string SE_SYSTEM_ENVIRONMENT_NAME = "SeSystemEnvironmentPrivilege"; public const string SE_SYSTEM_PROFILE_NAME = "SeSystemProfilePrivilege"; public const string SE_SYSTEMTIME_NAME = "SeSystemtimePrivilege"; public const string SE_TAKE_OWNERSHIP_NAME = "SeTakeOwnershipPrivilege"; public const string SE_TCB_NAME = "SeTcbPrivilege"; public const string SE_TIME_ZONE_NAME = "SeTimeZonePrivilege"; public const string SE_TRUSTED_CREDMAN_ACCESS_NAME = "SeTrustedCredManAccessPrivilege"; public const string SE_UNDOCK_NAME = "SeUndockPrivilege"; public const string SE_UNSOLICITED_INPUT_NAME = "SeUnsolicitedInputPrivilege"; }
63.560976
89
0.833461
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
Ordisoftware/Hebrew-Lettriq
Project/Dependencies/Meziantou.AccessToken/Privileges.cs
2,606
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; public class NetBoard : NetworkBehaviour { public int[,] grid { get; private set; } [SyncVar] public ChessType turn; public GameObject[] chessPrefabs; public Stack<GameObject> chessPath; // Use this for initialization void Start() { chessPath = new Stack<GameObject>(); grid = new int[15, 15]; turn = ChessType.black; } public void Play(int[] pos) { if (grid[pos[0], pos[1]] != 0) return; GameObject temp = Instantiate(chessPrefabs[(int)turn - 1], new Vector3(pos[0], pos[1], -1), Quaternion.identity); chessPath.Push(temp); NetworkServer.Spawn(temp); grid[pos[0], pos[1]] = (int)turn; if (CheckWiner(pos)) { Debug.Log(turn + "胜"); Time.timeScale = 0; } if (turn == ChessType.black) { turn = ChessType.white; } else { turn = ChessType.black; } } [Server] bool CheckWiner(int[] pos) { if (CheckOneline(pos, new int[] { 1, 0 })) return true; if (CheckOneline(pos, new int[] { 1, 1 })) return true; if (CheckOneline(pos, new int[] { 1, -1 })) return true; if (CheckOneline(pos, new int[] { 0, 1 })) return true; return false; } bool CheckOneline(int[] pos, int[] offset) { int sum = 1; for (int x = pos[0] + offset[0], y = pos[1] + offset[1]; x < 15 && x >= 0 && y < 15 && y >= 0; x += offset[0], y += offset[1]) { if (grid[x, y] == (int)turn) { sum++; } else { break; } } for (int x = pos[0] - offset[0], y = pos[1] - offset[1]; x < 15 && x >= 0 && y < 15 && y >= 0; x -= offset[0], y -= offset[1]) { if (grid[x, y] == (int)turn) { sum++; } else { break; } } if (sum >= 5) { return true; } return false; } public void ReSetChess() { if (chessPath.Count > 0) { GameObject temp = chessPath.Pop(); grid[(int)(temp.transform.position.x), (int)(temp.transform.position.y)] = 0; Destroy(temp); } if (chessPath.Count > 0) { GameObject temp = chessPath.Pop(); grid[(int)(temp.transform.position.x), (int)(temp.transform.position.y)] = 0; Destroy(temp); } } // Update is called once per frame void Update() { } }
26.209524
134
0.470567
[ "MIT" ]
QinZhuo/FivePointAI
1/NetBoard.cs
2,756
C#
using Stratis.Bitcoin.Tests.Common.TestFramework; using Xunit; // Disable warnings about "this" qualifier to make the Specification more readable // ReSharper disable ArrangeThisQualifier namespace Stratis.Bitcoin.IntegrationTests.Transactions { public partial class TransactionWithNullDataSpecification : BddSpecification { [Fact] public void A_nulldata_transaction_is_sent_to_the_network() { Given(two_proof_of_work_nodes); And(a_sending_and_a_receiving_wallet); And(some_funds_in_the_sending_wallet); And(no_fund_in_the_receiving_wallet); And(the_wallets_are_in_sync); And(a_nulldata_transaction); When(the_transaction_is_broadcasted); And(the_block_is_mined); Then(the_transaction_should_get_confirmed); And(the_transaction_should_appear_in_the_blockchain); } } }
34.62963
82
0.71016
[ "MIT" ]
BreezeHub/StratisBitcoinFullNode
src/Stratis.Bitcoin.IntegrationTests/Transactions/TransactionWithNullDataSpecification.cs
937
C#
using System; using System.Threading.Tasks; using MQTTnet.Implementations; using MQTTnet.Internal; namespace MQTTnet.Server { public sealed class MqttServerMultiThreadedApplicationMessageInterceptorDelegate : IMqttServerApplicationMessageInterceptor { readonly Func<MqttApplicationMessageInterceptorContext, Task> _callback; public MqttServerMultiThreadedApplicationMessageInterceptorDelegate(Action<MqttApplicationMessageInterceptorContext> callback) { if (callback == null) throw new ArgumentNullException(nameof(callback)); _callback = context => { callback(context); return PlatformAbstractionLayer.CompletedTask; }; } public Func<MqttApplicationMessageInterceptorContext, Exception, Task> ExceptionHandler { get; set; } public MqttServerMultiThreadedApplicationMessageInterceptorDelegate(Func<MqttApplicationMessageInterceptorContext, Task> callback) { _callback = callback ?? throw new ArgumentNullException(nameof(callback)); } public Task InterceptApplicationMessagePublishAsync(MqttApplicationMessageInterceptorContext context) { TaskEx.Run(async () => { try { await _callback.Invoke(context).ConfigureAwait(false); } catch (Exception exception) { var exceptionHandler = ExceptionHandler; if (exceptionHandler != null) { await exceptionHandler.Invoke(context, exception).ConfigureAwait(false); } } }).RunInBackground(); return PlatformAbstractionLayer.CompletedTask; } } }
36.235294
138
0.62987
[ "MIT" ]
azraelrabbit/MQTTnet
MQTTnetFX/Server/MqttServerMultiThreadedApplicationMessageInterceptorDelegate.cs
1,848
C#
using System.ComponentModel.DataAnnotations; using Orchard.ContentManagement; using Orchard.ContentManagement.Records; namespace Piedone.Facebook.Suite.Models { /// <summary> /// Base class for social plugin settings part records /// </summary> public abstract class SocialPluginPartRecord : ContentPartRecord { public virtual int Width { get; set; } public virtual string ColorScheme { get; set; } public SocialPluginPartRecord() { Width = 500; ColorScheme = "light"; } } /// <summary> /// Base class for social plugin settings parts /// </summary> /// <typeparam name="TSocialPluginPartRecord">A child of SocialPluginPartRecord</typeparam> public abstract class SocialPluginPart<TRecord> : ContentPart<TRecord> where TRecord : SocialPluginPartRecord { [Required] public int Width { get { return Record.Width; } set { Record.Width = value; } } [Required] public string ColorScheme { get { return Record.ColorScheme; } set { Record.ColorScheme = value; } } } }
27.930233
95
0.610325
[ "BSD-3-Clause" ]
Trifectgaming/Trifect-CMS
Modules/Piedone.Facebook.Suite/Models/SocialPlugin.cs
1,203
C#
// Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace MassTransit.AzureServiceBusTransport { using System; using Configuration; public static class TransportConfiguratorExtensions { public static IServiceBusHost Host(this IServiceBusBusFactoryConfigurator configurator, Uri hostAddress, Action<IServiceBusHostConfigurator> configure) { var hostConfigurator = new AzureServiceBusHostConfigurator(hostAddress); configure(hostConfigurator); return configurator.Host(hostConfigurator.Settings); } public static void SharedAccessSignature(this IServiceBusHostConfigurator configurator, Action<ISharedAccessSignatureTokenProviderConfigurator> configure) { var tokenProviderConfigurator = new SharedAccessSignatureTokenProviderConfigurator(); configure(tokenProviderConfigurator); configurator.TokenProvider = tokenProviderConfigurator.GetTokenProvider(); } } }
40.512195
113
0.712222
[ "Apache-2.0" ]
lsfera/MassTransit
src/MassTransit.AzureServiceBusTransport/TransportConfiguratorExtensions.cs
1,663
C#
/* * 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 FluentAssertions; using Koralium.SqlParser.Expressions; using Koralium.SqlParser.Literals; using NUnit.Framework; using System.Collections.Generic; using System.Linq; namespace Koralium.SqlParser.Tests { public class QueryBuilderTests { [Test] public void TestBooleanComparisionEquals() { var actual = QueryBuilder.BooleanExpression<TestClass>(x => x.String == "test"); var expected = new BooleanComparisonExpression() { Type = BooleanComparisonType.Equals, Left = new ColumnReference() { Identifiers = new List<string>() { "String" }, }, Right = new StringLiteral() { Value = "test" } }; actual.Should().BeEquivalentTo(expected, x => x.RespectingRuntimeTypes()); } [Test] public void TestBooleanComparisionGreaterThan() { var actual = QueryBuilder.BooleanExpression<TestClass>(x => x.Long > 3); var expected = new BooleanComparisonExpression() { Type = BooleanComparisonType.GreaterThan, Left = new ColumnReference() { Identifiers = new List<string>() { "Long" }, }, Right = new IntegerLiteral() { Value = 3 } }; actual.Should().BeEquivalentTo(expected, x => x.RespectingRuntimeTypes()); } [Test] public void TestBooleanComparisionGreaterThanOrEqualTo() { var actual = QueryBuilder.BooleanExpression<TestClass>(x => x.Long >= 3); var expected = new BooleanComparisonExpression() { Type = BooleanComparisonType.GreaterThanOrEqualTo, Left = new ColumnReference() { Identifiers = new List<string>() { "Long" }, }, Right = new IntegerLiteral() { Value = 3 } }; actual.Should().BeEquivalentTo(expected, x => x.RespectingRuntimeTypes()); } [Test] public void TestBooleanComparisionLessThan() { var actual = QueryBuilder.BooleanExpression<TestClass>(x => x.Long < 3); var expected = new BooleanComparisonExpression() { Type = BooleanComparisonType.LessThan, Left = new ColumnReference() { Identifiers = new List<string>() { "Long" }, }, Right = new IntegerLiteral() { Value = 3 } }; actual.Should().BeEquivalentTo(expected, x => x.RespectingRuntimeTypes()); } [Test] public void TestBooleanComparisionLessThanOrEqualTo() { var actual = QueryBuilder.BooleanExpression<TestClass>(x => x.Long <= 3); var expected = new BooleanComparisonExpression() { Type = BooleanComparisonType.LessThanOrEqualTo, Left = new ColumnReference() { Identifiers = new List<string>() { "Long" }, }, Right = new IntegerLiteral() { Value = 3 } }; actual.Should().BeEquivalentTo(expected, x => x.RespectingRuntimeTypes()); } [Test] public void TestBooleanComparisionNotEqualTo() { var actual = QueryBuilder.BooleanExpression<TestClass>(x => x.Long != 3); var expected = new BooleanComparisonExpression() { Type = BooleanComparisonType.NotEqualTo, Left = new ColumnReference() { Identifiers = new List<string>() { "Long" }, }, Right = new IntegerLiteral() { Value = 3 } }; actual.Should().BeEquivalentTo(expected, x => x.RespectingRuntimeTypes()); } [Test] public void TestBooleanComparisionEqualsString() { var actual = QueryBuilder.BooleanExpression<TestClass>(x => x.String.CompareTo("test") == 0); var expected = new BooleanComparisonExpression() { Type = BooleanComparisonType.Equals, Left = new ColumnReference() { Identifiers = new List<string>() { "String" }, }, Right = new StringLiteral() { Value = "test" } }; actual.Should().BeEquivalentTo(expected, x => x.RespectingRuntimeTypes()); } [Test] public void TestBooleanComparisionNotEqualsString() { var actual = QueryBuilder.BooleanExpression<TestClass>(x => x.String.CompareTo("test") != 0); var expected = new BooleanComparisonExpression() { Type = BooleanComparisonType.NotEqualTo, Left = new ColumnReference() { Identifiers = new List<string>() { "String" }, }, Right = new StringLiteral() { Value = "test" } }; actual.Should().BeEquivalentTo(expected, x => x.RespectingRuntimeTypes()); } [Test] public void TestBooleanComparisionGreaterThanString() { var actual = QueryBuilder.BooleanExpression<TestClass>(x => x.String.CompareTo("test") > 0); var expected = new BooleanComparisonExpression() { Type = BooleanComparisonType.GreaterThan, Left = new ColumnReference() { Identifiers = new List<string>() { "String" }, }, Right = new StringLiteral() { Value = "test" } }; actual.Should().BeEquivalentTo(expected, x => x.RespectingRuntimeTypes()); } [Test] public void TestBooleanComparisionGreaterThanOrEqualsString() { var actual = QueryBuilder.BooleanExpression<TestClass>(x => x.String.CompareTo("test") >= 0); var expected = new BooleanComparisonExpression() { Type = BooleanComparisonType.GreaterThanOrEqualTo, Left = new ColumnReference() { Identifiers = new List<string>() { "String" }, }, Right = new StringLiteral() { Value = "test" } }; actual.Should().BeEquivalentTo(expected, x => x.RespectingRuntimeTypes()); } [Test] public void TestBooleanComparisionLessThanString() { var actual = QueryBuilder.BooleanExpression<TestClass>(x => x.String.CompareTo("test") < 0); var expected = new BooleanComparisonExpression() { Type = BooleanComparisonType.LessThan, Left = new ColumnReference() { Identifiers = new List<string>() { "String" }, }, Right = new StringLiteral() { Value = "test" } }; actual.Should().BeEquivalentTo(expected, x => x.RespectingRuntimeTypes()); } [Test] public void TestBooleanComparisionLessThanOrEqualToString() { var actual = QueryBuilder.BooleanExpression<TestClass>(x => x.String.CompareTo("test") <= 0); var expected = new BooleanComparisonExpression() { Type = BooleanComparisonType.LessThanOrEqualTo, Left = new ColumnReference() { Identifiers = new List<string>() { "String" }, }, Right = new StringLiteral() { Value = "test" } }; actual.Should().BeEquivalentTo(expected, x => x.RespectingRuntimeTypes()); } [Test] public void TestBooleanBinaryAnd() { var actual = QueryBuilder.BooleanExpression<TestClass>(x => x.Long == 0 && x.String == "test"); var expected = new BooleanBinaryExpression() { Left = new BooleanComparisonExpression() { Type = BooleanComparisonType.Equals, Left = new ColumnReference() { Identifiers = new List<string>() { "Long" }, }, Right = new IntegerLiteral() { Value = 0 } }, Right = new BooleanComparisonExpression() { Type = BooleanComparisonType.Equals, Left = new ColumnReference() { Identifiers = new List<string>() { "String" }, }, Right = new StringLiteral() { Value = "test" } }, Type = BooleanBinaryType.AND }; actual.Should().BeEquivalentTo(expected, x => x.RespectingRuntimeTypes()); } [Test] public void TestBooleanBinaryOr() { var actual = QueryBuilder.BooleanExpression<TestClass>(x => x.Long == 0 || x.String == "test"); var expected = new BooleanBinaryExpression() { Left = new BooleanComparisonExpression() { Type = BooleanComparisonType.Equals, Left = new ColumnReference() { Identifiers = new List<string>() { "Long" }, }, Right = new IntegerLiteral() { Value = 0 } }, Right = new BooleanComparisonExpression() { Type = BooleanComparisonType.Equals, Left = new ColumnReference() { Identifiers = new List<string>() { "String" }, }, Right = new StringLiteral() { Value = "test" } }, Type = BooleanBinaryType.OR }; actual.Should().BeEquivalentTo(expected, x => x.RespectingRuntimeTypes()); } [Test] public void TestStringEqualsNull() { var actual = QueryBuilder.BooleanExpression<TestClass>(x => x.String == null); var expected = new BooleanComparisonExpression() { Type = BooleanComparisonType.Equals, Left = new ColumnReference() { Identifiers = new List<string>() { "String" }, }, Right = new NullLiteral() }; actual.Should().BeEquivalentTo(expected, x => x.RespectingRuntimeTypes()); } [Test] public void TestBinaryExpressionAdd() { var actual = QueryBuilder.BooleanExpression<TestClass>(x => (x.Long + 1) == 0); var expected = new BooleanComparisonExpression() { Type = BooleanComparisonType.Equals, Left = new Expressions.BinaryExpression() { Left = new ColumnReference() { Identifiers = new List<string>() { "Long" }, }, Right = new IntegerLiteral() { Value = 1 }, Type = BinaryType.Add }, Right = new IntegerLiteral() { Value = 0 } }; actual.Should().BeEquivalentTo(expected, x => x.RespectingRuntimeTypes()); } [Test] public void TestBinaryExpressionSubtract() { var actual = QueryBuilder.BooleanExpression<TestClass>(x => (x.Long - 1) == 0); var expected = new BooleanComparisonExpression() { Type = BooleanComparisonType.Equals, Left = new Expressions.BinaryExpression() { Left = new ColumnReference() { Identifiers = new List<string>() { "Long" }, }, Right = new IntegerLiteral() { Value = 1 }, Type = BinaryType.Subtract }, Right = new IntegerLiteral() { Value = 0 } }; actual.Should().BeEquivalentTo(expected, x => x.RespectingRuntimeTypes()); } [Test] public void TestBinaryExpressionMultiply() { var actual = QueryBuilder.BooleanExpression<TestClass>(x => (x.Long * 1) == 0); var expected = new BooleanComparisonExpression() { Type = BooleanComparisonType.Equals, Left = new Expressions.BinaryExpression() { Left = new ColumnReference() { Identifiers = new List<string>() { "Long" }, }, Right = new IntegerLiteral() { Value = 1 }, Type = BinaryType.Multiply }, Right = new IntegerLiteral() { Value = 0 } }; actual.Should().BeEquivalentTo(expected, x => x.RespectingRuntimeTypes()); } [Test] public void TestBinaryExpressionDivide() { var actual = QueryBuilder.BooleanExpression<TestClass>(x => (x.Long / 1) == 0); var expected = new BooleanComparisonExpression() { Type = BooleanComparisonType.Equals, Left = new Expressions.BinaryExpression() { Left = new ColumnReference() { Identifiers = new List<string>() { "Long" }, }, Right = new IntegerLiteral() { Value = 1 }, Type = BinaryType.Divide }, Right = new IntegerLiteral() { Value = 0 } }; actual.Should().BeEquivalentTo(expected, x => x.RespectingRuntimeTypes()); } [Test] public void TestStringContains() { var actual = QueryBuilder.BooleanExpression<TestClass>(x => x.String.Contains("test")); var expected = new LikeExpression() { Left = new ColumnReference() { Identifiers = new List<string>() { "String" } }, Right = new StringLiteral() { Value = "%test%" } }; actual.Should().BeEquivalentTo(expected, x => x.RespectingRuntimeTypes()); } [Test] public void TestStringContainsConcat() { var testclass = new TestClass() { String = "test" }; var actual = QueryBuilder.BooleanExpression<TestClass>(x => x.String.Contains(testclass.String + "2")); var expected = new LikeExpression() { Left = new ColumnReference() { Identifiers = new List<string>() { "String" } }, Right = new StringLiteral() { Value = "%test2%" } }; actual.Should().BeEquivalentTo(expected, x => x.RespectingRuntimeTypes()); } [Test] public void TestStringStartsWith() { var actual = QueryBuilder.BooleanExpression<TestClass>(x => x.String.StartsWith("test")); var expected = new LikeExpression() { Left = new ColumnReference() { Identifiers = new List<string>() { "String" } }, Right = new StringLiteral() { Value = "test%" } }; actual.Should().BeEquivalentTo(expected, x => x.RespectingRuntimeTypes()); } [Test] public void TestStringEndsWith() { var actual = QueryBuilder.BooleanExpression<TestClass>(x => x.String.EndsWith("test")); var expected = new LikeExpression() { Left = new ColumnReference() { Identifiers = new List<string>() { "String" } }, Right = new StringLiteral() { Value = "%test" } }; actual.Should().BeEquivalentTo(expected, x => x.RespectingRuntimeTypes()); } [Test] public void TestListContainsString() { List<string> values = new List<string>() { "test1", "test2" }; var actual = QueryBuilder.BooleanExpression<TestClass>(x => values.Contains(x.String)); var expected = new InExpression() { Expression = new ColumnReference() { Identifiers = new List<string>() { "String" } }, Values = values.Select(x => new StringLiteral() { Value = x } as ScalarExpression).ToList() }; actual.Should().BeEquivalentTo(expected, x => x.RespectingRuntimeTypes()); } [Test] public void TestListContainsInteger() { List<int> values = new List<int>() { 3, 17 }; var actual = QueryBuilder.BooleanExpression<TestClass>(x => values.Contains((int)x.Long)); var expected = new InExpression() { Expression = new ColumnReference() { Identifiers = new List<string>() { "Long" } }, Values = values.Select(x => new IntegerLiteral() { Value = x } as ScalarExpression).ToList() }; actual.Should().BeEquivalentTo(expected, x => x.RespectingRuntimeTypes()); } [Test] public void TestListNotContainsString() { List<string> values = new List<string>() { "test1", "test2" }; var actual = QueryBuilder.BooleanExpression<TestClass>(x => !values.Contains(x.String)); var expected = new InExpression() { Expression = new ColumnReference() { Identifiers = new List<string>() { "String" } }, Values = values.Select(x => new StringLiteral() { Value = x } as ScalarExpression).ToList(), Not = true }; actual.Should().BeEquivalentTo(expected, x => x.RespectingRuntimeTypes()); } [Test] [System.Diagnostics.CodeAnalysis.SuppressMessage("Minor Code Smell", "S1940:Boolean checks should not be inverted", Justification = "Required for test case")] public void TestBooleanComparisionInvertedLessThanOrEqualTo() { var actual = QueryBuilder.BooleanExpression<TestClass>(x => !(x.Long <= 3)); var expected = new BooleanComparisonExpression() { Type = BooleanComparisonType.GreaterThan, Left = new ColumnReference() { Identifiers = new List<string>() { "Long" }, }, Right = new IntegerLiteral() { Value = 3 } }; actual.Should().BeEquivalentTo(expected, x => x.RespectingRuntimeTypes()); } [Test] [System.Diagnostics.CodeAnalysis.SuppressMessage("Minor Code Smell", "S1940:Boolean checks should not be inverted", Justification = "Required for test case")] public void TestBooleanComparisionInvertedEquals() { var actual = QueryBuilder.BooleanExpression<TestClass>(x => !(x.String == "test")); var expected = new BooleanComparisonExpression() { Type = BooleanComparisonType.NotEqualTo, Left = new ColumnReference() { Identifiers = new List<string>() { "String" }, }, Right = new StringLiteral() { Value = "test" } }; actual.Should().BeEquivalentTo(expected, x => x.RespectingRuntimeTypes()); } [Test] [System.Diagnostics.CodeAnalysis.SuppressMessage("Minor Code Smell", "S1940:Boolean checks should not be inverted", Justification = "Required for test case")] public void TestBooleanComparisionInvertedNotEqualTo() { var actual = QueryBuilder.BooleanExpression<TestClass>(x => !(x.Long != 3)); var expected = new BooleanComparisonExpression() { Type = BooleanComparisonType.Equals, Left = new ColumnReference() { Identifiers = new List<string>() { "Long" }, }, Right = new IntegerLiteral() { Value = 3 } }; actual.Should().BeEquivalentTo(expected, x => x.RespectingRuntimeTypes()); } [Test] [System.Diagnostics.CodeAnalysis.SuppressMessage("Minor Code Smell", "S1940:Boolean checks should not be inverted", Justification = "Required for test case")] public void TestBooleanComparisionInvertedGreaterThan() { var actual = QueryBuilder.BooleanExpression<TestClass>(x => !(x.Long > 3)); var expected = new BooleanComparisonExpression() { Type = BooleanComparisonType.LessThanOrEqualTo, Left = new ColumnReference() { Identifiers = new List<string>() { "Long" }, }, Right = new IntegerLiteral() { Value = 3 } }; actual.Should().BeEquivalentTo(expected, x => x.RespectingRuntimeTypes()); } [Test] [System.Diagnostics.CodeAnalysis.SuppressMessage("Minor Code Smell", "S1940:Boolean checks should not be inverted", Justification = "Required for test case")] public void TestBooleanComparisionInvertedGreaterThanOrEqualTo() { var actual = QueryBuilder.BooleanExpression<TestClass>(x => !(x.Long >= 3)); var expected = new BooleanComparisonExpression() { Type = BooleanComparisonType.LessThan, Left = new ColumnReference() { Identifiers = new List<string>() { "Long" }, }, Right = new IntegerLiteral() { Value = 3 } }; actual.Should().BeEquivalentTo(expected, x => x.RespectingRuntimeTypes()); } [Test] [System.Diagnostics.CodeAnalysis.SuppressMessage("Minor Code Smell", "S1940:Boolean checks should not be inverted", Justification = "Required for test case")] public void TestBooleanComparisionInvertedLessThan() { var actual = QueryBuilder.BooleanExpression<TestClass>(x => !(x.Long < 3)); var expected = new BooleanComparisonExpression() { Type = BooleanComparisonType.GreaterThanOrEqualTo, Left = new ColumnReference() { Identifiers = new List<string>() { "Long" }, }, Right = new IntegerLiteral() { Value = 3 } }; actual.Should().BeEquivalentTo(expected, x => x.RespectingRuntimeTypes()); } [Test] public void TestInvertedBooleanBinaryAnd() { //Test DeMorgan law for negation var actual = QueryBuilder.BooleanExpression<TestClass>(x => !(x.Long == 0 && x.String == "test")); var expected = new BooleanBinaryExpression() { Left = new BooleanComparisonExpression() { Type = BooleanComparisonType.NotEqualTo, Left = new ColumnReference() { Identifiers = new List<string>() { "Long" }, }, Right = new IntegerLiteral() { Value = 0 } }, Right = new BooleanComparisonExpression() { Type = BooleanComparisonType.NotEqualTo, Left = new ColumnReference() { Identifiers = new List<string>() { "String" }, }, Right = new StringLiteral() { Value = "test" } }, Type = BooleanBinaryType.OR }; actual.Should().BeEquivalentTo(expected, x => x.RespectingRuntimeTypes()); } [Test] public void TestInvertedBooleanBinaryOr() { //Test DeMorgan law for negation var actual = QueryBuilder.BooleanExpression<TestClass>(x => !(x.Long == 0 || x.String == "test")); var expected = new BooleanBinaryExpression() { Left = new BooleanComparisonExpression() { Type = BooleanComparisonType.NotEqualTo, Left = new ColumnReference() { Identifiers = new List<string>() { "Long" }, }, Right = new IntegerLiteral() { Value = 0 } }, Right = new BooleanComparisonExpression() { Type = BooleanComparisonType.NotEqualTo, Left = new ColumnReference() { Identifiers = new List<string>() { "String" }, }, Right = new StringLiteral() { Value = "test" } }, Type = BooleanBinaryType.AND }; actual.Should().BeEquivalentTo(expected, x => x.RespectingRuntimeTypes()); } [Test] public void TestAnyArrayFunction() { var actual = QueryBuilder.BooleanExpression<TestClass>(x => x.IntList.Any(y => y == 1)); var expected = new BooleanScalarExpression() { ScalarExpression = new FunctionCall() { FunctionName = "any_match", Parameters = new List<SqlExpression>() { new ColumnReference() { Identifiers = new List<string>(){ "IntList" } }, new LambdaExpression() { Parameters = new List<string>() { "y" }, Expression = new BooleanComparisonExpression() { Left = new ColumnReference(){ Identifiers = new List<string>() { "y" }}, Right = new IntegerLiteral(){ Value = 1 }, Type = BooleanComparisonType.Equals } } } } }; actual.Should().BeEquivalentTo(expected, x => x.RespectingRuntimeTypes()); } } }
37.61753
166
0.491598
[ "Apache-2.0" ]
rs-swc/Koralium
netcore/tests/Koralium.SqlParser.Tests/QueryBuilderTests.cs
28,328
C#
#region Related components using System; using System.Linq; using System.Dynamic; using System.Collections.Generic; using Newtonsoft.Json.Linq; using net.vieapps.Components.Utility; #endregion namespace net.vieapps.Components.Security { /// <summary> /// Presents a privilege to perform an action on a specified object of a specified service /// </summary> [Serializable] public class Privilege { /// <summary> /// Initializes the privilege /// </summary> public Privilege() : this(null, null, null) { } /// <summary> /// Initializes the privilege /// </summary> /// <param name="serviceName">The name of the service</param> /// <param name="objectName">The name of the service's object</param> /// <param name="role">The privilege role (must matched with <see cref="PrivilegeRole">PrivilegeRole</see> enum)</param> public Privilege(string serviceName, string objectName, string role) : this(serviceName, objectName, null, role) { } /// <summary> /// Initializes the privilege /// </summary> /// <param name="serviceName">The name of the service</param> /// <param name="objectName">The name of the service's object</param> /// <param name="objectIdentity">The identity of the service's object</param> /// <param name="role">The privilege role (must matched with <see cref="PrivilegeRole">PrivilegeRole</see> enum)</param> public Privilege(string serviceName, string objectName, string objectIdentity, string role) : this(serviceName, objectName, objectIdentity, PrivilegeRole.Viewer) => this.Role = Enum.TryParse(role, out PrivilegeRole privilegeRole) ? privilegeRole.ToString() : PrivilegeRole.Viewer.ToString(); /// <summary> /// Initializes the privilege /// </summary> /// <param name="serviceName">The name of the service</param> /// <param name="objectName">The name of the service's object</param> /// <param name="objectIdentity">The identity of the service's object</param> /// <param name="role">The privilege role</param> public Privilege(string serviceName, string objectName, string objectIdentity, PrivilegeRole role) { this.ServiceName = serviceName ?? ""; this.ObjectName = objectName ?? ""; this.ObjectIdentity = objectIdentity ?? ""; this.Role = role.ToString(); this.Actions = new List<string>(); } #region Properties /// <summary> /// Gets or sets the name of service /// </summary> public string ServiceName { get; set; } /// <summary> /// Gets or sets the name of service's object /// </summary> public string ObjectName { get; set; } /// <summary> /// Gets or sets the identity of service's object /// </summary> public string ObjectIdentity { get; set; } /// <summary> /// Gets or sets the working role (must matched with <see cref="PrivilegeRole">PrivilegeRole</see>, if no role was provided then the actions are use to considering the privilege) /// </summary> public string Role { get; set; } /// <summary> /// Gets or sets the working actions can perform /// </summary> public List<string> Actions { get; set; } #endregion /// <summary> /// Gets the JSON of this privilege object /// </summary> /// <returns></returns> public JObject ToJson() => new JObject { { "ServiceName", (this.ServiceName ?? "").Trim().ToLower() }, { "ObjectName", (this.ObjectName ?? "").Trim().ToLower() }, { "ObjectIdentity", (this.ObjectIdentity ?? "").Trim().ToLower() }, { "Role", (this.Role ?? "").Trim() }, { "Actions", (this.Actions ?? new List<string>()).ToJArray() } }; } // -------------------------------------------------------------------------------------------- /// <summary> /// Presents the privileges (access permissions) of a specified service or service's object (means access permissions of a run-time entity) /// </summary> [Serializable] public class Privileges { /// <summary> /// Initializes the privileges /// </summary> public Privileges() : this(false) { } /// <summary> /// Initializes the privileges /// </summary> /// <param name="anonymousCanView">true to allow anonymous can view by default</param> public Privileges(bool anonymousCanView) { if (anonymousCanView) this.ViewableRoles.Add(SystemRole.All.ToString()); } /// <summary> /// Initializes the privileges /// </summary> /// <param name="privileges">The object that contains the privileges</param> public Privileges(JObject privileges) { if (privileges != null) new[] { "Administrative", "Moderate", "Editable", "Contributive", "Viewable", "Downloadable" }.ForEach(name => { var values = privileges.Get<JArray>($"{name}Roles"); if (values != null) this.SetAttributeValue($"{name}Roles", new HashSet<string>(values.Select(value => value is JValue ? (value as JValue).Value as string : null).Where(value => value != null))); values = privileges.Get<JArray>($"{name}Users"); if (values != null) this.SetAttributeValue($"{name}Users", new HashSet<string>(values.Select(value => value is JValue ? (value as JValue).Value as string : null).Where(value => value != null))); }); } /// <summary> /// Initializes the privileges /// </summary> /// <param name="privileges">The object that contains the privileges</param> public Privileges(ExpandoObject privileges) { if (privileges != null) new[] { "Administrative", "Moderate", "Editable", "Contributive", "Viewable", "Downloadable" }.ForEach(name => { var values = privileges.Get<List<string>>($"{name}Roles"); if (values != null) this.SetAttributeValue($"{name}Roles", new HashSet<string>(values.Where(value => !string.IsNullOrWhiteSpace(value)))); values = privileges.Get<List<string>>($"{name}Users"); if (values != null) this.SetAttributeValue($"{name}Users", new HashSet<string>(values.Where(value => !string.IsNullOrWhiteSpace(value)))); }); } #region Properties /// <summary> /// Gets or sets the collection of identity of working roles that able to manage (means full access) /// </summary> public HashSet<string> AdministrativeRoles { get; set; } = new HashSet<string>(); /// <summary> /// Gets or sets the collection of identity of users that able to manage (means full access) /// </summary> public HashSet<string> AdministrativeUsers { get; set; } = new HashSet<string>(); /// <summary> /// Gets or sets the collection of identity of working roles that able to moderate (means moderate all kinds of resources) /// </summary> public HashSet<string> ModerateRoles { get; set; } = new HashSet<string>(); /// <summary> /// Gets or sets the collection of identity of users that able to moderate (means moderate all kinds of resources) /// </summary> public HashSet<string> ModerateUsers { get; set; } = new HashSet<string>(); /// <summary> /// Gets or sets the collection of identity of working roles that able to edit (means create new and re-update the published resources) /// </summary> public HashSet<string> EditableRoles { get; set; } = new HashSet<string>(); /// <summary> /// Gets or sets the collection of identity of users that able to edit (means create new and re-update the published resources) /// </summary> public HashSet<string> EditableUsers { get; set; } = new HashSet<string>(); /// <summary> /// Gets or sets the collection of identity of working roles that able to contribute (means create new and view the published/their own resources) /// </summary> public HashSet<string> ContributiveRoles { get; set; } = new HashSet<string>(); /// <summary> /// Gets or sets the collection of identity of users that able to contribute (means create new and view the published/their own resources) /// </summary> public HashSet<string> ContributiveUsers { get; set; } = new HashSet<string>(); /// <summary> /// Gets or sets the collection of identity of working roles that able to view the details (means read-only on published resources) /// </summary> public HashSet<string> ViewableRoles { get; set; } = new HashSet<string>(); /// <summary> /// Gets or sets the collection of identity of users that able to view the details (means read-only on published resources) /// </summary> public HashSet<string> ViewableUsers { get; set; } = new HashSet<string>(); /// <summary> /// Gets or sets the collection of identity of working roles that able to download files/attachments of the published resources /// </summary> public HashSet<string> DownloadableRoles { get; set; } = new HashSet<string>(); /// <summary> /// Gets or sets the collection of identity of users that able to download files/attachments of the published resources /// </summary> public HashSet<string> DownloadableUsers { get; set; } = new HashSet<string>(); #endregion } }
39.885965
181
0.654058
[ "Apache-2.0" ]
vieapps/Components.Security
Privileges.cs
9,096
C#
using System; using System.Collections.Generic; using System.Linq; using nJocLogic.data; namespace nJocLogic.util.gdl.model.assignments { public class AssignmentsFactory { public static AssignmentsImpl GetAssignmentsForRule(Implication rule, ISentenceDomainModel model, Dictionary<ISentenceForm, FunctionInfo> functionInfoMap, Dictionary<ISentenceForm, ICollection<Fact>> completedSentenceFormValues) { return new AssignmentsImpl(rule, SentenceDomainModels.GetVarDomains(rule, model, SentenceDomainModels.VarDomainOpts.IncludeHead), functionInfoMap, completedSentenceFormValues); } public static AssignmentsImpl GetAssignmentsForRule(Implication rule, Dictionary<TermVariable, ISet<TermObject>> varDomains, Dictionary<ISentenceForm, FunctionInfo> functionInfoMap, Dictionary<ISentenceForm, ICollection<Fact>> completedSentenceFormValues) { return new AssignmentsImpl(rule, varDomains, functionInfoMap, completedSentenceFormValues); } public static AssignmentsImpl GetAssignmentsWithRecursiveInput(Implication rule, ISentenceDomainModel model, ISentenceForm form, Fact input, Dictionary<ISentenceForm, FunctionInfo> functionInfoMap, Dictionary<ISentenceForm, ICollection<Fact>> completedSentenceFormValues) { //Look for the literal(s) in the rule with the sentence form of the //recursive input. This can be tricky if there are multiple matching //literals. var matchingLiterals = rule.Antecedents.Conjuncts.OfType<Fact>().Where(form.Matches).ToList(); var assignmentsList = new List<AssignmentsImpl>(); foreach (Fact matchingLiteral in matchingLiterals) { var preassignment = new TermObjectSubstitution(); preassignment.Add(matchingLiteral.Unify(input)); if (preassignment.NumMappings() > 0) { var assignments = new AssignmentsImpl( preassignment, rule, //TODO: This one getVarDomains call is why a lot of //SentenceModel/DomainModel stuff is required. Can //this be better factored somehow? SentenceDomainModels.GetVarDomains(rule, model, SentenceDomainModels.VarDomainOpts.IncludeHead), functionInfoMap, completedSentenceFormValues); assignmentsList.Add(assignments); } } if (assignmentsList.Count == 0) return new AssignmentsImpl(); if (assignmentsList.Count == 1) return assignmentsList[0]; throw new Exception("Not yet implemented: assignments for recursive functions with multiple recursive conjuncts"); //TODO: Plan to implement by subclassing TermObjectSubstitution into something //that contains and iterates over multiple TermObjectSubstitution } //TODO: Put the constructor that uses the SentenceModel here } }
49.421053
144
0.559904
[ "BSD-3-Clause" ]
druzil/nggp-base
nJocLogic/util/gdl/model/assignments/AssignmentsFactory.cs
3,756
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; using System.Web.Security; using System.Web.SessionState; using System.Web.Http; namespace WebServices { public class Global : HttpApplication { void Application_Start(object sender, EventArgs e) { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); RouteConfig.RegisterRoutes(RouteTable.Routes); } } }
28.210526
65
0.725746
[ "MIT" ]
hwebz/pro-aspnet-mvc-5-fifth-edition
pro-asp.net-mvc-5/Chapter 27/WebServices/WebServices/Global.asax.cs
538
C#
using System.Threading.Tasks; namespace Catalog.API.Infrastructure { public interface ICatalogTagsContextSeed { Task SeedAsync(); } }
17.222222
44
0.703226
[ "MIT" ]
balakrishnavalluri-gep/eShopOnContainersAI
src/Services/Catalog/Catalog.API/Infrastructure/ICatalogTagsContextSeed.cs
157
C#
using System.Windows.Input; using Avalonia.Input; using Avalonia.Threading; using ReactiveUI; namespace Kaigara.Commands; public abstract class RegisteredAsyncCommand : RegisteredCommandBase { public RegisteredAsyncCommand() : base() { } protected RegisteredAsyncCommand(string name, string label, KeyGesture? keyGesture, string? iconName) : base(name, label, keyGesture, iconName) { } protected override ICommand CreateCommand() { return ReactiveCommand.CreateFromTask(OnExecuteAsync, CanExecute, AvaloniaScheduler.Instance); } protected abstract Task OnExecuteAsync(); } public abstract class RegisteredAsyncCommand<TParam> : RegisteredCommandBase { public RegisteredAsyncCommand() : base() { } protected RegisteredAsyncCommand(string name, string label, KeyGesture? keyGesture, string? iconName) : base(name, label, keyGesture, iconName) { } protected override ICommand CreateCommand() { return ReactiveCommand.CreateFromTask<TParam>(OnExecuteAsync, CanExecute, AvaloniaScheduler.Instance); } protected abstract Task OnExecuteAsync(TParam param); }
23.82
110
0.722922
[ "MIT" ]
dfkeenan/Kaigara
Source/Kaigara.Core/Commands/RegisteredAsyncCommand.cs
1,193
C#
using System; using System.Collections.Generic; using System.Text; using Lab_06_Interfaces.Interface; namespace Lab_06_Interfaces.Classes.Fish { public class Shark : Cartilaginous, ISwim { public override bool IsWarmBlooded { get; set; } = false; public string SwimSpeed { get; set; } = "30 mph"; public bool CanBreatheUnderwater { get; set; } = true; public string FlipMeOver() { return "RIP"; } public string Swim() { return "swimming"; } } }
21.461538
65
0.594982
[ "MIT" ]
ecaoile/Lab-06-Interfaces
Lab_06_Interfaces/Lab_06_Interfaces/Classes/Fish/Shark.cs
560
C#
using Ashkatchap.AIBrain.Nodes; using System; using UnityEngine; namespace Ashkatchap.AIBrain { [Serializable] [CreateNode("Order/Succeeder (TRUE)")] public class Succeeder : Node { public NodeTreeOutput child; private bool waiting = true; public override NodeTreeOutput Tick(out ExecutionResult executionResult, ExecutionResult childResult) { if (waiting) { waiting = false; executionResult = ExecutionResult.Running; return child; } else { InterruptExecution(); executionResult = ExecutionResult.Success; return null; } } public override void InterruptExecution() { waiting = true; } public override void Calculate() { } #if UNITY_EDITOR public override void Init() { child = CreateTreeOutput(); } protected override void Draw() { GUILayout.BeginHorizontal(); child.DisplayLayout("Success"); GUILayout.EndHorizontal(); } #endif } }
21.255814
105
0.713348
[ "MIT" ]
forestrf/AshNodeEditor
AshNodeEditor/Assets/AshKatchap/AIBrain/Nodes/Order/Succeeder.cs
916
C#
// Copyright (c) 2017-2019 Jae-jun Kang // See the file LICENSE for details. using System; using System.Collections.Generic; using System.Threading; namespace x2net { public class ThreadlessFlow #if NET40 : ThreadlessFlow<ConcurrentEventQueue> #else : ThreadlessFlow<SynchronizedEventQueue> #endif { public ThreadlessFlow() : base() { } public ThreadlessFlow(string name) : base(name) { } } public class ThreadlessFlow<Q> : EventBasedFlow<Q> where Q : EventQueue, new() { protected bool running; protected List<Event> dequeued; public ThreadlessFlow() { } public ThreadlessFlow(string name) : this() { this.name = name; } public override Flow Start() { lock (syncRoot) { if (!running) { SetupInternal(); caseStack.Setup(this); currentFlow = this; equivalent = new EventEquivalent(); handlerChain = new List<Handler>(); dequeued = new List<Event>(); running = true; queue.Enqueue(new FlowStart()); } } return this; } public override void Stop() { lock (syncRoot) { if (!running) { return; } queue.Close(new FlowStop()); running = false; dequeued = null; handlerChain = null; equivalent = null; currentFlow = null; caseStack.Teardown(this); TeardownInternal(); } } public void Dispatch() { Event e = queue.Dequeue(); if (ReferenceEquals(e, null)) { return; } Dispatch(e); } public Event TryDispatch() { Event e; if (queue.TryDequeue(out e)) { Dispatch(e); return e; } return null; } public int TryDispatchAll() { return TryDispatchAll(null); } public int TryDispatchAll(List<Event> events) { Event e; dequeued.Clear(); while (queue.TryDequeue(out e)) { dequeued.Add(e); } int count = dequeued.Count; if (count != 0) { if (!ReferenceEquals(events, null)) { events.AddRange(dequeued); } for (int i = 0; i < count; ++i) { Dispatch(dequeued[i]); } dequeued.Clear(); } return count; } public bool TryDequeue(out Event e) { return queue.TryDequeue(out e); } /// <summary> /// Wait for a single event of type (T) with timeout in seconds. /// </summary> public bool Wait<T>(T expected, out T actual, double seconds) where T : Event { return Wait(expected, out actual, TimeSpan.FromSeconds(seconds)); } /// <summary> /// Wait for a single event of type (T) with timeout. /// </summary> public bool Wait<T>(T expected, out T actual, TimeSpan timeout) where T : Event { actual = null; var stopWatch = new System.Diagnostics.Stopwatch(); stopWatch.Start(); while (stopWatch.Elapsed < timeout) { Event dequeued; if (queue.TryDequeue(out dequeued)) { Dispatch(dequeued); if (expected.Equivalent(dequeued)) { actual = (T)dequeued; return true; } } Thread.Sleep(1); } return false; } /// <summary> /// Wait for multiple events with timeout in seconds. /// </summary> public bool Wait(double seconds, out Event[] actual, params Event[] expected) { return Wait(TimeSpan.FromSeconds(seconds), out actual, expected); } /// <summary> /// Wait for multiple events with timeout. /// </summary> public bool Wait(TimeSpan timeout, out Event[] actual, params Event[] expected) { int count = 0; actual = new Event[expected.Length]; var stopWatch = new System.Diagnostics.Stopwatch(); stopWatch.Start(); while (stopWatch.Elapsed < timeout) { Event dequeued; if (queue.TryDequeue(out dequeued)) { Dispatch(dequeued); for (int i = 0; i < expected.Length; ++i) { if (actual[i] == null && expected[i].Equivalent(dequeued)) { actual[i] = dequeued; if (++count >= expected.Length) { return true; } break; } } } Thread.Sleep(1); } return false; } } }
26.283105
87
0.422863
[ "MIT" ]
jaykang920/x2net
src/x2net/Flows/ThreadlessFlow.cs
5,758
C#