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
namespace Microsoft.Azure.Management.StorSimple8000Series.Models { using Azure; using Management; using StorSimple8000Series; using Rest; using Rest.Serialization; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// The backup. /// </summary> [JsonTransformation] public partial class Backup : BaseModel { /// <summary> /// Initializes a new instance of the Backup class. /// </summary> public Backup() { } /// <summary> /// Initializes a new instance of the Backup class. /// </summary> /// <param name="createdOn">The time when the backup was /// created.</param> /// <param name="sizeInBytes">The backup size in bytes.</param> /// <param name="elements">The backup elements.</param> /// <param name="id">The path ID that uniquely identifies the /// object.</param> /// <param name="name">The name of the object.</param> /// <param name="type">The hierarchical type of the object.</param> /// <param name="kind">The Kind of the object. Currently only /// Series8000 is supported. Possible values include: /// 'Series8000'</param> /// <param name="backupType">The type of the backup. Possible values /// include: 'LocalSnapshot', 'CloudSnapshot'</param> /// <param name="backupJobCreationType">The backup job creation type. /// Possible values include: 'Adhoc', 'BySchedule', 'BySSM'</param> /// <param name="backupPolicyId">The path ID of the backup /// policy.</param> /// <param name="ssmHostName">The StorSimple Snapshot Manager host /// name.</param> public Backup(System.DateTime createdOn, long sizeInBytes, IList<BackupElement> elements, string id = default(string), string name = default(string), string type = default(string), Kind? kind = default(Kind?), BackupType? backupType = default(BackupType?), BackupJobCreationType? backupJobCreationType = default(BackupJobCreationType?), string backupPolicyId = default(string), string ssmHostName = default(string)) : base(id, name, type, kind) { CreatedOn = createdOn; SizeInBytes = sizeInBytes; BackupType = backupType; BackupJobCreationType = backupJobCreationType; BackupPolicyId = backupPolicyId; SsmHostName = ssmHostName; Elements = elements; } /// <summary> /// Gets or sets the time when the backup was created. /// </summary> [JsonProperty(PropertyName = "properties.createdOn")] public System.DateTime CreatedOn { get; set; } /// <summary> /// Gets or sets the backup size in bytes. /// </summary> [JsonProperty(PropertyName = "properties.sizeInBytes")] public long SizeInBytes { get; set; } /// <summary> /// Gets or sets the type of the backup. Possible values include: /// 'LocalSnapshot', 'CloudSnapshot' /// </summary> [JsonProperty(PropertyName = "properties.backupType")] public BackupType? BackupType { get; set; } /// <summary> /// Gets or sets the backup job creation type. Possible values include: /// 'Adhoc', 'BySchedule', 'BySSM' /// </summary> [JsonProperty(PropertyName = "properties.backupJobCreationType")] public BackupJobCreationType? BackupJobCreationType { get; set; } /// <summary> /// Gets or sets the path ID of the backup policy. /// </summary> [JsonProperty(PropertyName = "properties.backupPolicyId")] public string BackupPolicyId { get; set; } /// <summary> /// Gets or sets the StorSimple Snapshot Manager host name. /// </summary> [JsonProperty(PropertyName = "properties.ssmHostName")] public string SsmHostName { get; set; } /// <summary> /// Gets or sets the backup elements. /// </summary> [JsonProperty(PropertyName = "properties.elements")] public IList<BackupElement> Elements { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (Elements == null) { throw new ValidationException(ValidationRules.CannotBeNull, "Elements"); } if (Elements != null) { foreach (var element in Elements) { if (element != null) { element.Validate(); } } } } } }
38.364341
423
0.581532
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/storsimple8000series/Microsoft.Azure.Management.StorSimple8000Series/src/Generated/Models/Backup.cs
4,949
C#
using System; using System.Text.Json.Serialization; using LessPaper.Shared.Interfaces.WriteApi.WriteObjectApi; namespace LessPaper.WriteService.Models.Response { public class UploadFileResponse : IUploadMetadata { public UploadFileResponse(string objectName, string objectId, uint sizeInBytes, DateTime latestChangeDate, DateTime latestViewDate, uint quickNumber) { ObjectName = objectName; ObjectId = objectId; SizeInBytes = sizeInBytes; LatestChangeDate = latestChangeDate; LatestViewDate = latestViewDate; QuickNumber = quickNumber; } /// <inheritdoc /> [JsonPropertyName("object_name")] public string ObjectName { get; } /// <inheritdoc /> [JsonPropertyName("object_id")] public string ObjectId { get; } /// <inheritdoc /> [JsonPropertyName("size_in_bytes")] public uint SizeInBytes { get; } /// <inheritdoc /> [JsonPropertyName("latest_change_date")] public DateTime LatestChangeDate { get; } /// <inheritdoc /> [JsonPropertyName("latest_view_date")] public DateTime LatestViewDate { get; } /// <inheritdoc /> [JsonPropertyName("quick_number")] public uint QuickNumber { get; } } }
30.613636
157
0.629547
[ "MIT" ]
ChristianHellwig/LessPaper.WriteApi
LessPaper.WriteService/Models/Response/UploadFileResponse.cs
1,349
C#
/******************** * 半人马长期幸福的创造灵感奖励需求类。 * --siiftun1857 */ using RimWorld; using System; using System.Collections.Generic; using UnityEngine; using Verse; using static Explorite.ExploriteCore; namespace Explorite { ///<summary>长期幸福的创造灵感奖励。</summary> public class Need_CentaurCreativityInspiration : Need { public Need_CentaurCreativityInspiration(Pawn pawn) : base(pawn) { threshPercents = new List<float>(); } private float lastEffectiveDelta = 0f; private float DeltaPerIntervalBase => 0.005f; private float DeltaPerInterval => InHappiness ? DeltaPerIntervalBase : 0f; public override int GUIChangeArrow => IsFrozen ? 0 : Math.Sign(lastEffectiveDelta); public override float MaxLevel => 10f; //protected override bool IsFrozen => false; public override bool ShowOnNeedList => false; //!Disabled && pawn.IsColonist; public bool ShouldShow => !Disabled; public bool InHappiness => pawn.needs.TryGetNeed<Need_Mood>().CurLevelPercentage >= 1f; private bool Disabled => pawn.def != AlienCentaurDef; public override void SetInitialLevel() => CurLevel = 0; public float NextInspirationIn => (CurLevel >= 1f ? MaxLevel - CurLevel : MaxLevel - 1f - CurLevel) / DeltaPerIntervalBase * 2.5f; public override string GetTipString() { string result = $"{LabelCap}: {CurLevel.ToStringPercent()} / {MaxLevel.ToStringPercent()} ({FormattingTickTime(NextInspirationIn, "0.0")})\n{def.description}"; return result; } /* private bool TryStartInspiration() { InspirationHandler ih = pawn.mindState.inspirationHandler; if (ih.Inspired || !pawn.health.capacities.CanBeAwake) { return false; } return ih.TryStartInspiration(InspirationDefOf.Inspired_Creativity, "LetterInspirationBeginThanksToHighMoodPart".Translate()); } */ public bool TryConsume() { if (CurLevel >= 1f) { CurLevel -= 1f; return false; } return false; } public override void NeedInterval() { if (Disabled) { CurLevel = 0f; } else if (!IsFrozen) { float curLevel = CurLevel; float targetLevel = CurLevel + DeltaPerInterval; //if (targetLevel >= 1f && TryStartInspiration()) // targetLevel -= 1f; CurLevel = Mathf.Min(Mathf.Max(targetLevel, 0f), MaxLevel); lastEffectiveDelta = CurLevel - curLevel; } } } }
28.9875
162
0.702889
[ "Apache-2.0" ]
Exploriters/Explorite-core-lab
Source/_Explorite/Need_CentaurCreativityInspiration.cs
2,379
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using SecurityLibrary.RC4; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SecurityPackageTest { [TestClass] public class RC4Test { [TestMethod] public void RC4TestEnc1() { RC4 algorithm = new RC4(); string cipher = algorithm.Encrypt("abcd", "test"); Assert.IsTrue(cipher.Equals("ÏíDu")); } [TestMethod] public void RC4TestDec1() { RC4 algorithm = new RC4(); string cipher = algorithm.Decrypt("ÏíDu", "test"); Assert.IsTrue(cipher.Equals("abcd")); } [TestMethod] public void RC4TestEnc2() { RC4 algorithm = new RC4(); string cipher = algorithm.Encrypt("0x61626364", "0x74657374"); Assert.IsTrue(cipher.Equals("0xcfed4475", StringComparison.InvariantCultureIgnoreCase)); } [TestMethod] public void RC4TestDec2() { RC4 algorithm = new RC4(); string cipher = algorithm.Decrypt("0xcfed4475", "0x74657374"); Assert.IsTrue(cipher.Equals("0x61626364", StringComparison.InvariantCultureIgnoreCase)); } [TestMethod] public void RC4TestNewEnc() { RC4 algorithm = new RC4(); string cipher = algorithm.Encrypt("aaaa", "test"); Assert.IsTrue(cipher.Equals("ÏîFp")); } [TestMethod] public void RC4TestNewDec() { RC4 algorithm = new RC4(); string cipher = algorithm.Decrypt("ÏîFp", "test"); Assert.IsTrue(cipher.Equals("aaaa")); } } }
29.253968
101
0.553988
[ "MIT" ]
abanoubamin/SecurityPackage
SecurityPackage/securitypackagetest/RC4Test.cs
1,853
C#
// ========================================================================== // AssetsValue.cs // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex Group // All rights reserved. // ========================================================================== using System; using System.Collections.Generic; namespace Squidex.Domain.Apps.Core.Schemas { public sealed class AssetsValue { private static readonly List<Guid> EmptyAssetIds = new List<Guid>(); public IReadOnlyList<Guid> AssetIds { get; } public AssetsValue(IReadOnlyList<Guid> assetIds) { AssetIds = assetIds ?? EmptyAssetIds; } } }
28.461538
78
0.45
[ "MIT" ]
andrewhoi/squidex
src/Squidex.Domain.Apps.Core/Schemas/AssetsValue.cs
742
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 Kmd.Studica.Programmes.Client { using Microsoft.Rest; using Microsoft.Rest.Serialization; 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> /// UnscheduledLessonsExternal operations. /// </summary> public partial class UnscheduledLessonsExternal : IServiceOperations<KMDStudicaProgrammes>, IUnscheduledLessonsExternal { /// <summary> /// Initializes a new instance of the UnscheduledLessonsExternal class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public UnscheduledLessonsExternal(KMDStudicaProgrammes client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the KMDStudicaProgrammes /// </summary> public KMDStudicaProgrammes Client { get; private set; } /// <param name='dateFrom'> /// Beginning of range for lesson date. /// </param> /// <param name='dateTo'> /// End of range for lesson date. /// </param> /// <param name='pageNumber'> /// The number of the page to return (1 is the first page). /// </param> /// <param name='pageSize'> /// Number of objects per page. /// </param> /// <param name='inlineCount'> /// A flag indicating if total number of items should be included. /// </param> /// <param name='schoolCode'> /// The school code for which to get data. /// </param> /// <param name='departmentId'> /// Department where the lesson is conducted. /// </param> /// <param name='hasExternalId'> /// Flag indicating if lesson contains external id. /// </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<PagedResponseUnscheduledLessonExternalResponse>> GetWithHttpMessagesAsync(System.DateTime dateFrom, System.DateTime dateTo, int pageNumber, int pageSize, bool inlineCount, string schoolCode, System.Guid? departmentId = default(System.Guid?), bool? hasExternalId = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (pageNumber > 2147483647) { throw new ValidationException(ValidationRules.InclusiveMaximum, "pageNumber", 2147483647); } if (pageNumber < 1) { throw new ValidationException(ValidationRules.InclusiveMinimum, "pageNumber", 1); } if (pageSize > 1000) { throw new ValidationException(ValidationRules.InclusiveMaximum, "pageSize", 1000); } if (pageSize < 1) { throw new ValidationException(ValidationRules.InclusiveMinimum, "pageSize", 1); } if (schoolCode == null) { throw new ValidationException(ValidationRules.CannotBeNull, "schoolCode"); } if (schoolCode != null) { if (schoolCode.Length > 6) { throw new ValidationException(ValidationRules.MaxLength, "schoolCode", 6); } if (schoolCode.Length < 6) { throw new ValidationException(ValidationRules.MinLength, "schoolCode", 6); } } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("departmentId", departmentId); tracingParameters.Add("dateFrom", dateFrom); tracingParameters.Add("dateTo", dateTo); tracingParameters.Add("hasExternalId", hasExternalId); tracingParameters.Add("pageNumber", pageNumber); tracingParameters.Add("pageSize", pageSize); tracingParameters.Add("inlineCount", inlineCount); tracingParameters.Add("schoolCode", schoolCode); 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("/") ? "" : "/")), "UnscheduledLessonsExternal").ToString(); List<string> _queryParameters = new List<string>(); if (departmentId != null) { _queryParameters.Add(string.Format("DepartmentId={0}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(departmentId, Client.SerializationSettings).Trim('"')))); } _queryParameters.Add(string.Format("DateFrom={0}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(dateFrom, new DateJsonConverter()).Trim('"')))); _queryParameters.Add(string.Format("DateTo={0}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(dateTo, new DateJsonConverter()).Trim('"')))); if (hasExternalId != null) { _queryParameters.Add(string.Format("HasExternalId={0}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(hasExternalId, Client.SerializationSettings).Trim('"')))); } _queryParameters.Add(string.Format("PageNumber={0}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(pageNumber, Client.SerializationSettings).Trim('"')))); _queryParameters.Add(string.Format("PageSize={0}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(pageSize, Client.SerializationSettings).Trim('"')))); _queryParameters.Add(string.Format("InlineCount={0}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(inlineCount, Client.SerializationSettings).Trim('"')))); if (schoolCode != null) { _queryParameters.Add(string.Format("SchoolCode={0}", System.Uri.EscapeDataString(schoolCode))); } 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<PagedResponseUnscheduledLessonExternalResponse>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<PagedResponseUnscheduledLessonExternalResponse>(_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; } } }
45.25188
448
0.581873
[ "MIT" ]
kmdstudica/external-api-examples
src/ExternalApiExamples/Clients/Programmes/UnscheduledLessonsExternal.cs
12,037
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("IdentityServer.UnitTests")] [assembly: AssemblyTrademark("")] // 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("d95e6c3e-1906-4323-93d0-490a6a2042cd")]
41.842105
84
0.779874
[ "Apache-2.0" ]
ajilantony/identityserver4
test/IdentityServer.UnitTests/Properties/AssemblyInfo.cs
797
C#
using System.Text; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Jazz.http { public class HttpApi { private static List<HttpRequestContainer> _apiCallQueue = new List<HttpRequestContainer>(); private static HttpRequestApi _internalRequestApi; private HttpApiSettings _apiSettings; public HttpApi(HttpApiSettings settings) { Application.runInBackground = true; _apiSettings = settings; if(_internalRequestApi != null) return; _internalRequestApi = new HttpRequestApi(); } public static int GetPendingMessages() { return _internalRequestApi == null ? 0 : _internalRequestApi.GetPendingMessages(); } public static void SetAuthKey(string authKey) { _internalRequestApi.AuthKey = authKey; } public void MakeApiCall(string apiEndPoint, object args, HttpRequestContainer.ActionSuccessHandler successCallback, HttpRequestContainer.ActionErrorHandler errorCallback, Dictionary<string, string> extraHeaders = null,string method = HttpRequestContainerType.POST, bool allowQueueing = false, bool toJson = true) { HttpRequestContainer request = new HttpRequestContainer() { apiEndPoint = apiEndPoint, Payload = Encoding.UTF8.GetBytes(JsonUtility.ToJson(args)), urlCall = _apiSettings.MakeApiUrl(apiEndPoint), CallbackError = errorCallback, CallbackSuccess = successCallback, Headers = extraHeaders ?? new Dictionary<string, string>(), RequestTimeout = _apiSettings.RequestTimeout, RequestKeepAlive = _apiSettings.RequestKeepAlive, Method = method }; Debug.Log(JsonUtility.ToJson(args)); if (allowQueueing && _apiCallQueue != null) { for (var i = _apiCallQueue.Count - 1; i >= 0; i--) if (_apiCallQueue[i].apiEndPoint == apiEndPoint) _apiCallQueue.RemoveAt(i); _apiCallQueue.Add(request); } else { _internalRequestApi.MakeApiCall(request); } } public static bool IsClientLoggedIn() { return _internalRequestApi != null && !string.IsNullOrEmpty(_internalRequestApi.AuthKey); } public static void ForgetClientCredentials() { if (_internalRequestApi != null) _internalRequestApi.AuthKey = null; } public void Update() { if (_internalRequestApi != null) { if (_apiCallQueue != null) { foreach (var eachRequest in _apiCallQueue) _internalRequestApi.MakeApiCall(eachRequest); _apiCallQueue = null; } _internalRequestApi.Update(); } } public void Dispose() { if(_internalRequestApi != null) { _internalRequestApi.Dispose(); } } } }
31.809524
320
0.564072
[ "MIT" ]
MiniOffical/steam-microtransaction-api
examples/unity/http/HttpApi.cs
3,342
C#
using System; using Aop.Api.Domain; using System.Collections.Generic; using Aop.Api.Response; namespace Aop.Api.Request { /// <summary> /// AOP API: alipay.ebpp.recharge.notify.send /// </summary> public class AlipayEbppRechargeNotifySendRequest : IAopRequest<AlipayEbppRechargeNotifySendResponse> { /// <summary> /// 发送支付宝手机充值超时提醒与补偿 /// </summary> public string BizContent { get; set; } #region IAopRequest Members private bool needEncrypt=false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AopObject bizModel; public void SetNeedEncrypt(bool needEncrypt){ this.needEncrypt=needEncrypt; } public bool GetNeedEncrypt(){ return this.needEncrypt; } public void SetNotifyUrl(string notifyUrl){ this.notifyUrl = notifyUrl; } public string GetNotifyUrl(){ return this.notifyUrl; } public void SetReturnUrl(string returnUrl){ this.returnUrl = returnUrl; } public string GetReturnUrl(){ return this.returnUrl; } public void SetTerminalType(String terminalType){ this.terminalType=terminalType; } public string GetTerminalType(){ return this.terminalType; } public void SetTerminalInfo(String terminalInfo){ this.terminalInfo=terminalInfo; } public string GetTerminalInfo(){ return this.terminalInfo; } public void SetProdCode(String prodCode){ this.prodCode=prodCode; } public string GetProdCode(){ return this.prodCode; } public string GetApiName() { return "alipay.ebpp.recharge.notify.send"; } public void SetApiVersion(string apiVersion){ this.apiVersion=apiVersion; } public string GetApiVersion(){ return this.apiVersion; } public IDictionary<string, string> GetParameters() { AopDictionary parameters = new AopDictionary(); parameters.Add("biz_content", this.BizContent); return parameters; } public AopObject GetBizModel() { return this.bizModel; } public void SetBizModel(AopObject bizModel) { this.bizModel = bizModel; } #endregion } }
23.590909
104
0.60578
[ "Apache-2.0" ]
Varorbc/alipay-sdk-net-all
AlipaySDKNet/Request/AlipayEbppRechargeNotifySendRequest.cs
2,627
C#
using AutoMapper; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace eProdaja.Mapping { public class eProdajaProfile : Profile { public eProdajaProfile() { CreateMap<Database.Korisnici, Model.Korisnici>().ReverseMap(); CreateMap<Database.JediniceMjere, Model.JediniceMjere>(); CreateMap<Database.VrsteProizvodum, Model.VrsteProizvodum>(); CreateMap<Database.Proizvodi, Model.Proizvodi>(); CreateMap<Model.Proizvodi, Database.Proizvodi>(); CreateMap<Model.Requests.ProizvodiInsertRequest, Database.Proizvodi> (); CreateMap<Model.Requests.ProizvodiUpdateRequest, Database.Proizvodi>(); } } }
33.391304
84
0.683594
[ "MIT" ]
irma-maslesa/RazvojSoftveraII
eProdaja/eProdaja/Mapping/eProdajaProfile.cs
770
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; namespace Azure.ResourceManager.Sql.Models { /// <summary> A restorable dropped database. </summary> public partial class RestorableDroppedDatabase : Resource { /// <summary> Initializes a new instance of RestorableDroppedDatabase. </summary> public RestorableDroppedDatabase() { } /// <summary> Initializes a new instance of RestorableDroppedDatabase. </summary> /// <param name="id"> Resource ID. </param> /// <param name="name"> Resource name. </param> /// <param name="type"> Resource type. </param> /// <param name="location"> The geo-location where the resource lives. </param> /// <param name="databaseName"> The name of the database. </param> /// <param name="edition"> The edition of the database. </param> /// <param name="maxSizeBytes"> The max size in bytes of the database. </param> /// <param name="serviceLevelObjective"> The service level objective name of the database. </param> /// <param name="elasticPoolName"> The elastic pool name of the database. </param> /// <param name="creationDate"> The creation date of the database (ISO8601 format). </param> /// <param name="deletionDate"> The deletion date of the database (ISO8601 format). </param> /// <param name="earliestRestoreDate"> The earliest restore date of the database (ISO8601 format). </param> internal RestorableDroppedDatabase(string id, string name, string type, string location, string databaseName, string edition, string maxSizeBytes, string serviceLevelObjective, string elasticPoolName, DateTimeOffset? creationDate, DateTimeOffset? deletionDate, DateTimeOffset? earliestRestoreDate) : base(id, name, type) { Location = location; DatabaseName = databaseName; Edition = edition; MaxSizeBytes = maxSizeBytes; ServiceLevelObjective = serviceLevelObjective; ElasticPoolName = elasticPoolName; CreationDate = creationDate; DeletionDate = deletionDate; EarliestRestoreDate = earliestRestoreDate; } /// <summary> The geo-location where the resource lives. </summary> public string Location { get; } /// <summary> The name of the database. </summary> public string DatabaseName { get; } /// <summary> The edition of the database. </summary> public string Edition { get; } /// <summary> The max size in bytes of the database. </summary> public string MaxSizeBytes { get; } /// <summary> The service level objective name of the database. </summary> public string ServiceLevelObjective { get; } /// <summary> The elastic pool name of the database. </summary> public string ElasticPoolName { get; } /// <summary> The creation date of the database (ISO8601 format). </summary> public DateTimeOffset? CreationDate { get; } /// <summary> The deletion date of the database (ISO8601 format). </summary> public DateTimeOffset? DeletionDate { get; } /// <summary> The earliest restore date of the database (ISO8601 format). </summary> public DateTimeOffset? EarliestRestoreDate { get; } } }
52.151515
328
0.656595
[ "MIT" ]
AWESOME-S-MINDSET/azure-sdk-for-net
sdk/sqlmanagement/Azure.ResourceManager.Sql/src/Generated/Models/RestorableDroppedDatabase.cs
3,442
C#
// // SmtpClientTests.cs // // Author: Jeffrey Stedfast <jestedfa@microsoft.com> // // Copyright (c) 2013-2020 .NET Foundation and Contributors // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using System.IO; using System.Net; using System.Linq; using System.Text; using System.Threading; using System.Net.Sockets; using System.Threading.Tasks; using System.Collections.Generic; using NUnit.Framework; using MimeKit; using MimeKit.IO; using MimeKit.Utils; using MailKit; using MailKit.Security; using MailKit.Net.Smtp; using MailKit.Net.Proxy; using UnitTests.Net.Proxy; namespace UnitTests.Net.Smtp { [TestFixture] public class SmtpClientTests { class MyProgress : ITransferProgress { public long BytesTransferred; public long TotalSize; public void Report (long bytesTransferred, long totalSize) { BytesTransferred = bytesTransferred; TotalSize = totalSize; } public void Report (long bytesTransferred) { BytesTransferred = bytesTransferred; } } MimeMessage CreateSimpleMessage () { var message = new MimeMessage (); message.From.Add (new MailboxAddress ("Sender Name", "sender@example.com")); message.To.Add (new MailboxAddress ("Recipient Name", "recipient@example.com")); message.Subject = "This is a test..."; message.Body = new TextPart ("plain") { Text = "This is the message body." }; return message; } MimeMessage CreateBinaryMessage () { var message = new MimeMessage (); message.From.Add (new MailboxAddress ("Sender Name", "sender@example.com")); message.To.Add (new MailboxAddress ("Recipient Name", "recipient@example.com")); message.Subject = "This is a test..."; message.Body = new TextPart ("plain") { Text = "This is the message body with some unicode unicode: ☮ ☯", ContentTransferEncoding = ContentEncoding.Binary }; return message; } MimeMessage CreateEightBitMessage () { var message = new MimeMessage (); message.From.Add (new MailboxAddress ("Sender Name", "sender@example.com")); message.To.Add (new MailboxAddress ("Recipient Name", "recipient@example.com")); message.Subject = "This is a test..."; message.Body = new TextPart ("plain") { Text = "This is the message body with some unicode unicode: ☮ ☯" }; return message; } [Test] public void TestArgumentExceptions () { using (var client = new SmtpClient ()) { var credentials = new NetworkCredential ("username", "password"); var message = CreateSimpleMessage (); var sender = message.From.Mailboxes.FirstOrDefault (); var recipients = message.To.Mailboxes.ToList (); var options = FormatOptions.Default; var empty = new MailboxAddress[0]; // ReplayConnect Assert.Throws<ArgumentNullException> (() => client.ReplayConnect (null, Stream.Null)); Assert.Throws<ArgumentNullException> (() => client.ReplayConnect ("host", null)); Assert.ThrowsAsync<ArgumentNullException> (async () => await client.ReplayConnectAsync (null, Stream.Null)); Assert.ThrowsAsync<ArgumentNullException> (async () => await client.ReplayConnectAsync ("host", null)); // Connect Assert.Throws<ArgumentNullException> (() => client.Connect ((Uri) null)); Assert.ThrowsAsync<ArgumentNullException> (async () => await client.ConnectAsync ((Uri) null)); Assert.Throws<ArgumentException> (() => client.Connect (new Uri ("path", UriKind.Relative))); Assert.ThrowsAsync<ArgumentException> (async () => await client.ConnectAsync (new Uri ("path", UriKind.Relative))); Assert.Throws<ArgumentNullException> (() => client.Connect (null, 25, false)); Assert.ThrowsAsync<ArgumentNullException> (async () => await client.ConnectAsync (null, 25, false)); Assert.Throws<ArgumentException> (() => client.Connect (string.Empty, 25, false)); Assert.ThrowsAsync<ArgumentException> (async () => await client.ConnectAsync (string.Empty, 25, false)); Assert.Throws<ArgumentOutOfRangeException> (() => client.Connect ("host", -1, false)); Assert.ThrowsAsync<ArgumentOutOfRangeException> (async () => await client.ConnectAsync ("host", -1, false)); Assert.Throws<ArgumentNullException> (() => client.Connect (null, 25, SecureSocketOptions.None)); Assert.ThrowsAsync<ArgumentNullException> (async () => await client.ConnectAsync (null, 25, SecureSocketOptions.None)); Assert.Throws<ArgumentException> (() => client.Connect (string.Empty, 25, SecureSocketOptions.None)); Assert.ThrowsAsync<ArgumentException> (async () => await client.ConnectAsync (string.Empty, 25, SecureSocketOptions.None)); Assert.Throws<ArgumentOutOfRangeException> (() => client.Connect ("host", -1, SecureSocketOptions.None)); Assert.ThrowsAsync<ArgumentOutOfRangeException> (async () => await client.ConnectAsync ("host", -1, SecureSocketOptions.None)); Assert.Throws<ArgumentNullException> (() => client.Connect ((Socket) null, "host", 25, SecureSocketOptions.None)); Assert.ThrowsAsync<ArgumentNullException> (async () => await client.ConnectAsync ((Socket) null, "host", 25, SecureSocketOptions.None)); Assert.Throws<ArgumentNullException> (() => client.Connect ((Stream) null, "host", 25, SecureSocketOptions.None)); Assert.ThrowsAsync<ArgumentNullException> (async () => await client.ConnectAsync ((Stream) null, "host", 25, SecureSocketOptions.None)); using (var socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { Assert.Throws<ArgumentException> (() => client.Connect (socket, "host", 25, SecureSocketOptions.None)); Assert.ThrowsAsync<ArgumentException> (async () => await client.ConnectAsync (socket, "host", 25, SecureSocketOptions.None)); } // Authenticate Assert.Throws<ArgumentNullException> (() => client.Authenticate ((SaslMechanism) null)); Assert.ThrowsAsync<ArgumentNullException> (async () => await client.AuthenticateAsync ((SaslMechanism) null)); Assert.Throws<ArgumentNullException> (() => client.Authenticate ((ICredentials) null)); Assert.ThrowsAsync<ArgumentNullException> (async () => await client.AuthenticateAsync ((ICredentials) null)); Assert.Throws<ArgumentNullException> (() => client.Authenticate (null, "password")); Assert.ThrowsAsync<ArgumentNullException> (async () => await client.AuthenticateAsync (null, "password")); Assert.Throws<ArgumentNullException> (() => client.Authenticate ("username", null)); Assert.ThrowsAsync<ArgumentNullException> (async () => await client.AuthenticateAsync ("username", null)); Assert.Throws<ArgumentNullException> (() => client.Authenticate (null, credentials)); Assert.ThrowsAsync<ArgumentNullException> (async () => await client.AuthenticateAsync (null, credentials)); Assert.Throws<ArgumentNullException> (() => client.Authenticate (Encoding.UTF8, null)); Assert.ThrowsAsync<ArgumentNullException> (async () => await client.AuthenticateAsync (Encoding.UTF8, null)); Assert.Throws<ArgumentNullException> (() => client.Authenticate (null, "username", "password")); Assert.ThrowsAsync<ArgumentNullException> (async () => await client.AuthenticateAsync (null, "username", "password")); Assert.Throws<ArgumentNullException> (() => client.Authenticate (Encoding.UTF8, null, "password")); Assert.ThrowsAsync<ArgumentNullException> (async () => await client.AuthenticateAsync (Encoding.UTF8, null, "password")); Assert.Throws<ArgumentNullException> (() => client.Authenticate (Encoding.UTF8, "username", null)); Assert.ThrowsAsync<ArgumentNullException> (async () => await client.AuthenticateAsync (Encoding.UTF8, "username", null)); // Send Assert.Throws<ArgumentNullException> (() => client.Send (null)); Assert.Throws<ArgumentNullException> (() => client.Send (null, message)); Assert.Throws<ArgumentNullException> (() => client.Send (options, null)); Assert.Throws<ArgumentNullException> (() => client.Send (message, null, recipients)); Assert.Throws<ArgumentNullException> (() => client.Send (message, sender, null)); Assert.Throws<InvalidOperationException> (() => client.Send (message, sender, empty)); Assert.Throws<ArgumentNullException> (() => client.Send (null, message, sender, recipients)); Assert.Throws<ArgumentNullException> (() => client.Send (options, null, sender, recipients)); Assert.Throws<ArgumentNullException> (() => client.Send (options, message, null, recipients)); Assert.Throws<ArgumentNullException> (() => client.Send (options, message, sender, null)); Assert.Throws<InvalidOperationException> (() => client.Send (options, message, sender, empty)); Assert.ThrowsAsync<ArgumentNullException> (async () => await client.SendAsync (null)); Assert.ThrowsAsync<ArgumentNullException> (async () => await client.SendAsync (null, message)); Assert.ThrowsAsync<ArgumentNullException> (async () => await client.SendAsync (options, null)); Assert.ThrowsAsync<ArgumentNullException> (async () => await client.SendAsync (message, null, recipients)); Assert.ThrowsAsync<ArgumentNullException> (async () => await client.SendAsync (message, sender, null)); Assert.ThrowsAsync<InvalidOperationException> (async () => await client.SendAsync (message, sender, empty)); Assert.ThrowsAsync<ArgumentNullException> (async () => await client.SendAsync (null, message, sender, recipients)); Assert.ThrowsAsync<ArgumentNullException> (async () => await client.SendAsync (options, null, sender, recipients)); Assert.ThrowsAsync<ArgumentNullException> (async () => await client.SendAsync (options, message, null, recipients)); Assert.ThrowsAsync<ArgumentNullException> (async () => await client.SendAsync (options, message, sender, null)); Assert.ThrowsAsync<InvalidOperationException> (async () => await client.SendAsync (options, message, sender, empty)); // Expand Assert.Throws<ArgumentNullException> (() => client.Expand (null)); Assert.Throws<ArgumentException> (() => client.Expand (string.Empty)); Assert.Throws<ArgumentException> (() => client.Expand ("line1\r\nline2")); Assert.ThrowsAsync<ArgumentNullException> (async () => await client.ExpandAsync (null)); Assert.ThrowsAsync<ArgumentException> (async () => await client.ExpandAsync (string.Empty)); Assert.ThrowsAsync<ArgumentException> (async () => await client.ExpandAsync ("line1\r\nline2")); // Verify Assert.Throws<ArgumentNullException> (() => client.Verify (null)); Assert.Throws<ArgumentException> (() => client.Verify (string.Empty)); Assert.Throws<ArgumentException> (() => client.Verify ("line1\r\nline2")); Assert.ThrowsAsync<ArgumentNullException> (async () => await client.VerifyAsync (null)); Assert.ThrowsAsync<ArgumentException> (async () => await client.VerifyAsync (string.Empty)); Assert.ThrowsAsync<ArgumentException> (async () => await client.VerifyAsync ("line1\r\nline2")); } } static void AssertDefaultValues (string host, int port, SecureSocketOptions options, Uri expected) { SmtpClient.ComputeDefaultValues (host, ref port, ref options, out Uri uri, out bool starttls); if (expected.PathAndQuery == "/?starttls=when-available") { Assert.AreEqual (SecureSocketOptions.StartTlsWhenAvailable, options, "{0}", expected); Assert.IsTrue (starttls, "{0}", expected); } else if (expected.PathAndQuery == "/?starttls=always") { Assert.AreEqual (SecureSocketOptions.StartTls, options, "{0}", expected); Assert.IsTrue (starttls, "{0}", expected); } else if (expected.Scheme == "smtps") { Assert.AreEqual (SecureSocketOptions.SslOnConnect, options, "{0}", expected); Assert.IsFalse (starttls, "{0}", expected); } else { Assert.AreEqual (SecureSocketOptions.None, options, "{0}", expected); Assert.IsFalse (starttls, "{0}", expected); } Assert.AreEqual (expected.ToString (), uri.ToString ()); Assert.AreEqual (expected.Port, port, "{0}", expected); } [Test] public void TestComputeDefaultValues () { const string host = "smtp.skyfall.net"; AssertDefaultValues (host, 0, SecureSocketOptions.None, new Uri ($"smtp://{host}:25")); AssertDefaultValues (host, 25, SecureSocketOptions.None, new Uri ($"smtp://{host}:25")); AssertDefaultValues (host, 465, SecureSocketOptions.None, new Uri ($"smtp://{host}:465")); AssertDefaultValues (host, 0, SecureSocketOptions.SslOnConnect, new Uri ($"smtps://{host}:465")); AssertDefaultValues (host, 25, SecureSocketOptions.SslOnConnect, new Uri ($"smtps://{host}:25")); AssertDefaultValues (host, 465, SecureSocketOptions.SslOnConnect, new Uri ($"smtps://{host}:465")); AssertDefaultValues (host, 0, SecureSocketOptions.StartTls, new Uri ($"smtp://{host}:25/?starttls=always")); AssertDefaultValues (host, 25, SecureSocketOptions.StartTls, new Uri ($"smtp://{host}:25/?starttls=always")); AssertDefaultValues (host, 465, SecureSocketOptions.StartTls, new Uri ($"smtp://{host}:465/?starttls=always")); AssertDefaultValues (host, 0, SecureSocketOptions.StartTlsWhenAvailable, new Uri ($"smtp://{host}:25/?starttls=when-available")); AssertDefaultValues (host, 25, SecureSocketOptions.StartTlsWhenAvailable, new Uri ($"smtp://{host}:25/?starttls=when-available")); AssertDefaultValues (host, 465, SecureSocketOptions.StartTlsWhenAvailable, new Uri ($"smtp://{host}:465/?starttls=when-available")); AssertDefaultValues (host, 0, SecureSocketOptions.Auto, new Uri ($"smtp://{host}:25/?starttls=when-available")); AssertDefaultValues (host, 25, SecureSocketOptions.Auto, new Uri ($"smtp://{host}:25/?starttls=when-available")); AssertDefaultValues (host, 465, SecureSocketOptions.Auto, new Uri ($"smtps://{host}:465")); } static Socket Connect (string host, int port) { var ipAddresses = Dns.GetHostAddresses (host); Socket socket = null; for (int i = 0; i < ipAddresses.Length; i++) { socket = new Socket (ipAddresses[i].AddressFamily, SocketType.Stream, ProtocolType.Tcp); try { socket.Connect (ipAddresses[i], port); break; } catch { socket.Dispose (); socket = null; } } return socket; } [Test] public void TestSslHandshakeExceptions () { using (var client = new SmtpClient ()) { Assert.Throws<SslHandshakeException> (() => client.Connect ("www.gmail.com", 80, true)); Assert.ThrowsAsync<SslHandshakeException> (async () => await client.ConnectAsync ("www.gmail.com", 80, true)); using (var socket = Connect ("www.gmail.com", 80)) Assert.Throws<SslHandshakeException> (() => client.Connect (socket, "www.gmail.com", 80, SecureSocketOptions.SslOnConnect)); using (var socket = Connect ("www.gmail.com", 80)) Assert.ThrowsAsync<SslHandshakeException> (async () => await client.ConnectAsync (socket, "www.gmail.com", 80, SecureSocketOptions.SslOnConnect)); } } [Test] public void TestSyncRoot () { using (var client = new SmtpClient ()) { Assert.AreEqual (client, client.SyncRoot); } } [Test] public void TestSendWithoutSenderOrRecipients () { var commands = new List<SmtpReplayCommand> (); commands.Add (new SmtpReplayCommand ("", "comcast-greeting.txt")); commands.Add (new SmtpReplayCommand ("EHLO [127.0.0.1]\r\n", "comcast-ehlo.txt")); commands.Add (new SmtpReplayCommand ("QUIT\r\n", "comcast-quit.txt")); using (var client = new SmtpClient ()) { var message = CreateSimpleMessage (); client.LocalDomain = "127.0.0.1"; try { client.ReplayConnect ("localhost", new SmtpReplayStream (commands, false)); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Connect: {0}", ex); } message.From.Clear (); message.Sender = null; Assert.Throws<InvalidOperationException> (() => client.Send (message)); message.From.Add (new MailboxAddress ("Sender Name", "sender@example.com")); message.To.Clear (); Assert.Throws<InvalidOperationException> (() => client.Send (message)); client.Disconnect (true); } } [Test] public async Task TestSendWithoutSenderOrRecipientsAsync () { var commands = new List<SmtpReplayCommand> (); commands.Add (new SmtpReplayCommand ("", "comcast-greeting.txt")); commands.Add (new SmtpReplayCommand ("EHLO [127.0.0.1]\r\n", "comcast-ehlo.txt")); commands.Add (new SmtpReplayCommand ("QUIT\r\n", "comcast-quit.txt")); using (var client = new SmtpClient ()) { var message = CreateSimpleMessage (); client.LocalDomain = "127.0.0.1"; try { await client.ReplayConnectAsync ("localhost", new SmtpReplayStream (commands, true)); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Connect: {0}", ex); } message.From.Clear (); message.Sender = null; Assert.ThrowsAsync<InvalidOperationException> (async () => await client.SendAsync (message)); message.From.Add (new MailboxAddress ("Sender Name", "sender@example.com")); message.To.Clear (); Assert.ThrowsAsync<InvalidOperationException> (async () => await client.SendAsync (message)); await client.DisconnectAsync (true); } } [Test] public void TestInvalidStateExceptions () { var commands = new List<SmtpReplayCommand> (); commands.Add (new SmtpReplayCommand ("", "comcast-greeting.txt")); commands.Add (new SmtpReplayCommand ("EHLO [127.0.0.1]\r\n", "comcast-ehlo.txt")); commands.Add (new SmtpReplayCommand ("MAIL FROM:<sender@example.com>\r\n", "auth-required.txt")); commands.Add (new SmtpReplayCommand ("MAIL FROM:<sender@example.com>\r\n", "comcast-mail-from.txt")); commands.Add (new SmtpReplayCommand ("RCPT TO:<recipient@example.com>\r\n", "auth-required.txt")); commands.Add (new SmtpReplayCommand ("MAIL FROM:<sender@example.com>\r\n", "auth-required.txt")); commands.Add (new SmtpReplayCommand ("MAIL FROM:<sender@example.com>\r\n", "comcast-mail-from.txt")); commands.Add (new SmtpReplayCommand ("RCPT TO:<recipient@example.com>\r\n", "auth-required.txt")); commands.Add (new SmtpReplayCommand ("AUTH PLAIN AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "comcast-auth-plain.txt")); commands.Add (new SmtpReplayCommand ("QUIT\r\n", "comcast-quit.txt")); using (var client = new SmtpClient ()) { var message = CreateSimpleMessage (); var sender = message.From.Mailboxes.FirstOrDefault (); var recipients = message.To.Mailboxes.ToList (); var options = FormatOptions.Default; client.LocalDomain = "127.0.0.1"; Assert.Throws<ServiceNotConnectedException> (() => client.Authenticate ("username", "password")); Assert.Throws<ServiceNotConnectedException> (() => client.Authenticate (new NetworkCredential ("username", "password"))); Assert.Throws<ServiceNotConnectedException> (() => client.Authenticate (new SaslMechanismPlain ("username", "password"))); Assert.Throws<ServiceNotConnectedException> (() => client.NoOp ()); Assert.Throws<ServiceNotConnectedException> (() => client.Send (options, message, sender, recipients)); Assert.Throws<ServiceNotConnectedException> (() => client.Send (message, sender, recipients)); Assert.Throws<ServiceNotConnectedException> (() => client.Send (options, message)); Assert.Throws<ServiceNotConnectedException> (() => client.Send (message)); Assert.Throws<ServiceNotConnectedException> (() => client.Expand ("user@example.com")); Assert.Throws<ServiceNotConnectedException> (() => client.Verify ("user@example.com")); try { client.ReplayConnect ("localhost", new SmtpReplayStream (commands, false)); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Connect: {0}", ex); } Assert.Throws<InvalidOperationException> (() => client.Connect ("host", 465, SecureSocketOptions.SslOnConnect)); Assert.Throws<InvalidOperationException> (() => client.Connect ("host", 465, true)); using (var socket = Connect ("www.gmail.com", 80)) Assert.Throws<InvalidOperationException> (() => client.Connect (socket, "host", 465, SecureSocketOptions.SslOnConnect)); Assert.Throws<ServiceNotAuthenticatedException> (() => client.Send (options, message, sender, recipients)); Assert.Throws<ServiceNotAuthenticatedException> (() => client.Send (message, sender, recipients)); Assert.Throws<ServiceNotAuthenticatedException> (() => client.Send (options, message)); Assert.Throws<ServiceNotAuthenticatedException> (() => client.Send (message)); try { client.Authenticate ("username", "password"); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex); } Assert.Throws<InvalidOperationException> (() => client.Authenticate ("username", "password")); Assert.Throws<InvalidOperationException> (() => client.Authenticate (new NetworkCredential ("username", "password"))); Assert.Throws<InvalidOperationException> (() => client.Authenticate (new SaslMechanismPlain ("username", "password"))); client.Disconnect (true); } } [Test] public async Task TestInvalidStateExceptionsAsync () { var commands = new List<SmtpReplayCommand> (); commands.Add (new SmtpReplayCommand ("", "comcast-greeting.txt")); commands.Add (new SmtpReplayCommand ("EHLO [127.0.0.1]\r\n", "comcast-ehlo.txt")); commands.Add (new SmtpReplayCommand ("MAIL FROM:<sender@example.com>\r\n", "auth-required.txt")); commands.Add (new SmtpReplayCommand ("MAIL FROM:<sender@example.com>\r\n", "comcast-mail-from.txt")); commands.Add (new SmtpReplayCommand ("RCPT TO:<recipient@example.com>\r\n", "auth-required.txt")); commands.Add (new SmtpReplayCommand ("MAIL FROM:<sender@example.com>\r\n", "auth-required.txt")); commands.Add (new SmtpReplayCommand ("MAIL FROM:<sender@example.com>\r\n", "comcast-mail-from.txt")); commands.Add (new SmtpReplayCommand ("RCPT TO:<recipient@example.com>\r\n", "auth-required.txt")); commands.Add (new SmtpReplayCommand ("AUTH PLAIN AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "comcast-auth-plain.txt")); commands.Add (new SmtpReplayCommand ("QUIT\r\n", "comcast-quit.txt")); using (var client = new SmtpClient ()) { var message = CreateSimpleMessage (); var sender = message.From.Mailboxes.FirstOrDefault (); var recipients = message.To.Mailboxes.ToList (); var options = FormatOptions.Default; client.LocalDomain = "127.0.0.1"; Assert.ThrowsAsync<ServiceNotConnectedException> (async () => await client.AuthenticateAsync ("username", "password")); Assert.ThrowsAsync<ServiceNotConnectedException> (async () => await client.AuthenticateAsync (new NetworkCredential ("username", "password"))); Assert.ThrowsAsync<ServiceNotConnectedException> (async () => await client.AuthenticateAsync (new SaslMechanismPlain ("username", "password"))); Assert.ThrowsAsync<ServiceNotConnectedException> (async () => await client.NoOpAsync ()); Assert.ThrowsAsync<ServiceNotConnectedException> (async () => await client.SendAsync (options, message, sender, recipients)); Assert.ThrowsAsync<ServiceNotConnectedException> (async () => await client.SendAsync (message, sender, recipients)); Assert.ThrowsAsync<ServiceNotConnectedException> (async () => await client.SendAsync (options, message)); Assert.ThrowsAsync<ServiceNotConnectedException> (async () => await client.SendAsync (message)); Assert.ThrowsAsync<ServiceNotConnectedException> (async () => await client.ExpandAsync ("user@example.com")); Assert.ThrowsAsync<ServiceNotConnectedException> (async () => await client.VerifyAsync ("user@example.com")); try { await client.ReplayConnectAsync ("localhost", new SmtpReplayStream (commands, true)); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Connect: {0}", ex); } Assert.ThrowsAsync<InvalidOperationException> (async () => await client.ConnectAsync ("host", 465, SecureSocketOptions.SslOnConnect)); Assert.ThrowsAsync<InvalidOperationException> (async () => await client.ConnectAsync ("host", 465, true)); using (var socket = Connect ("www.gmail.com", 80)) Assert.ThrowsAsync<InvalidOperationException> (async () => await client.ConnectAsync (socket, "host", 465, SecureSocketOptions.SslOnConnect)); Assert.ThrowsAsync<ServiceNotAuthenticatedException> (async () => await client.SendAsync (options, message, sender, recipients)); Assert.ThrowsAsync<ServiceNotAuthenticatedException> (async () => await client.SendAsync (message, sender, recipients)); Assert.ThrowsAsync<ServiceNotAuthenticatedException> (async () => await client.SendAsync (options, message)); Assert.ThrowsAsync<ServiceNotAuthenticatedException> (async () => await client.SendAsync (message)); try { await client.AuthenticateAsync ("username", "password"); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex); } Assert.ThrowsAsync<InvalidOperationException> (async () => await client.AuthenticateAsync ("username", "password")); Assert.ThrowsAsync<InvalidOperationException> (async () => await client.AuthenticateAsync (new NetworkCredential ("username", "password"))); Assert.ThrowsAsync<InvalidOperationException> (async () => await client.AuthenticateAsync (new SaslMechanismPlain ("username", "password"))); await client.DisconnectAsync (true); } } [Test] public void TestConnectGMail () { var options = SecureSocketOptions.SslOnConnect; var host = "smtp.gmail.com"; int port = 465; using (var client = new SmtpClient ()) { int connected = 0, disconnected = 0; client.Connected += (sender, e) => { Assert.AreEqual (host, e.Host, "ConnectedEventArgs.Host"); Assert.AreEqual (port, e.Port, "ConnectedEventArgs.Port"); Assert.AreEqual (options, e.Options, "ConnectedEventArgs.Options"); connected++; }; client.Disconnected += (sender, e) => { Assert.AreEqual (host, e.Host, "DisconnectedEventArgs.Host"); Assert.AreEqual (port, e.Port, "DisconnectedEventArgs.Port"); Assert.AreEqual (options, e.Options, "DisconnectedEventArgs.Options"); Assert.IsTrue (e.IsRequested, "DisconnectedEventArgs.IsRequested"); disconnected++; }; client.Connect (host, 0, options); Assert.IsTrue (client.IsConnected, "Expected the client to be connected"); Assert.IsTrue (client.IsSecure, "Expected a secure connection"); Assert.IsFalse (client.IsAuthenticated, "Expected the client to not be authenticated"); Assert.AreEqual (1, connected, "ConnectedEvent"); Assert.Throws<InvalidOperationException> (() => client.Connect (host, 0, options)); client.Disconnect (true); Assert.IsFalse (client.IsConnected, "Expected the client to be disconnected"); Assert.IsFalse (client.IsSecure, "Expected IsSecure to be false after disconnecting"); Assert.AreEqual (1, disconnected, "DisconnectedEvent"); } } [Test] public async Task TestConnectGMailAsync () { var options = SecureSocketOptions.SslOnConnect; var host = "smtp.gmail.com"; int port = 465; using (var client = new SmtpClient ()) { int connected = 0, disconnected = 0; client.Connected += (sender, e) => { Assert.AreEqual (host, e.Host, "ConnectedEventArgs.Host"); Assert.AreEqual (port, e.Port, "ConnectedEventArgs.Port"); Assert.AreEqual (options, e.Options, "ConnectedEventArgs.Options"); connected++; }; client.Disconnected += (sender, e) => { Assert.AreEqual (host, e.Host, "DisconnectedEventArgs.Host"); Assert.AreEqual (port, e.Port, "DisconnectedEventArgs.Port"); Assert.AreEqual (options, e.Options, "DisconnectedEventArgs.Options"); Assert.IsTrue (e.IsRequested, "DisconnectedEventArgs.IsRequested"); disconnected++; }; await client.ConnectAsync ("smtp.gmail.com", 0, SecureSocketOptions.SslOnConnect); Assert.IsTrue (client.IsConnected, "Expected the client to be connected"); Assert.IsTrue (client.IsSecure, "Expected a secure connection"); Assert.IsFalse (client.IsAuthenticated, "Expected the client to not be authenticated"); Assert.AreEqual (1, connected, "ConnectedEvent"); Assert.ThrowsAsync<InvalidOperationException> (async () => await client.ConnectAsync (host, 0, options)); await client.DisconnectAsync (true); Assert.IsFalse (client.IsConnected, "Expected the client to be disconnected"); Assert.IsFalse (client.IsSecure, "Expected IsSecure to be false after disconnecting"); Assert.AreEqual (1, disconnected, "DisconnectedEvent"); } } [Test] public void TestConnectGMailViaProxy () { var options = SecureSocketOptions.SslOnConnect; var host = "smtp.gmail.com"; int port = 465; using (var proxy = new Socks5ProxyListener ()) { proxy.Start (IPAddress.Loopback, 0); using (var client = new SmtpClient ()) { int connected = 0, disconnected = 0; client.Connected += (sender, e) => { Assert.AreEqual (host, e.Host, "ConnectedEventArgs.Host"); Assert.AreEqual (port, e.Port, "ConnectedEventArgs.Port"); Assert.AreEqual (options, e.Options, "ConnectedEventArgs.Options"); connected++; }; client.Disconnected += (sender, e) => { Assert.AreEqual (host, e.Host, "DisconnectedEventArgs.Host"); Assert.AreEqual (port, e.Port, "DisconnectedEventArgs.Port"); Assert.AreEqual (options, e.Options, "DisconnectedEventArgs.Options"); Assert.IsTrue (e.IsRequested, "DisconnectedEventArgs.IsRequested"); disconnected++; }; client.ProxyClient = new Socks5Client (proxy.IPAddress.ToString (), proxy.Port); client.ServerCertificateValidationCallback = (s, c, h, e) => true; client.ClientCertificates = null; client.LocalEndPoint = null; client.Timeout = 20000; try { client.Connect (host, 0, options); } catch (TimeoutException) { Assert.Inconclusive ("Timed out."); return; } catch (Exception ex) { Assert.Fail (ex.Message); } Assert.IsTrue (client.IsConnected, "Expected the client to be connected"); Assert.IsTrue (client.IsSecure, "Expected a secure connection"); Assert.IsFalse (client.IsAuthenticated, "Expected the client to not be authenticated"); Assert.AreEqual (1, connected, "ConnectedEvent"); Assert.Throws<InvalidOperationException> (() => client.Connect (host, 0, options)); client.Disconnect (true); Assert.IsFalse (client.IsConnected, "Expected the client to be disconnected"); Assert.IsFalse (client.IsSecure, "Expected IsSecure to be false after disconnecting"); Assert.AreEqual (1, disconnected, "DisconnectedEvent"); } } } [Test] public async Task TestConnectGMailViaProxyAsync () { var options = SecureSocketOptions.SslOnConnect; var host = "smtp.gmail.com"; int port = 465; using (var proxy = new Socks5ProxyListener ()) { proxy.Start (IPAddress.Loopback, 0); using (var client = new SmtpClient ()) { int connected = 0, disconnected = 0; client.Connected += (sender, e) => { Assert.AreEqual (host, e.Host, "ConnectedEventArgs.Host"); Assert.AreEqual (port, e.Port, "ConnectedEventArgs.Port"); Assert.AreEqual (options, e.Options, "ConnectedEventArgs.Options"); connected++; }; client.Disconnected += (sender, e) => { Assert.AreEqual (host, e.Host, "DisconnectedEventArgs.Host"); Assert.AreEqual (port, e.Port, "DisconnectedEventArgs.Port"); Assert.AreEqual (options, e.Options, "DisconnectedEventArgs.Options"); Assert.IsTrue (e.IsRequested, "DisconnectedEventArgs.IsRequested"); disconnected++; }; client.ProxyClient = new Socks5Client (proxy.IPAddress.ToString (), proxy.Port); client.ServerCertificateValidationCallback = (s, c, h, e) => true; client.ClientCertificates = null; client.LocalEndPoint = null; client.Timeout = 20000; try { await client.ConnectAsync ("smtp.gmail.com", 0, SecureSocketOptions.SslOnConnect); } catch (TimeoutException) { Assert.Inconclusive ("Timed out."); return; } catch (Exception ex) { Assert.Fail (ex.Message); } Assert.IsTrue (client.IsConnected, "Expected the client to be connected"); Assert.IsTrue (client.IsSecure, "Expected a secure connection"); Assert.IsFalse (client.IsAuthenticated, "Expected the client to not be authenticated"); Assert.AreEqual (1, connected, "ConnectedEvent"); Assert.ThrowsAsync<InvalidOperationException> (async () => await client.ConnectAsync ("pop.gmail.com", 0, SecureSocketOptions.SslOnConnect)); await client.DisconnectAsync (true); Assert.IsFalse (client.IsConnected, "Expected the client to be disconnected"); Assert.IsFalse (client.IsSecure, "Expected IsSecure to be false after disconnecting"); Assert.AreEqual (1, disconnected, "DisconnectedEvent"); } } } [Test] public void TestConnectGMailSocket () { var options = SecureSocketOptions.SslOnConnect; var host = "smtp.gmail.com"; int port = 465; using (var client = new SmtpClient ()) { int connected = 0, disconnected = 0; client.Connected += (sender, e) => { Assert.AreEqual (host, e.Host, "ConnectedEventArgs.Host"); Assert.AreEqual (port, e.Port, "ConnectedEventArgs.Port"); Assert.AreEqual (options, e.Options, "ConnectedEventArgs.Options"); connected++; }; client.Disconnected += (sender, e) => { Assert.AreEqual (host, e.Host, "DisconnectedEventArgs.Host"); Assert.AreEqual (port, e.Port, "DisconnectedEventArgs.Port"); Assert.AreEqual (options, e.Options, "DisconnectedEventArgs.Options"); Assert.IsTrue (e.IsRequested, "DisconnectedEventArgs.IsRequested"); disconnected++; }; var socket = Connect (host, port); Assert.Throws<ArgumentNullException> (() => client.Connect (socket, null, port, SecureSocketOptions.Auto)); Assert.Throws<ArgumentException> (() => client.Connect (socket, "", port, SecureSocketOptions.Auto)); Assert.Throws<ArgumentOutOfRangeException> (() => client.Connect (socket, host, -1, SecureSocketOptions.Auto)); client.Connect (socket, host, port, SecureSocketOptions.Auto); Assert.IsTrue (client.IsConnected, "Expected the client to be connected"); Assert.IsTrue (client.IsSecure, "Expected a secure connection"); Assert.IsFalse (client.IsAuthenticated, "Expected the client to not be authenticated"); Assert.AreEqual (1, connected, "ConnectedEvent"); Assert.Throws<InvalidOperationException> (() => client.Connect (socket, host, port, SecureSocketOptions.Auto)); client.Disconnect (true); Assert.IsFalse (client.IsConnected, "Expected the client to be disconnected"); Assert.IsFalse (client.IsSecure, "Expected IsSecure to be false after disconnecting"); Assert.AreEqual (1, disconnected, "DisconnectedEvent"); } } [Test] public async Task TestConnectGMailSocketAsync () { var options = SecureSocketOptions.SslOnConnect; var host = "smtp.gmail.com"; int port = 465; using (var client = new SmtpClient ()) { int connected = 0, disconnected = 0; client.Connected += (sender, e) => { Assert.AreEqual (host, e.Host, "ConnectedEventArgs.Host"); Assert.AreEqual (port, e.Port, "ConnectedEventArgs.Port"); Assert.AreEqual (options, e.Options, "ConnectedEventArgs.Options"); connected++; }; client.Disconnected += (sender, e) => { Assert.AreEqual (host, e.Host, "DisconnectedEventArgs.Host"); Assert.AreEqual (port, e.Port, "DisconnectedEventArgs.Port"); Assert.AreEqual (options, e.Options, "DisconnectedEventArgs.Options"); Assert.IsTrue (e.IsRequested, "DisconnectedEventArgs.IsRequested"); disconnected++; }; var socket = Connect (host, port); Assert.ThrowsAsync<ArgumentNullException> (async () => await client.ConnectAsync (socket, null, port, SecureSocketOptions.Auto)); Assert.ThrowsAsync<ArgumentException> (async () => await client.ConnectAsync (socket, "", port, SecureSocketOptions.Auto)); Assert.ThrowsAsync<ArgumentOutOfRangeException> (async () => await client.ConnectAsync (socket, host, -1, SecureSocketOptions.Auto)); await client.ConnectAsync (socket, host, port, SecureSocketOptions.Auto); Assert.IsTrue (client.IsConnected, "Expected the client to be connected"); Assert.IsTrue (client.IsSecure, "Expected a secure connection"); Assert.IsFalse (client.IsAuthenticated, "Expected the client to not be authenticated"); Assert.AreEqual (1, connected, "ConnectedEvent"); Assert.ThrowsAsync<InvalidOperationException> (async () => await client.ConnectAsync (socket, host, port, SecureSocketOptions.Auto)); await client.DisconnectAsync (true); Assert.IsFalse (client.IsConnected, "Expected the client to be disconnected"); Assert.IsFalse (client.IsSecure, "Expected IsSecure to be false after disconnecting"); Assert.AreEqual (1, disconnected, "DisconnectedEvent"); } } [Test] public void TestConnectYahoo () { var options = SecureSocketOptions.StartTls; var host = "smtp.mail.yahoo.com"; var port = 587; using (var cancel = new CancellationTokenSource (30 * 1000)) { using (var client = new SmtpClient ()) { int connected = 0, disconnected = 0; client.Connected += (sender, e) => { Assert.AreEqual (host, e.Host, "ConnectedEventArgs.Host"); Assert.AreEqual (port, e.Port, "ConnectedEventArgs.Port"); Assert.AreEqual (options, e.Options, "ConnectedEventArgs.Options"); connected++; }; client.Disconnected += (sender, e) => { Assert.AreEqual (host, e.Host, "DisconnectedEventArgs.Host"); Assert.AreEqual (port, e.Port, "DisconnectedEventArgs.Port"); Assert.AreEqual (options, e.Options, "DisconnectedEventArgs.Options"); Assert.IsTrue (e.IsRequested, "DisconnectedEventArgs.IsRequested"); disconnected++; }; var uri = new Uri ($"smtp://{host}:{port}/?starttls=always"); client.Connect (uri, cancel.Token); Assert.IsTrue (client.IsConnected, "Expected the client to be connected"); Assert.IsTrue (client.IsSecure, "Expected a secure connection"); Assert.IsFalse (client.IsAuthenticated, "Expected the client to not be authenticated"); Assert.AreEqual (1, connected, "ConnectedEvent"); client.Disconnect (true); Assert.IsFalse (client.IsConnected, "Expected the client to be disconnected"); Assert.IsFalse (client.IsSecure, "Expected IsSecure to be false after disconnecting"); Assert.AreEqual (1, disconnected, "DisconnectedEvent"); } } } [Test] public async Task TestConnectYahooAsync () { var options = SecureSocketOptions.StartTls; var host = "smtp.mail.yahoo.com"; var port = 587; using (var cancel = new CancellationTokenSource (30 * 1000)) { using (var client = new SmtpClient ()) { int connected = 0, disconnected = 0; client.Connected += (sender, e) => { Assert.AreEqual (host, e.Host, "ConnectedEventArgs.Host"); Assert.AreEqual (port, e.Port, "ConnectedEventArgs.Port"); Assert.AreEqual (options, e.Options, "ConnectedEventArgs.Options"); connected++; }; client.Disconnected += (sender, e) => { Assert.AreEqual (host, e.Host, "DisconnectedEventArgs.Host"); Assert.AreEqual (port, e.Port, "DisconnectedEventArgs.Port"); Assert.AreEqual (options, e.Options, "DisconnectedEventArgs.Options"); Assert.IsTrue (e.IsRequested, "DisconnectedEventArgs.IsRequested"); disconnected++; }; var uri = new Uri ($"smtp://{host}:{port}/?starttls=always"); await client.ConnectAsync (uri, cancel.Token); Assert.IsTrue (client.IsConnected, "Expected the client to be connected"); Assert.IsTrue (client.IsSecure, "Expected a secure connection"); Assert.IsFalse (client.IsAuthenticated, "Expected the client to not be authenticated"); Assert.AreEqual (1, connected, "ConnectedEvent"); await client.DisconnectAsync (true); Assert.IsFalse (client.IsConnected, "Expected the client to be disconnected"); Assert.IsFalse (client.IsSecure, "Expected IsSecure to be false after disconnecting"); Assert.AreEqual (1, disconnected, "DisconnectedEvent"); } } } [Test] public void TestConnectYahooSocket () { var options = SecureSocketOptions.StartTls; var host = "smtp.mail.yahoo.com"; var port = 587; using (var cancel = new CancellationTokenSource (30 * 1000)) { using (var client = new SmtpClient ()) { int connected = 0, disconnected = 0; client.Connected += (sender, e) => { Assert.AreEqual (host, e.Host, "ConnectedEventArgs.Host"); Assert.AreEqual (port, e.Port, "ConnectedEventArgs.Port"); Assert.AreEqual (options, e.Options, "ConnectedEventArgs.Options"); connected++; }; client.Disconnected += (sender, e) => { Assert.AreEqual (host, e.Host, "DisconnectedEventArgs.Host"); Assert.AreEqual (port, e.Port, "DisconnectedEventArgs.Port"); Assert.AreEqual (options, e.Options, "DisconnectedEventArgs.Options"); Assert.IsTrue (e.IsRequested, "DisconnectedEventArgs.IsRequested"); disconnected++; }; var socket = Connect (host, port); client.Connect (socket, host, port, options, cancel.Token); Assert.IsTrue (client.IsConnected, "Expected the client to be connected"); Assert.IsTrue (client.IsSecure, "Expected a secure connection"); Assert.IsFalse (client.IsAuthenticated, "Expected the client to not be authenticated"); Assert.AreEqual (1, connected, "ConnectedEvent"); client.Disconnect (true); Assert.IsFalse (client.IsConnected, "Expected the client to be disconnected"); Assert.IsFalse (client.IsSecure, "Expected IsSecure to be false after disconnecting"); Assert.AreEqual (1, disconnected, "DisconnectedEvent"); } } } [Test] public async Task TestConnectYahooSocketAsync () { var options = SecureSocketOptions.StartTls; var host = "smtp.mail.yahoo.com"; var port = 587; using (var cancel = new CancellationTokenSource (30 * 1000)) { using (var client = new SmtpClient ()) { int connected = 0, disconnected = 0; client.Connected += (sender, e) => { Assert.AreEqual (host, e.Host, "ConnectedEventArgs.Host"); Assert.AreEqual (port, e.Port, "ConnectedEventArgs.Port"); Assert.AreEqual (options, e.Options, "ConnectedEventArgs.Options"); connected++; }; client.Disconnected += (sender, e) => { Assert.AreEqual (host, e.Host, "DisconnectedEventArgs.Host"); Assert.AreEqual (port, e.Port, "DisconnectedEventArgs.Port"); Assert.AreEqual (options, e.Options, "DisconnectedEventArgs.Options"); Assert.IsTrue (e.IsRequested, "DisconnectedEventArgs.IsRequested"); disconnected++; }; var socket = Connect (host, port); await client.ConnectAsync (socket, host, port, options, cancel.Token); Assert.IsTrue (client.IsConnected, "Expected the client to be connected"); Assert.IsTrue (client.IsSecure, "Expected a secure connection"); Assert.IsFalse (client.IsAuthenticated, "Expected the client to not be authenticated"); Assert.AreEqual (1, connected, "ConnectedEvent"); await client.DisconnectAsync (true); Assert.IsFalse (client.IsConnected, "Expected the client to be disconnected"); Assert.IsFalse (client.IsSecure, "Expected IsSecure to be false after disconnecting"); Assert.AreEqual (1, disconnected, "DisconnectedEvent"); } } } [Test] public void TestSaslInitialResponse () { var commands = new List<SmtpReplayCommand> (); commands.Add (new SmtpReplayCommand ("", "comcast-greeting.txt")); commands.Add (new SmtpReplayCommand ("EHLO unit-tests.mimekit.org\r\n", "comcast-ehlo.txt")); commands.Add (new SmtpReplayCommand ("AUTH PLAIN AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "comcast-auth-plain.txt")); commands.Add (new SmtpReplayCommand ("QUIT\r\n", "comcast-quit.txt")); using (var client = new SmtpClient ()) { client.LocalDomain = "unit-tests.mimekit.org"; try { client.ReplayConnect ("localhost", new SmtpReplayStream (commands, false)); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue (client.IsConnected, "Client failed to connect."); Assert.IsFalse (client.IsSecure, "IsSecure should be false."); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Authentication), "Failed to detect AUTH extension"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("LOGIN"), "Failed to detect the LOGIN auth mechanism"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("PLAIN"), "Failed to detect the PLAIN auth mechanism"); try { client.Authenticate (new SaslMechanismPlain ("username", "password")); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex); } try { client.Disconnect (true); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse (client.IsConnected, "Failed to disconnect"); } } [Test] public async Task TestSaslInitialResponseAsync () { var commands = new List<SmtpReplayCommand> (); commands.Add (new SmtpReplayCommand ("", "comcast-greeting.txt")); commands.Add (new SmtpReplayCommand ("EHLO unit-tests.mimekit.org\r\n", "comcast-ehlo.txt")); commands.Add (new SmtpReplayCommand ("AUTH PLAIN AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "comcast-auth-plain.txt")); commands.Add (new SmtpReplayCommand ("QUIT\r\n", "comcast-quit.txt")); using (var client = new SmtpClient ()) { client.LocalDomain = "unit-tests.mimekit.org"; try { await client.ReplayConnectAsync ("localhost", new SmtpReplayStream (commands, true)); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue (client.IsConnected, "Client failed to connect."); Assert.IsFalse (client.IsSecure, "IsSecure should be false."); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Authentication), "Failed to detect AUTH extension"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("LOGIN"), "Failed to detect the LOGIN auth mechanism"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("PLAIN"), "Failed to detect the PLAIN auth mechanism"); try { await client.AuthenticateAsync (new SaslMechanismPlain ("username", "password")); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex); } try { await client.DisconnectAsync (true); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse (client.IsConnected, "Failed to disconnect"); } } [Test] public void TestAuthenticationFailed () { var commands = new List<SmtpReplayCommand> (); commands.Add (new SmtpReplayCommand ("", "comcast-greeting.txt")); commands.Add (new SmtpReplayCommand ("EHLO unit-tests.mimekit.org\r\n", "comcast-ehlo.txt")); commands.Add (new SmtpReplayCommand ("AUTH PLAIN AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "auth-failed.txt")); commands.Add (new SmtpReplayCommand ("AUTH LOGIN\r\n", "comcast-auth-login-username.txt")); commands.Add (new SmtpReplayCommand ("dXNlcm5hbWU=\r\n", "comcast-auth-login-password.txt")); commands.Add (new SmtpReplayCommand ("cGFzc3dvcmQ=\r\n", "auth-failed.txt")); commands.Add (new SmtpReplayCommand ("AUTH PLAIN AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "auth-failed.txt")); commands.Add (new SmtpReplayCommand ("QUIT\r\n", "comcast-quit.txt")); using (var client = new SmtpClient ()) { client.LocalDomain = "unit-tests.mimekit.org"; try { client.ReplayConnect ("localhost", new SmtpReplayStream (commands, false)); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue (client.IsConnected, "Client failed to connect."); Assert.IsFalse (client.IsSecure, "IsSecure should be false."); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Authentication), "Failed to detect AUTH extension"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("LOGIN"), "Failed to detect the LOGIN auth mechanism"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("PLAIN"), "Failed to detect the PLAIN auth mechanism"); try { client.Authenticate ("username", "password"); Assert.Fail ("Authenticate should have failed"); } catch (AuthenticationException ex) { Assert.AreEqual ("535: authentication failed", ex.Message); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex); } try { client.Authenticate (new SaslMechanismPlain ("username", "password")); Assert.Fail ("Authenticate should have failed"); } catch (AuthenticationException ex) { Assert.AreEqual ("535: authentication failed", ex.Message); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex); } try { client.Disconnect (true); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse (client.IsConnected, "Failed to disconnect"); } } [Test] public async Task TestAuthenticationFailedAsync () { var commands = new List<SmtpReplayCommand> (); commands.Add (new SmtpReplayCommand ("", "comcast-greeting.txt")); commands.Add (new SmtpReplayCommand ("EHLO unit-tests.mimekit.org\r\n", "comcast-ehlo.txt")); commands.Add (new SmtpReplayCommand ("AUTH PLAIN AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "auth-failed.txt")); commands.Add (new SmtpReplayCommand ("AUTH LOGIN\r\n", "comcast-auth-login-username.txt")); commands.Add (new SmtpReplayCommand ("dXNlcm5hbWU=\r\n", "comcast-auth-login-password.txt")); commands.Add (new SmtpReplayCommand ("cGFzc3dvcmQ=\r\n", "auth-failed.txt")); commands.Add (new SmtpReplayCommand ("AUTH PLAIN AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "auth-failed.txt")); commands.Add (new SmtpReplayCommand ("QUIT\r\n", "comcast-quit.txt")); using (var client = new SmtpClient ()) { client.LocalDomain = "unit-tests.mimekit.org"; try { await client.ReplayConnectAsync ("localhost", new SmtpReplayStream (commands, true)); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue (client.IsConnected, "Client failed to connect."); Assert.IsFalse (client.IsSecure, "IsSecure should be false."); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Authentication), "Failed to detect AUTH extension"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("LOGIN"), "Failed to detect the LOGIN auth mechanism"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("PLAIN"), "Failed to detect the PLAIN auth mechanism"); try { await client.AuthenticateAsync ("username", "password"); Assert.Fail ("Authenticate should have failed"); } catch (AuthenticationException ex) { Assert.AreEqual ("535: authentication failed", ex.Message); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex); } try { await client.AuthenticateAsync (new SaslMechanismPlain ("username", "password")); Assert.Fail ("Authenticate should have failed"); } catch (AuthenticationException ex) { Assert.AreEqual ("535: authentication failed", ex.Message); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex); } try { await client.DisconnectAsync (true); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse (client.IsConnected, "Failed to disconnect"); } } [Test] public void TestHeloFallback () { var commands = new List<SmtpReplayCommand> (); commands.Add (new SmtpReplayCommand ("", "comcast-greeting.txt")); commands.Add (new SmtpReplayCommand ("EHLO [IPv6:::1]\r\n", "ehlo-failed.txt")); commands.Add (new SmtpReplayCommand ("HELO [IPv6:::1]\r\n", "helo.txt")); commands.Add (new SmtpReplayCommand ("QUIT\r\n", "comcast-quit.txt")); using (var client = new SmtpClient ()) { client.LocalDomain = "::1"; try { client.ReplayConnect ("localhost", new SmtpReplayStream (commands, false)); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue (client.IsConnected, "Client failed to connect."); Assert.IsFalse (client.IsSecure, "IsSecure should be false."); Assert.AreEqual (SmtpCapabilities.None, client.Capabilities, "Capabilities"); try { client.Disconnect (true); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse (client.IsConnected, "Failed to disconnect"); } } [Test] public async Task TestHeloFallbackAsync () { var commands = new List<SmtpReplayCommand> (); commands.Add (new SmtpReplayCommand ("", "comcast-greeting.txt")); commands.Add (new SmtpReplayCommand ("EHLO [IPv6:::1]\r\n", "ehlo-failed.txt")); commands.Add (new SmtpReplayCommand ("HELO [IPv6:::1]\r\n", "helo.txt")); commands.Add (new SmtpReplayCommand ("QUIT\r\n", "comcast-quit.txt")); using (var client = new SmtpClient ()) { client.LocalDomain = "::1"; try { await client.ReplayConnectAsync ("localhost", new SmtpReplayStream (commands, true)); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue (client.IsConnected, "Client failed to connect."); Assert.IsFalse (client.IsSecure, "IsSecure should be false."); Assert.AreEqual (SmtpCapabilities.None, client.Capabilities, "Capabilities"); try { await client.DisconnectAsync (true); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse (client.IsConnected, "Failed to disconnect"); } } [Test] public void TestBasicFunctionality () { var commands = new List<SmtpReplayCommand> (); commands.Add (new SmtpReplayCommand ("", "comcast-greeting.txt")); commands.Add (new SmtpReplayCommand ("EHLO unit-tests.mimekit.org\r\n", "comcast-ehlo.txt")); commands.Add (new SmtpReplayCommand ("AUTH LOGIN\r\n", "comcast-auth-login-username.txt")); commands.Add (new SmtpReplayCommand ("dXNlcm5hbWU=\r\n", "comcast-auth-login-password.txt")); commands.Add (new SmtpReplayCommand ("cGFzc3dvcmQ=\r\n", "comcast-auth-login.txt")); commands.Add (new SmtpReplayCommand ("VRFY Smith\r\n", "rfc0821-vrfy.txt")); commands.Add (new SmtpReplayCommand ("EXPN Example-People\r\n", "rfc0821-expn.txt")); commands.Add (new SmtpReplayCommand ("NOOP\r\n", "comcast-noop.txt")); commands.Add (new SmtpReplayCommand ("MAIL FROM:<sender@example.com>\r\n", "comcast-mail-from.txt")); commands.Add (new SmtpReplayCommand ("RCPT TO:<recipient@example.com>\r\n", "comcast-rcpt-to.txt")); commands.Add (new SmtpReplayCommand ("DATA\r\n", "comcast-data.txt")); commands.Add (new SmtpReplayCommand (".\r\n", "comcast-data-done.txt")); commands.Add (new SmtpReplayCommand ("MAIL FROM:<sender@example.com>\r\n", "comcast-mail-from.txt")); commands.Add (new SmtpReplayCommand ("RCPT TO:<recipient@example.com>\r\n", "comcast-rcpt-to.txt")); commands.Add (new SmtpReplayCommand ("DATA\r\n", "comcast-data.txt")); commands.Add (new SmtpReplayCommand (".\r\n", "comcast-data-done.txt")); commands.Add (new SmtpReplayCommand ("MAIL FROM:<sender@example.com>\r\n", "comcast-mail-from.txt")); commands.Add (new SmtpReplayCommand ("RCPT TO:<recipient@example.com>\r\n", "comcast-rcpt-to.txt")); commands.Add (new SmtpReplayCommand ("DATA\r\n", "comcast-data.txt")); commands.Add (new SmtpReplayCommand (".\r\n", "comcast-data-done.txt")); commands.Add (new SmtpReplayCommand ("MAIL FROM:<sender@example.com>\r\n", "comcast-mail-from.txt")); commands.Add (new SmtpReplayCommand ("RCPT TO:<recipient@example.com>\r\n", "comcast-rcpt-to.txt")); commands.Add (new SmtpReplayCommand ("DATA\r\n", "comcast-data.txt")); commands.Add (new SmtpReplayCommand (".\r\n", "comcast-data-done.txt")); commands.Add (new SmtpReplayCommand ("QUIT\r\n", "comcast-quit.txt")); using (var client = new SmtpClient ()) { client.LocalDomain = "unit-tests.mimekit.org"; try { client.ReplayConnect ("localhost", new SmtpReplayStream (commands, false)); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue (client.IsConnected, "Client failed to connect."); Assert.IsFalse (client.IsSecure, "IsSecure should be false."); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Authentication), "Failed to detect AUTH extension"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("LOGIN"), "Failed to detect the LOGIN auth mechanism"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("PLAIN"), "Failed to detect the PLAIN auth mechanism"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EightBitMime), "Failed to detect 8BITMIME extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EnhancedStatusCodes), "Failed to detect ENHANCEDSTATUSCODES extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Size), "Failed to detect SIZE extension"); Assert.AreEqual (36700160, client.MaxSize, "Failed to parse SIZE correctly"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.StartTLS), "Failed to detect STARTTLS extension"); Assert.Throws<ArgumentException> (() => client.Capabilities |= SmtpCapabilities.UTF8); Assert.AreEqual (120000, client.Timeout, "Timeout"); client.Timeout *= 2; // disable PLAIN authentication client.AuthenticationMechanisms.Remove ("PLAIN"); try { client.Authenticate ("username", "password"); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex); } MailboxAddress vrfy = null; try { vrfy = client.Verify ("Smith"); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Verify: {0}", ex); } Assert.NotNull (vrfy, "VRFY result"); Assert.AreEqual ("Fred Smith", vrfy.Name, "VRFY name"); Assert.AreEqual ("Smith@USC-ISIF.ARPA", vrfy.Address, "VRFY address"); InternetAddressList expn = null; try { expn = client.Expand ("Example-People"); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Expand: {0}", ex); } Assert.NotNull (expn, "EXPN result"); Assert.AreEqual (6, expn.Count, "EXPN count"); Assert.AreEqual ("Jon Postel", expn[0].Name, "expn[0].Name"); Assert.AreEqual ("Postel@USC-ISIF.ARPA", ((MailboxAddress) expn[0]).Address, "expn[0].Address"); Assert.AreEqual ("Fred Fonebone", expn[1].Name, "expn[1].Name"); Assert.AreEqual ("Fonebone@USC-ISIQ.ARPA", ((MailboxAddress) expn[1]).Address, "expn[1].Address"); Assert.AreEqual ("Sam Q. Smith", expn[2].Name, "expn[2].Name"); Assert.AreEqual ("SQSmith@USC-ISIQ.ARPA", ((MailboxAddress) expn[2]).Address, "expn[2].Address"); Assert.AreEqual ("Quincy Smith", expn[3].Name, "expn[3].Name"); Assert.AreEqual ("USC-ISIF.ARPA", ((MailboxAddress) expn[3]).Route[0], "expn[3].Route"); Assert.AreEqual ("Q-Smith@ISI-VAXA.ARPA", ((MailboxAddress) expn[3]).Address, "expn[3].Address"); Assert.AreEqual ("", expn[4].Name, "expn[4].Name"); Assert.AreEqual ("joe@foo-unix.ARPA", ((MailboxAddress) expn[4]).Address, "expn[4].Address"); Assert.AreEqual ("", expn[5].Name, "expn[5].Name"); Assert.AreEqual ("xyz@bar-unix.ARPA", ((MailboxAddress) expn[5]).Address, "expn[5].Address"); try { client.NoOp (); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in NoOp: {0}", ex); } var message = CreateSimpleMessage (); var options = FormatOptions.Default; try { client.Send (message); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Send: {0}", ex); } try { client.Send (message, message.From.Mailboxes.FirstOrDefault (), message.To.Mailboxes); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Send: {0}", ex); } try { client.Send (options, message); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Send: {0}", ex); } try { client.Send (options, message, message.From.Mailboxes.FirstOrDefault (), message.To.Mailboxes); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Send: {0}", ex); } try { client.Disconnect (true); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse (client.IsConnected, "Failed to disconnect"); } } [Test] public async Task TestBasicFunctionalityAsync () { var commands = new List<SmtpReplayCommand> (); commands.Add (new SmtpReplayCommand ("", "comcast-greeting.txt")); commands.Add (new SmtpReplayCommand ("EHLO unit-tests.mimekit.org\r\n", "comcast-ehlo.txt")); commands.Add (new SmtpReplayCommand ("AUTH LOGIN\r\n", "comcast-auth-login-username.txt")); commands.Add (new SmtpReplayCommand ("dXNlcm5hbWU=\r\n", "comcast-auth-login-password.txt")); commands.Add (new SmtpReplayCommand ("cGFzc3dvcmQ=\r\n", "comcast-auth-login.txt")); commands.Add (new SmtpReplayCommand ("VRFY Smith\r\n", "rfc0821-vrfy.txt")); commands.Add (new SmtpReplayCommand ("EXPN Example-People\r\n", "rfc0821-expn.txt")); commands.Add (new SmtpReplayCommand ("NOOP\r\n", "comcast-noop.txt")); commands.Add (new SmtpReplayCommand ("MAIL FROM:<sender@example.com>\r\n", "comcast-mail-from.txt")); commands.Add (new SmtpReplayCommand ("RCPT TO:<recipient@example.com>\r\n", "comcast-rcpt-to.txt")); commands.Add (new SmtpReplayCommand ("DATA\r\n", "comcast-data.txt")); commands.Add (new SmtpReplayCommand (".\r\n", "comcast-data-done.txt")); commands.Add (new SmtpReplayCommand ("MAIL FROM:<sender@example.com>\r\n", "comcast-mail-from.txt")); commands.Add (new SmtpReplayCommand ("RCPT TO:<recipient@example.com>\r\n", "comcast-rcpt-to.txt")); commands.Add (new SmtpReplayCommand ("DATA\r\n", "comcast-data.txt")); commands.Add (new SmtpReplayCommand (".\r\n", "comcast-data-done.txt")); commands.Add (new SmtpReplayCommand ("MAIL FROM:<sender@example.com>\r\n", "comcast-mail-from.txt")); commands.Add (new SmtpReplayCommand ("RCPT TO:<recipient@example.com>\r\n", "comcast-rcpt-to.txt")); commands.Add (new SmtpReplayCommand ("DATA\r\n", "comcast-data.txt")); commands.Add (new SmtpReplayCommand (".\r\n", "comcast-data-done.txt")); commands.Add (new SmtpReplayCommand ("MAIL FROM:<sender@example.com>\r\n", "comcast-mail-from.txt")); commands.Add (new SmtpReplayCommand ("RCPT TO:<recipient@example.com>\r\n", "comcast-rcpt-to.txt")); commands.Add (new SmtpReplayCommand ("DATA\r\n", "comcast-data.txt")); commands.Add (new SmtpReplayCommand (".\r\n", "comcast-data-done.txt")); commands.Add (new SmtpReplayCommand ("QUIT\r\n", "comcast-quit.txt")); using (var client = new SmtpClient ()) { client.LocalDomain = "unit-tests.mimekit.org"; try { await client.ReplayConnectAsync ("localhost", new SmtpReplayStream (commands, true)); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue (client.IsConnected, "Client failed to connect."); Assert.IsFalse (client.IsSecure, "IsSecure should be false."); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Authentication), "Failed to detect AUTH extension"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("LOGIN"), "Failed to detect the LOGIN auth mechanism"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("PLAIN"), "Failed to detect the PLAIN auth mechanism"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EightBitMime), "Failed to detect 8BITMIME extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EnhancedStatusCodes), "Failed to detect ENHANCEDSTATUSCODES extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Size), "Failed to detect SIZE extension"); Assert.AreEqual (36700160, client.MaxSize, "Failed to parse SIZE correctly"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.StartTLS), "Failed to detect STARTTLS extension"); Assert.Throws<ArgumentException> (() => client.Capabilities |= SmtpCapabilities.UTF8); Assert.AreEqual (120000, client.Timeout, "Timeout"); client.Timeout *= 2; // disable PLAIN authentication client.AuthenticationMechanisms.Remove ("PLAIN"); try { await client.AuthenticateAsync ("username", "password"); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex); } MailboxAddress vrfy = null; try { vrfy = await client.VerifyAsync ("Smith"); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Verify: {0}", ex); } Assert.NotNull (vrfy, "VRFY result"); Assert.AreEqual ("Fred Smith", vrfy.Name, "VRFY name"); Assert.AreEqual ("Smith@USC-ISIF.ARPA", vrfy.Address, "VRFY address"); InternetAddressList expn = null; try { expn = await client.ExpandAsync ("Example-People"); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Expand: {0}", ex); } Assert.NotNull (expn, "EXPN result"); Assert.AreEqual (6, expn.Count, "EXPN count"); Assert.AreEqual ("Jon Postel", expn[0].Name, "expn[0].Name"); Assert.AreEqual ("Postel@USC-ISIF.ARPA", ((MailboxAddress) expn[0]).Address, "expn[0].Address"); Assert.AreEqual ("Fred Fonebone", expn[1].Name, "expn[1].Name"); Assert.AreEqual ("Fonebone@USC-ISIQ.ARPA", ((MailboxAddress) expn[1]).Address, "expn[1].Address"); Assert.AreEqual ("Sam Q. Smith", expn[2].Name, "expn[2].Name"); Assert.AreEqual ("SQSmith@USC-ISIQ.ARPA", ((MailboxAddress) expn[2]).Address, "expn[2].Address"); Assert.AreEqual ("Quincy Smith", expn[3].Name, "expn[3].Name"); Assert.AreEqual ("USC-ISIF.ARPA", ((MailboxAddress) expn[3]).Route[0], "expn[3].Route"); Assert.AreEqual ("Q-Smith@ISI-VAXA.ARPA", ((MailboxAddress) expn[3]).Address, "expn[3].Address"); Assert.AreEqual ("", expn[4].Name, "expn[4].Name"); Assert.AreEqual ("joe@foo-unix.ARPA", ((MailboxAddress) expn[4]).Address, "expn[4].Address"); Assert.AreEqual ("", expn[5].Name, "expn[5].Name"); Assert.AreEqual ("xyz@bar-unix.ARPA", ((MailboxAddress) expn[5]).Address, "expn[5].Address"); try { await client.NoOpAsync (); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in NoOp: {0}", ex); } var message = CreateSimpleMessage (); var options = FormatOptions.Default; try { await client.SendAsync (message); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Send: {0}", ex); } try { await client.SendAsync (message, message.From.Mailboxes.FirstOrDefault (), message.To.Mailboxes); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Send: {0}", ex); } try { await client.SendAsync (options, message); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Send: {0}", ex); } try { await client.SendAsync (options, message, message.From.Mailboxes.FirstOrDefault (), message.To.Mailboxes); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Send: {0}", ex); } try { await client.DisconnectAsync (true); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse (client.IsConnected, "Failed to disconnect"); } } [Test] public void TestSaslAuthentication () { var commands = new List<SmtpReplayCommand> (); commands.Add (new SmtpReplayCommand ("", "comcast-greeting.txt")); commands.Add (new SmtpReplayCommand ("EHLO unit-tests.mimekit.org\r\n", "comcast-ehlo.txt")); commands.Add (new SmtpReplayCommand ("AUTH LOGIN\r\n", "comcast-auth-login-username.txt")); commands.Add (new SmtpReplayCommand ("dXNlcm5hbWU=\r\n", "comcast-auth-login-password.txt")); commands.Add (new SmtpReplayCommand ("cGFzc3dvcmQ=\r\n", "comcast-auth-login.txt")); commands.Add (new SmtpReplayCommand ("QUIT\r\n", "comcast-quit.txt")); using (var client = new SmtpClient ()) { client.LocalDomain = "unit-tests.mimekit.org"; try { client.ReplayConnect ("localhost", new SmtpReplayStream (commands, false)); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue (client.IsConnected, "Client failed to connect."); Assert.IsFalse (client.IsSecure, "IsSecure should be false."); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Authentication), "Failed to detect AUTH extension"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("LOGIN"), "Failed to detect the LOGIN auth mechanism"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("PLAIN"), "Failed to detect the PLAIN auth mechanism"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EightBitMime), "Failed to detect 8BITMIME extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EnhancedStatusCodes), "Failed to detect ENHANCEDSTATUSCODES extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Size), "Failed to detect SIZE extension"); Assert.AreEqual (36700160, client.MaxSize, "Failed to parse SIZE correctly"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.StartTLS), "Failed to detect STARTTLS extension"); Assert.Throws<ArgumentException> (() => client.Capabilities |= SmtpCapabilities.UTF8); Assert.AreEqual (120000, client.Timeout, "Timeout"); client.Timeout *= 2; try { var credentials = new NetworkCredential ("username", "password"); var sasl = new SaslMechanismLogin (new Uri ("smtp://localhost"), credentials); client.Authenticate (sasl); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex); } try { client.Disconnect (true); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse (client.IsConnected, "Failed to disconnect"); } } [Test] public async Task TestSaslAuthenticationAsync () { var commands = new List<SmtpReplayCommand> (); commands.Add (new SmtpReplayCommand ("", "comcast-greeting.txt")); commands.Add (new SmtpReplayCommand ("EHLO unit-tests.mimekit.org\r\n", "comcast-ehlo.txt")); commands.Add (new SmtpReplayCommand ("AUTH LOGIN\r\n", "comcast-auth-login-username.txt")); commands.Add (new SmtpReplayCommand ("dXNlcm5hbWU=\r\n", "comcast-auth-login-password.txt")); commands.Add (new SmtpReplayCommand ("cGFzc3dvcmQ=\r\n", "comcast-auth-login.txt")); commands.Add (new SmtpReplayCommand ("QUIT\r\n", "comcast-quit.txt")); using (var client = new SmtpClient ()) { client.LocalDomain = "unit-tests.mimekit.org"; try { await client.ReplayConnectAsync ("localhost", new SmtpReplayStream (commands, true)); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue (client.IsConnected, "Client failed to connect."); Assert.IsFalse (client.IsSecure, "IsSecure should be false."); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Authentication), "Failed to detect AUTH extension"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("LOGIN"), "Failed to detect the LOGIN auth mechanism"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("PLAIN"), "Failed to detect the PLAIN auth mechanism"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EightBitMime), "Failed to detect 8BITMIME extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EnhancedStatusCodes), "Failed to detect ENHANCEDSTATUSCODES extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Size), "Failed to detect SIZE extension"); Assert.AreEqual (36700160, client.MaxSize, "Failed to parse SIZE correctly"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.StartTLS), "Failed to detect STARTTLS extension"); Assert.Throws<ArgumentException> (() => client.Capabilities |= SmtpCapabilities.UTF8); Assert.AreEqual (120000, client.Timeout, "Timeout"); client.Timeout *= 2; try { var credentials = new NetworkCredential ("username", "password"); var sasl = new SaslMechanismLogin (new Uri ("smtp://localhost"), credentials); await client.AuthenticateAsync (sasl); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex); } try { await client.DisconnectAsync (true); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse (client.IsConnected, "Failed to disconnect"); } } [Test] public void TestEightBitMime () { var commands = new List<SmtpReplayCommand> (); commands.Add (new SmtpReplayCommand ("", "comcast-greeting.txt")); commands.Add (new SmtpReplayCommand ("EHLO [127.0.0.1]\r\n", "comcast-ehlo.txt")); commands.Add (new SmtpReplayCommand ("AUTH PLAIN AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "comcast-auth-plain.txt")); commands.Add (new SmtpReplayCommand ("MAIL FROM:<sender@example.com> BODY=8BITMIME\r\n", "comcast-mail-from.txt")); commands.Add (new SmtpReplayCommand ("RCPT TO:<recipient@example.com>\r\n", "comcast-rcpt-to.txt")); commands.Add (new SmtpReplayCommand ("DATA\r\n", "comcast-data.txt")); commands.Add (new SmtpReplayCommand (".\r\n", "comcast-data-done.txt")); commands.Add (new SmtpReplayCommand ("QUIT\r\n", "comcast-quit.txt")); using (var client = new SmtpClient ()) { try { client.ReplayConnect ("localhost", new SmtpReplayStream (commands, false)); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue (client.IsConnected, "Client failed to connect."); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Authentication), "Failed to detect AUTH extension"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("LOGIN"), "Failed to detect the LOGIN auth mechanism"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("PLAIN"), "Failed to detect the PLAIN auth mechanism"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EightBitMime), "Failed to detect 8BITMIME extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EnhancedStatusCodes), "Failed to detect ENHANCEDSTATUSCODES extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Size), "Failed to detect SIZE extension"); Assert.AreEqual (36700160, client.MaxSize, "Failed to parse SIZE correctly"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.StartTLS), "Failed to detect STARTTLS extension"); try { client.Authenticate ("username", "password"); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex); } try { client.Send (CreateEightBitMessage ()); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Send: {0}", ex); } try { client.Disconnect (true); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse (client.IsConnected, "Failed to disconnect"); } } [Test] public async Task TestEightBitMimeAsync () { var commands = new List<SmtpReplayCommand> (); commands.Add (new SmtpReplayCommand ("", "comcast-greeting.txt")); commands.Add (new SmtpReplayCommand ("EHLO [127.0.0.1]\r\n", "comcast-ehlo.txt")); commands.Add (new SmtpReplayCommand ("AUTH PLAIN AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "comcast-auth-plain.txt")); commands.Add (new SmtpReplayCommand ("MAIL FROM:<sender@example.com> BODY=8BITMIME\r\n", "comcast-mail-from.txt")); commands.Add (new SmtpReplayCommand ("RCPT TO:<recipient@example.com>\r\n", "comcast-rcpt-to.txt")); commands.Add (new SmtpReplayCommand ("DATA\r\n", "comcast-data.txt")); commands.Add (new SmtpReplayCommand (".\r\n", "comcast-data-done.txt")); commands.Add (new SmtpReplayCommand ("QUIT\r\n", "comcast-quit.txt")); using (var client = new SmtpClient ()) { try { await client.ReplayConnectAsync ("localhost", new SmtpReplayStream (commands, true)); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue (client.IsConnected, "Client failed to connect."); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Authentication), "Failed to detect AUTH extension"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("LOGIN"), "Failed to detect the LOGIN auth mechanism"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("PLAIN"), "Failed to detect the PLAIN auth mechanism"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EightBitMime), "Failed to detect 8BITMIME extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EnhancedStatusCodes), "Failed to detect ENHANCEDSTATUSCODES extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Size), "Failed to detect SIZE extension"); Assert.AreEqual (36700160, client.MaxSize, "Failed to parse SIZE correctly"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.StartTLS), "Failed to detect STARTTLS extension"); try { await client.AuthenticateAsync ("username", "password"); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex); } try { await client.SendAsync (CreateEightBitMessage ()); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Send: {0}", ex); } try { await client.DisconnectAsync (true); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse (client.IsConnected, "Failed to disconnect"); } } [Test] public void TestInternationalMailboxes () { var mailbox = new MailboxAddress (string.Empty, "úßerñame@example.com"); var addrspec = MailboxAddress.EncodeAddrspec (mailbox.Address); var commands = new List<SmtpReplayCommand> (); commands.Add (new SmtpReplayCommand ("", "comcast-greeting.txt")); commands.Add (new SmtpReplayCommand ("EHLO [127.0.0.1]\r\n", "comcast-ehlo+smtputf8.txt")); commands.Add (new SmtpReplayCommand ("AUTH PLAIN AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "comcast-auth-plain.txt")); commands.Add (new SmtpReplayCommand ($"MAIL FROM:<{mailbox.Address}> SMTPUTF8 BODY=8BITMIME\r\n", "comcast-mail-from.txt")); commands.Add (new SmtpReplayCommand ($"RCPT TO:<{mailbox.Address}>\r\n", "comcast-rcpt-to.txt")); commands.Add (new SmtpReplayCommand ("DATA\r\n", "comcast-data.txt")); commands.Add (new SmtpReplayCommand (".\r\n", "comcast-data-done.txt")); commands.Add (new SmtpReplayCommand ($"MAIL FROM:<{addrspec}> BODY=8BITMIME\r\n", "comcast-mail-from.txt")); commands.Add (new SmtpReplayCommand ($"RCPT TO:<{addrspec}>\r\n", "comcast-rcpt-to.txt")); commands.Add (new SmtpReplayCommand ("DATA\r\n", "comcast-data.txt")); commands.Add (new SmtpReplayCommand (".\r\n", "comcast-data-done.txt")); commands.Add (new SmtpReplayCommand ("QUIT\r\n", "comcast-quit.txt")); using (var client = new SmtpClient ()) { try { client.ReplayConnect ("localhost", new SmtpReplayStream (commands, false)); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue (client.IsConnected, "Client failed to connect."); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Authentication), "Failed to detect AUTH extension"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("LOGIN"), "Failed to detect the LOGIN auth mechanism"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("PLAIN"), "Failed to detect the PLAIN auth mechanism"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.UTF8), "Failed to detect SMTPUTF8 extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EightBitMime), "Failed to detect 8BITMIME extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EnhancedStatusCodes), "Failed to detect ENHANCEDSTATUSCODES extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Size), "Failed to detect SIZE extension"); Assert.AreEqual (36700160, client.MaxSize, "Failed to parse SIZE correctly"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.StartTLS), "Failed to detect STARTTLS extension"); var message = CreateEightBitMessage (); try { client.Authenticate ("username", "password"); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex); } try { client.Send (message, mailbox, new MailboxAddress[] { mailbox }); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Send: {0}", ex); } // Disable SMTPUTF8 client.Capabilities &= ~SmtpCapabilities.UTF8; try { client.Send (message, mailbox, new MailboxAddress[] { mailbox }); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Send: {0}", ex); } try { client.Disconnect (true); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse (client.IsConnected, "Failed to disconnect"); } } [Test] public async Task TestInternationalMailboxesAsync () { var mailbox = new MailboxAddress (string.Empty, "úßerñame@example.com"); var addrspec = MailboxAddress.EncodeAddrspec (mailbox.Address); var commands = new List<SmtpReplayCommand> (); commands.Add (new SmtpReplayCommand ("", "comcast-greeting.txt")); commands.Add (new SmtpReplayCommand ("EHLO [127.0.0.1]\r\n", "comcast-ehlo+smtputf8.txt")); commands.Add (new SmtpReplayCommand ("AUTH PLAIN AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "comcast-auth-plain.txt")); commands.Add (new SmtpReplayCommand ($"MAIL FROM:<{mailbox.Address}> SMTPUTF8 BODY=8BITMIME\r\n", "comcast-mail-from.txt")); commands.Add (new SmtpReplayCommand ($"RCPT TO:<{mailbox.Address}>\r\n", "comcast-rcpt-to.txt")); commands.Add (new SmtpReplayCommand ("DATA\r\n", "comcast-data.txt")); commands.Add (new SmtpReplayCommand (".\r\n", "comcast-data-done.txt")); commands.Add (new SmtpReplayCommand ($"MAIL FROM:<{addrspec}> BODY=8BITMIME\r\n", "comcast-mail-from.txt")); commands.Add (new SmtpReplayCommand ($"RCPT TO:<{addrspec}>\r\n", "comcast-rcpt-to.txt")); commands.Add (new SmtpReplayCommand ("DATA\r\n", "comcast-data.txt")); commands.Add (new SmtpReplayCommand (".\r\n", "comcast-data-done.txt")); commands.Add (new SmtpReplayCommand ("QUIT\r\n", "comcast-quit.txt")); using (var client = new SmtpClient ()) { try { await client.ReplayConnectAsync ("localhost", new SmtpReplayStream (commands, true)); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue (client.IsConnected, "Client failed to connect."); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Authentication), "Failed to detect AUTH extension"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("LOGIN"), "Failed to detect the LOGIN auth mechanism"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("PLAIN"), "Failed to detect the PLAIN auth mechanism"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.UTF8), "Failed to detect SMTPUTF8 extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EightBitMime), "Failed to detect 8BITMIME extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EnhancedStatusCodes), "Failed to detect ENHANCEDSTATUSCODES extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Size), "Failed to detect SIZE extension"); Assert.AreEqual (36700160, client.MaxSize, "Failed to parse SIZE correctly"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.StartTLS), "Failed to detect STARTTLS extension"); var message = CreateEightBitMessage (); try { await client.AuthenticateAsync ("username", "password"); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex); } try { await client.SendAsync (message, mailbox, new MailboxAddress[] { mailbox }); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Send: {0}", ex); } // Disable SMTPUTF8 client.Capabilities &= ~SmtpCapabilities.UTF8; try { await client.SendAsync (message, mailbox, new MailboxAddress[] { mailbox }); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Send: {0}", ex); } try { await client.DisconnectAsync (true); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse (client.IsConnected, "Failed to disconnect"); } } static long Measure (MimeMessage message) { var options = FormatOptions.Default.Clone (); options.NewLineFormat = NewLineFormat.Dos; options.EnsureNewLine = true; using (var measure = new MeasuringStream ()) { message.WriteTo (options, measure); return measure.Length; } } [TestCase (false, TestName = "TestBinaryMimeNoProgress")] [TestCase (true, TestName = "TestBinaryMimeWithProgress")] public void TestBinaryMime (bool showProgress) { var message = CreateBinaryMessage (); var size = Measure (message); string bdat; using (var memory = new MemoryStream ()) { var options = FormatOptions.Default.Clone (); options.NewLineFormat = NewLineFormat.Dos; options.EnsureNewLine = true; var bytes = Encoding.ASCII.GetBytes (string.Format ("BDAT {0} LAST\r\n", size)); memory.Write (bytes, 0, bytes.Length); message.WriteTo (options, memory); bytes = memory.GetBuffer (); bdat = Encoding.UTF8.GetString (bytes, 0, (int) memory.Length); } var commands = new List<SmtpReplayCommand> (); commands.Add (new SmtpReplayCommand ("", "comcast-greeting.txt")); commands.Add (new SmtpReplayCommand ("EHLO [127.0.0.1]\r\n", "comcast-ehlo+binarymime.txt")); commands.Add (new SmtpReplayCommand ("AUTH PLAIN AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "comcast-auth-plain.txt")); commands.Add (new SmtpReplayCommand ("MAIL FROM:<sender@example.com> BODY=BINARYMIME\r\n", "comcast-mail-from.txt")); commands.Add (new SmtpReplayCommand ("RCPT TO:<recipient@example.com>\r\n", "comcast-rcpt-to.txt")); commands.Add (new SmtpReplayCommand (bdat, "comcast-data-done.txt")); commands.Add (new SmtpReplayCommand ("QUIT\r\n", "comcast-quit.txt")); using (var client = new SmtpClient ()) { try { client.ReplayConnect ("localhost", new SmtpReplayStream (commands, false)); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue (client.IsConnected, "Client failed to connect."); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Authentication), "Failed to detect AUTH extension"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("LOGIN"), "Failed to detect the LOGIN auth mechanism"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("PLAIN"), "Failed to detect the PLAIN auth mechanism"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EightBitMime), "Failed to detect 8BITMIME extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EnhancedStatusCodes), "Failed to detect ENHANCEDSTATUSCODES extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Size), "Failed to detect SIZE extension"); Assert.AreEqual (36700160, client.MaxSize, "Failed to parse SIZE correctly"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.StartTLS), "Failed to detect STARTTLS extension"); try { client.Authenticate ("username", "password"); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex); } Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.BinaryMime), "Failed to detect BINARYMIME extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Chunking), "Failed to detect CHUNKING extension"); try { if (showProgress) { var progress = new MyProgress (); client.Send (message, progress: progress); Assert.AreEqual (size, progress.BytesTransferred, "BytesTransferred"); } else { client.Send (message); } } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Send: {0}", ex); } try { client.Disconnect (true); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse (client.IsConnected, "Failed to disconnect"); } } [TestCase (false, TestName = "TestBinaryMimeAsyncNoProgress")] [TestCase (true, TestName = "TestBinaryMimeAsyncWithProgress")] public async Task TestBinaryMimeAsync (bool showProgress) { var message = CreateBinaryMessage (); var size = Measure (message); string bdat; using (var memory = new MemoryStream ()) { var options = FormatOptions.Default.Clone (); options.NewLineFormat = NewLineFormat.Dos; options.EnsureNewLine = true; var bytes = Encoding.ASCII.GetBytes (string.Format ("BDAT {0} LAST\r\n", size)); memory.Write (bytes, 0, bytes.Length); message.WriteTo (options, memory); bytes = memory.GetBuffer (); bdat = Encoding.UTF8.GetString (bytes, 0, (int) memory.Length); } var commands = new List<SmtpReplayCommand> (); commands.Add (new SmtpReplayCommand ("", "comcast-greeting.txt")); commands.Add (new SmtpReplayCommand ("EHLO [127.0.0.1]\r\n", "comcast-ehlo+binarymime.txt")); commands.Add (new SmtpReplayCommand ("AUTH PLAIN AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "comcast-auth-plain.txt")); commands.Add (new SmtpReplayCommand ("MAIL FROM:<sender@example.com> BODY=BINARYMIME\r\n", "comcast-mail-from.txt")); commands.Add (new SmtpReplayCommand ("RCPT TO:<recipient@example.com>\r\n", "comcast-rcpt-to.txt")); commands.Add (new SmtpReplayCommand (bdat, "comcast-data-done.txt")); commands.Add (new SmtpReplayCommand ("QUIT\r\n", "comcast-quit.txt")); using (var client = new SmtpClient ()) { try { await client.ReplayConnectAsync ("localhost", new SmtpReplayStream (commands, true)); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue (client.IsConnected, "Client failed to connect."); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Authentication), "Failed to detect AUTH extension"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("LOGIN"), "Failed to detect the LOGIN auth mechanism"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("PLAIN"), "Failed to detect the PLAIN auth mechanism"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EightBitMime), "Failed to detect 8BITMIME extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EnhancedStatusCodes), "Failed to detect ENHANCEDSTATUSCODES extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Size), "Failed to detect SIZE extension"); Assert.AreEqual (36700160, client.MaxSize, "Failed to parse SIZE correctly"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.StartTLS), "Failed to detect STARTTLS extension"); try { await client.AuthenticateAsync ("username", "password"); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex); } Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.BinaryMime), "Failed to detect BINARYMIME extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Chunking), "Failed to detect CHUNKING extension"); try { if (showProgress) { var progress = new MyProgress (); await client.SendAsync (message, progress: progress); Assert.AreEqual (size, progress.BytesTransferred, "BytesTransferred"); } else { await client.SendAsync (message); } } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Send: {0}", ex); } try { await client.DisconnectAsync (true); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse (client.IsConnected, "Failed to disconnect"); } } [TestCase (false, TestName = "TestPipeliningNoProgress")] [TestCase (true, TestName = "TestPipeliningWithProgress")] public void TestPipelining (bool showProgress) { var commands = new List<SmtpReplayCommand> (); commands.Add (new SmtpReplayCommand ("", "comcast-greeting.txt")); commands.Add (new SmtpReplayCommand ("EHLO [127.0.0.1]\r\n", "comcast-ehlo+pipelining.txt")); commands.Add (new SmtpReplayCommand ("AUTH PLAIN AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "comcast-auth-plain.txt")); commands.Add (new SmtpReplayCommand ("MAIL FROM:<sender@example.com> BODY=8BITMIME\r\nRCPT TO:<recipient@example.com>\r\n", "pipelined-mail-from-rcpt-to.txt")); commands.Add (new SmtpReplayCommand ("DATA\r\n", "comcast-data.txt")); commands.Add (new SmtpReplayCommand (".\r\n", "comcast-data-done.txt")); commands.Add (new SmtpReplayCommand ("QUIT\r\n", "comcast-quit.txt")); using (var client = new SmtpClient ()) { try { client.ReplayConnect ("localhost", new SmtpReplayStream (commands, false)); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue (client.IsConnected, "Client failed to connect."); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Authentication), "Failed to detect AUTH extension"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("LOGIN"), "Failed to detect the LOGIN auth mechanism"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("PLAIN"), "Failed to detect the PLAIN auth mechanism"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Pipelining), "Failed to detect PIPELINING extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EightBitMime), "Failed to detect 8BITMIME extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EnhancedStatusCodes), "Failed to detect ENHANCEDSTATUSCODES extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Size), "Failed to detect SIZE extension"); Assert.AreEqual (36700160, client.MaxSize, "Failed to parse SIZE correctly"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.StartTLS), "Failed to detect STARTTLS extension"); try { client.Authenticate ("username", "password"); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex); } try { var message = CreateEightBitMessage (); if (showProgress) { var progress = new MyProgress (); client.Send (message, progress: progress); Assert.AreEqual (Measure (message), progress.BytesTransferred, "BytesTransferred"); } else { client.Send (message); } } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Send: {0}", ex); } try { client.Disconnect (true); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse (client.IsConnected, "Failed to disconnect"); } } [TestCase (false, TestName = "TestPipeliningAsyncNoProgress")] [TestCase (true, TestName = "TestPipeliningAsyncWithProgress")] public async Task TestPipeliningAsync (bool showProgress) { var commands = new List<SmtpReplayCommand> (); commands.Add (new SmtpReplayCommand ("", "comcast-greeting.txt")); commands.Add (new SmtpReplayCommand ("EHLO [127.0.0.1]\r\n", "comcast-ehlo+pipelining.txt")); commands.Add (new SmtpReplayCommand ("AUTH PLAIN AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "comcast-auth-plain.txt")); commands.Add (new SmtpReplayCommand ("MAIL FROM:<sender@example.com> BODY=8BITMIME\r\nRCPT TO:<recipient@example.com>\r\n", "pipelined-mail-from-rcpt-to.txt")); commands.Add (new SmtpReplayCommand ("DATA\r\n", "comcast-data.txt")); commands.Add (new SmtpReplayCommand (".\r\n", "comcast-data-done.txt")); commands.Add (new SmtpReplayCommand ("QUIT\r\n", "comcast-quit.txt")); using (var client = new SmtpClient ()) { try { await client.ReplayConnectAsync ("localhost", new SmtpReplayStream (commands, true)); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue (client.IsConnected, "Client failed to connect."); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Authentication), "Failed to detect AUTH extension"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("LOGIN"), "Failed to detect the LOGIN auth mechanism"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("PLAIN"), "Failed to detect the PLAIN auth mechanism"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Pipelining), "Failed to detect PIPELINING extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EightBitMime), "Failed to detect 8BITMIME extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EnhancedStatusCodes), "Failed to detect ENHANCEDSTATUSCODES extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Size), "Failed to detect SIZE extension"); Assert.AreEqual (36700160, client.MaxSize, "Failed to parse SIZE correctly"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.StartTLS), "Failed to detect STARTTLS extension"); try { await client.AuthenticateAsync ("username", "password"); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex); } try { var message = CreateEightBitMessage (); if (showProgress) { var progress = new MyProgress (); await client.SendAsync (message, progress: progress); Assert.AreEqual (Measure (message), progress.BytesTransferred, "BytesTransferred"); } else { await client.SendAsync (message); } } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Send: {0}", ex); } try { await client.DisconnectAsync (true); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse (client.IsConnected, "Failed to disconnect"); } } [Test] public void TestMailFromMailboxUnavailable () { var commands = new List<SmtpReplayCommand> (); commands.Add (new SmtpReplayCommand ("", "comcast-greeting.txt")); commands.Add (new SmtpReplayCommand ("EHLO [127.0.0.1]\r\n", "comcast-ehlo.txt")); commands.Add (new SmtpReplayCommand ("AUTH PLAIN AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "comcast-auth-plain.txt")); commands.Add (new SmtpReplayCommand ("MAIL FROM:<sender@example.com>\r\n", "mailbox-unavailable.txt")); commands.Add (new SmtpReplayCommand ("RSET\r\n", "comcast-rset.txt")); commands.Add (new SmtpReplayCommand ("QUIT\r\n", "comcast-quit.txt")); using (var client = new SmtpClient ()) { try { client.ReplayConnect ("localhost", new SmtpReplayStream (commands, false)); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue (client.IsConnected, "Client failed to connect."); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Authentication), "Failed to detect AUTH extension"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("LOGIN"), "Failed to detect the LOGIN auth mechanism"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("PLAIN"), "Failed to detect the PLAIN auth mechanism"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EightBitMime), "Failed to detect 8BITMIME extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EnhancedStatusCodes), "Failed to detect ENHANCEDSTATUSCODES extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Size), "Failed to detect SIZE extension"); Assert.AreEqual (36700160, client.MaxSize, "Failed to parse SIZE correctly"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.StartTLS), "Failed to detect STARTTLS extension"); try { client.Authenticate ("username", "password"); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex); } try { client.Send (CreateSimpleMessage ()); Assert.Fail ("Expected an SmtpException"); } catch (SmtpCommandException sex) { Assert.AreEqual (sex.ErrorCode, SmtpErrorCode.SenderNotAccepted, "Unexpected SmtpErrorCode"); } catch (Exception ex) { Assert.Fail ("Did not expect this exception in Send: {0}", ex); } Assert.IsTrue (client.IsConnected, "Expected the client to still be connected"); try { client.Disconnect (true); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse (client.IsConnected, "Failed to disconnect"); } } [Test] public async Task TestMailFromMailboxUnavailableAsync () { var commands = new List<SmtpReplayCommand> (); commands.Add (new SmtpReplayCommand ("", "comcast-greeting.txt")); commands.Add (new SmtpReplayCommand ("EHLO [127.0.0.1]\r\n", "comcast-ehlo.txt")); commands.Add (new SmtpReplayCommand ("AUTH PLAIN AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "comcast-auth-plain.txt")); commands.Add (new SmtpReplayCommand ("MAIL FROM:<sender@example.com>\r\n", "mailbox-unavailable.txt")); commands.Add (new SmtpReplayCommand ("RSET\r\n", "comcast-rset.txt")); commands.Add (new SmtpReplayCommand ("QUIT\r\n", "comcast-quit.txt")); using (var client = new SmtpClient ()) { try { await client.ReplayConnectAsync ("localhost", new SmtpReplayStream (commands, true)); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue (client.IsConnected, "Client failed to connect."); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Authentication), "Failed to detect AUTH extension"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("LOGIN"), "Failed to detect the LOGIN auth mechanism"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("PLAIN"), "Failed to detect the PLAIN auth mechanism"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EightBitMime), "Failed to detect 8BITMIME extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EnhancedStatusCodes), "Failed to detect ENHANCEDSTATUSCODES extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Size), "Failed to detect SIZE extension"); Assert.AreEqual (36700160, client.MaxSize, "Failed to parse SIZE correctly"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.StartTLS), "Failed to detect STARTTLS extension"); try { await client.AuthenticateAsync ("username", "password"); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex); } try { await client.SendAsync (CreateSimpleMessage ()); Assert.Fail ("Expected an SmtpException"); } catch (SmtpCommandException sex) { Assert.AreEqual (sex.ErrorCode, SmtpErrorCode.SenderNotAccepted, "Unexpected SmtpErrorCode"); } catch (Exception ex) { Assert.Fail ("Did not expect this exception in Send: {0}", ex); } Assert.IsTrue (client.IsConnected, "Expected the client to still be connected"); try { await client.DisconnectAsync (true); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse (client.IsConnected, "Failed to disconnect"); } } [Test] public void TestRcptToMailboxUnavailable () { var commands = new List<SmtpReplayCommand> (); commands.Add (new SmtpReplayCommand ("", "comcast-greeting.txt")); commands.Add (new SmtpReplayCommand ("EHLO [127.0.0.1]\r\n", "comcast-ehlo.txt")); commands.Add (new SmtpReplayCommand ("AUTH PLAIN AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "comcast-auth-plain.txt")); commands.Add (new SmtpReplayCommand ("MAIL FROM:<sender@example.com>\r\n", "comcast-mail-from.txt")); commands.Add (new SmtpReplayCommand ("RCPT TO:<recipient@example.com>\r\n", "mailbox-unavailable.txt")); commands.Add (new SmtpReplayCommand ("RSET\r\n", "comcast-rset.txt")); commands.Add (new SmtpReplayCommand ("QUIT\r\n", "comcast-quit.txt")); using (var client = new SmtpClient ()) { try { client.ReplayConnect ("localhost", new SmtpReplayStream (commands, false)); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue (client.IsConnected, "Client failed to connect."); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Authentication), "Failed to detect AUTH extension"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("LOGIN"), "Failed to detect the LOGIN auth mechanism"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("PLAIN"), "Failed to detect the PLAIN auth mechanism"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EightBitMime), "Failed to detect 8BITMIME extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EnhancedStatusCodes), "Failed to detect ENHANCEDSTATUSCODES extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Size), "Failed to detect SIZE extension"); Assert.AreEqual (36700160, client.MaxSize, "Failed to parse SIZE correctly"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.StartTLS), "Failed to detect STARTTLS extension"); try { client.Authenticate ("username", "password"); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex); } try { client.Send (CreateSimpleMessage ()); Assert.Fail ("Expected an SmtpException"); } catch (SmtpCommandException sex) { Assert.AreEqual (sex.ErrorCode, SmtpErrorCode.RecipientNotAccepted, "Unexpected SmtpErrorCode"); } catch (Exception ex) { Assert.Fail ("Did not expect this exception in Send: {0}", ex); } Assert.IsTrue (client.IsConnected, "Expected the client to still be connected"); try { client.Disconnect (true); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse (client.IsConnected, "Failed to disconnect"); } } [Test] public async Task TestRcptToMailboxUnavailableAsync () { var commands = new List<SmtpReplayCommand> (); commands.Add (new SmtpReplayCommand ("", "comcast-greeting.txt")); commands.Add (new SmtpReplayCommand ("EHLO [127.0.0.1]\r\n", "comcast-ehlo.txt")); commands.Add (new SmtpReplayCommand ("AUTH PLAIN AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "comcast-auth-plain.txt")); commands.Add (new SmtpReplayCommand ("MAIL FROM:<sender@example.com>\r\n", "comcast-mail-from.txt")); commands.Add (new SmtpReplayCommand ("RCPT TO:<recipient@example.com>\r\n", "mailbox-unavailable.txt")); commands.Add (new SmtpReplayCommand ("RSET\r\n", "comcast-rset.txt")); commands.Add (new SmtpReplayCommand ("QUIT\r\n", "comcast-quit.txt")); using (var client = new SmtpClient ()) { try { await client.ReplayConnectAsync ("localhost", new SmtpReplayStream (commands, true)); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue (client.IsConnected, "Client failed to connect."); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Authentication), "Failed to detect AUTH extension"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("LOGIN"), "Failed to detect the LOGIN auth mechanism"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("PLAIN"), "Failed to detect the PLAIN auth mechanism"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EightBitMime), "Failed to detect 8BITMIME extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EnhancedStatusCodes), "Failed to detect ENHANCEDSTATUSCODES extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Size), "Failed to detect SIZE extension"); Assert.AreEqual (36700160, client.MaxSize, "Failed to parse SIZE correctly"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.StartTLS), "Failed to detect STARTTLS extension"); try { await client.AuthenticateAsync ("username", "password"); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex); } try { await client.SendAsync (CreateSimpleMessage ()); Assert.Fail ("Expected an SmtpException"); } catch (SmtpCommandException sex) { Assert.AreEqual (sex.ErrorCode, SmtpErrorCode.RecipientNotAccepted, "Unexpected SmtpErrorCode"); } catch (Exception ex) { Assert.Fail ("Did not expect this exception in Send: {0}", ex); } Assert.IsTrue (client.IsConnected, "Expected the client to still be connected"); try { await client.DisconnectAsync (true); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse (client.IsConnected, "Failed to disconnect"); } } [Test] public void TestUnauthorizedAccessException () { var commands = new List<SmtpReplayCommand> (); commands.Add (new SmtpReplayCommand ("", "comcast-greeting.txt")); commands.Add (new SmtpReplayCommand ("EHLO [127.0.0.1]\r\n", "comcast-ehlo.txt")); commands.Add (new SmtpReplayCommand ("MAIL FROM:<sender@example.com>\r\n", "auth-required.txt")); commands.Add (new SmtpReplayCommand ("QUIT\r\n", "comcast-quit.txt")); using (var client = new SmtpClient ()) { try { client.ReplayConnect ("localhost", new SmtpReplayStream (commands, false)); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue (client.IsConnected, "Client failed to connect."); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Authentication), "Failed to detect AUTH extension"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("LOGIN"), "Failed to detect the LOGIN auth mechanism"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("PLAIN"), "Failed to detect the PLAIN auth mechanism"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EightBitMime), "Failed to detect 8BITMIME extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EnhancedStatusCodes), "Failed to detect ENHANCEDSTATUSCODES extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Size), "Failed to detect SIZE extension"); Assert.AreEqual (36700160, client.MaxSize, "Failed to parse SIZE correctly"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.StartTLS), "Failed to detect STARTTLS extension"); try { client.Send (CreateSimpleMessage ()); Assert.Fail ("Expected an ServiceNotAuthenticatedException"); } catch (ServiceNotAuthenticatedException) { // this is the expected exception } catch (Exception ex) { Assert.Fail ("Did not expect this exception in Send: {0}", ex); } Assert.IsTrue (client.IsConnected, "Expected the client to still be connected"); try { client.Disconnect (true); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse (client.IsConnected, "Failed to disconnect"); } } [Test] public async Task TestUnauthorizedAccessExceptionAsync () { var commands = new List<SmtpReplayCommand> (); commands.Add (new SmtpReplayCommand ("", "comcast-greeting.txt")); commands.Add (new SmtpReplayCommand ("EHLO [127.0.0.1]\r\n", "comcast-ehlo.txt")); commands.Add (new SmtpReplayCommand ("MAIL FROM:<sender@example.com>\r\n", "auth-required.txt")); commands.Add (new SmtpReplayCommand ("QUIT\r\n", "comcast-quit.txt")); using (var client = new SmtpClient ()) { try { await client.ReplayConnectAsync ("localhost", new SmtpReplayStream (commands, true)); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue (client.IsConnected, "Client failed to connect."); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Authentication), "Failed to detect AUTH extension"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("LOGIN"), "Failed to detect the LOGIN auth mechanism"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("PLAIN"), "Failed to detect the PLAIN auth mechanism"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EightBitMime), "Failed to detect 8BITMIME extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EnhancedStatusCodes), "Failed to detect ENHANCEDSTATUSCODES extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Size), "Failed to detect SIZE extension"); Assert.AreEqual (36700160, client.MaxSize, "Failed to parse SIZE correctly"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.StartTLS), "Failed to detect STARTTLS extension"); try { await client.SendAsync (CreateSimpleMessage ()); Assert.Fail ("Expected an ServiceNotAuthenticatedException"); } catch (ServiceNotAuthenticatedException) { // this is the expected exception } catch (Exception ex) { Assert.Fail ("Did not expect this exception in Send: {0}", ex); } Assert.IsTrue (client.IsConnected, "Expected the client to still be connected"); try { await client.DisconnectAsync (true); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse (client.IsConnected, "Failed to disconnect"); } } class DsnSmtpClient : SmtpClient { public DsnSmtpClient () { DeliveryStatusNotificationType = DeliveryStatusNotificationType.HeadersOnly; } protected override string GetEnvelopeId (MimeMessage message) { var id = base.GetEnvelopeId (message); Assert.IsNull (id); return message.MessageId; } protected override DeliveryStatusNotification? GetDeliveryStatusNotifications (MimeMessage message, MailboxAddress mailbox) { var notify = base.GetDeliveryStatusNotifications (message, mailbox); Assert.IsFalse (notify.HasValue); return DeliveryStatusNotification.Delay | DeliveryStatusNotification.Failure | DeliveryStatusNotification.Success; } } [Test] public void TestDeliveryStatusNotification () { var message = CreateEightBitMessage (); message.MessageId = MimeUtils.GenerateMessageId (); var mailFrom = string.Format ("MAIL FROM:<sender@example.com> BODY=8BITMIME ENVID={0} RET=HDRS\r\n", message.MessageId); var commands = new List<SmtpReplayCommand> (); commands.Add (new SmtpReplayCommand ("", "comcast-greeting.txt")); commands.Add (new SmtpReplayCommand ("EHLO [127.0.0.1]\r\n", "comcast-ehlo+dsn.txt")); commands.Add (new SmtpReplayCommand ("AUTH PLAIN AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "comcast-auth-plain.txt")); commands.Add (new SmtpReplayCommand (mailFrom, "comcast-mail-from.txt")); commands.Add (new SmtpReplayCommand ("RCPT TO:<recipient@example.com> NOTIFY=SUCCESS,FAILURE,DELAY\r\n", "comcast-rcpt-to.txt")); commands.Add (new SmtpReplayCommand ("DATA\r\n", "comcast-data.txt")); commands.Add (new SmtpReplayCommand (".\r\n", "comcast-data-done.txt")); commands.Add (new SmtpReplayCommand ("QUIT\r\n", "comcast-quit.txt")); using (var client = new DsnSmtpClient ()) { try { client.ReplayConnect ("localhost", new SmtpReplayStream (commands, false)); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue (client.IsConnected, "Client failed to connect."); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Authentication), "Failed to detect AUTH extension"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("LOGIN"), "Failed to detect the LOGIN auth mechanism"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("PLAIN"), "Failed to detect the PLAIN auth mechanism"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Dsn), "Failed to detect DSN extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Pipelining), "Failed to detect PIPELINING extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EightBitMime), "Failed to detect 8BITMIME extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EnhancedStatusCodes), "Failed to detect ENHANCEDSTATUSCODES extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Size), "Failed to detect SIZE extension"); Assert.AreEqual (36700160, client.MaxSize, "Failed to parse SIZE correctly"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.StartTLS), "Failed to detect STARTTLS extension"); try { client.Authenticate ("username", "password"); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex); } // disable pipelining client.Capabilities &= ~SmtpCapabilities.Pipelining; try { client.Send (message); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Send: {0}", ex); } try { client.Disconnect (true); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse (client.IsConnected, "Failed to disconnect"); } } [Test] public async Task TestDeliveryStatusNotificationAsync () { var message = CreateEightBitMessage (); message.MessageId = MimeUtils.GenerateMessageId (); var mailFrom = string.Format ("MAIL FROM:<sender@example.com> BODY=8BITMIME ENVID={0} RET=HDRS\r\n", message.MessageId); var commands = new List<SmtpReplayCommand> (); commands.Add (new SmtpReplayCommand ("", "comcast-greeting.txt")); commands.Add (new SmtpReplayCommand ("EHLO [127.0.0.1]\r\n", "comcast-ehlo+dsn.txt")); commands.Add (new SmtpReplayCommand ("AUTH PLAIN AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "comcast-auth-plain.txt")); commands.Add (new SmtpReplayCommand (mailFrom, "comcast-mail-from.txt")); commands.Add (new SmtpReplayCommand ("RCPT TO:<recipient@example.com> NOTIFY=SUCCESS,FAILURE,DELAY\r\n", "comcast-rcpt-to.txt")); commands.Add (new SmtpReplayCommand ("DATA\r\n", "comcast-data.txt")); commands.Add (new SmtpReplayCommand (".\r\n", "comcast-data-done.txt")); commands.Add (new SmtpReplayCommand ("QUIT\r\n", "comcast-quit.txt")); using (var client = new DsnSmtpClient ()) { try { await client.ReplayConnectAsync ("localhost", new SmtpReplayStream (commands, true)); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue (client.IsConnected, "Client failed to connect."); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Authentication), "Failed to detect AUTH extension"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("LOGIN"), "Failed to detect the LOGIN auth mechanism"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("PLAIN"), "Failed to detect the PLAIN auth mechanism"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Dsn), "Failed to detect DSN extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Pipelining), "Failed to detect PIPELINING extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EightBitMime), "Failed to detect 8BITMIME extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EnhancedStatusCodes), "Failed to detect ENHANCEDSTATUSCODES extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Size), "Failed to detect SIZE extension"); Assert.AreEqual (36700160, client.MaxSize, "Failed to parse SIZE correctly"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.StartTLS), "Failed to detect STARTTLS extension"); try { await client.AuthenticateAsync ("username", "password"); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex); } // disable pipelining client.Capabilities &= ~SmtpCapabilities.Pipelining; try { await client.SendAsync (message); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Send: {0}", ex); } try { await client.DisconnectAsync (true); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse (client.IsConnected, "Failed to disconnect"); } } class CustomSmtpClient : SmtpClient { public SmtpResponse SendCommand (string command) { return SendCommand (command, CancellationToken.None); } public Task<SmtpResponse> SendCommandAsync (string command) { return SendCommandAsync (command, CancellationToken.None); } } [Test] public void TestCustomCommand () { var commands = new List<SmtpReplayCommand> (); commands.Add (new SmtpReplayCommand ("", "comcast-greeting.txt")); commands.Add (new SmtpReplayCommand ("EHLO unit-tests.mimekit.org\r\n", "comcast-ehlo.txt")); commands.Add (new SmtpReplayCommand ("VRFY Smith\r\n", "rfc0821-vrfy.txt")); commands.Add (new SmtpReplayCommand ("EXPN Example-People\r\n", "rfc0821-expn.txt")); using (var client = new CustomSmtpClient ()) { client.LocalDomain = "unit-tests.mimekit.org"; Assert.Throws<ServiceNotConnectedException> (() => client.SendCommand ("COMMAND")); try { client.ReplayConnect ("localhost", new SmtpReplayStream (commands, false)); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue (client.IsConnected, "Client failed to connect."); Assert.IsFalse (client.IsSecure, "IsSecure should be false."); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Authentication), "Failed to detect AUTH extension"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("LOGIN"), "Failed to detect the LOGIN auth mechanism"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("PLAIN"), "Failed to detect the PLAIN auth mechanism"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EightBitMime), "Failed to detect 8BITMIME extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EnhancedStatusCodes), "Failed to detect ENHANCEDSTATUSCODES extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Size), "Failed to detect SIZE extension"); Assert.AreEqual (36700160, client.MaxSize, "Failed to parse SIZE correctly"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.StartTLS), "Failed to detect STARTTLS extension"); Assert.Throws<ArgumentException> (() => client.Capabilities |= SmtpCapabilities.UTF8); Assert.AreEqual (120000, client.Timeout, "Timeout"); client.Timeout *= 2; Assert.Throws<ArgumentNullException> (() => client.SendCommand (null)); SmtpResponse response = null; try { response = client.SendCommand ("VRFY Smith"); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Verify: {0}", ex); } Assert.NotNull (response, "VRFY result"); Assert.AreEqual (SmtpStatusCode.Ok, response.StatusCode, "VRFY response code"); Assert.AreEqual ("Fred Smith <Smith@USC-ISIF.ARPA>", response.Response, "VRFY response"); try { response = client.SendCommand ("EXPN Example-People"); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Expand: {0}", ex); } Assert.NotNull (response, "EXPN result"); Assert.AreEqual (SmtpStatusCode.Ok, response.StatusCode, "EXPN response code"); Assert.AreEqual ("Jon Postel <Postel@USC-ISIF.ARPA>\nFred Fonebone <Fonebone@USC-ISIQ.ARPA>\nSam Q. Smith <SQSmith@USC-ISIQ.ARPA>\nQuincy Smith <@USC-ISIF.ARPA:Q-Smith@ISI-VAXA.ARPA>\n<joe@foo-unix.ARPA>\n<xyz@bar-unix.ARPA>", response.Response, "EXPN response"); } } [Test] public async Task TestCustomCommandAsync () { var commands = new List<SmtpReplayCommand> (); commands.Add (new SmtpReplayCommand ("", "comcast-greeting.txt")); commands.Add (new SmtpReplayCommand ("EHLO unit-tests.mimekit.org\r\n", "comcast-ehlo.txt")); commands.Add (new SmtpReplayCommand ("VRFY Smith\r\n", "rfc0821-vrfy.txt")); commands.Add (new SmtpReplayCommand ("EXPN Example-People\r\n", "rfc0821-expn.txt")); using (var client = new CustomSmtpClient ()) { client.LocalDomain = "unit-tests.mimekit.org"; Assert.ThrowsAsync<ServiceNotConnectedException> (async () => await client.SendCommandAsync ("COMMAND")); try { await client.ReplayConnectAsync ("localhost", new SmtpReplayStream (commands, true)); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue (client.IsConnected, "Client failed to connect."); Assert.IsFalse (client.IsSecure, "IsSecure should be false."); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Authentication), "Failed to detect AUTH extension"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("LOGIN"), "Failed to detect the LOGIN auth mechanism"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("PLAIN"), "Failed to detect the PLAIN auth mechanism"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EightBitMime), "Failed to detect 8BITMIME extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EnhancedStatusCodes), "Failed to detect ENHANCEDSTATUSCODES extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Size), "Failed to detect SIZE extension"); Assert.AreEqual (36700160, client.MaxSize, "Failed to parse SIZE correctly"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.StartTLS), "Failed to detect STARTTLS extension"); Assert.Throws<ArgumentException> (() => client.Capabilities |= SmtpCapabilities.UTF8); Assert.AreEqual (120000, client.Timeout, "Timeout"); client.Timeout *= 2; Assert.ThrowsAsync<ArgumentNullException> (async () => await client.SendCommandAsync (null)); SmtpResponse response = null; try { response = await client.SendCommandAsync ("VRFY Smith"); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Verify: {0}", ex); } Assert.NotNull (response, "VRFY result"); Assert.AreEqual (SmtpStatusCode.Ok, response.StatusCode, "VRFY response code"); Assert.AreEqual ("Fred Smith <Smith@USC-ISIF.ARPA>", response.Response, "VRFY response"); try { response = await client.SendCommandAsync ("EXPN Example-People"); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Expand: {0}", ex); } Assert.NotNull (response, "EXPN result"); Assert.AreEqual (SmtpStatusCode.Ok, response.StatusCode, "EXPN response code"); Assert.AreEqual ("Jon Postel <Postel@USC-ISIF.ARPA>\nFred Fonebone <Fonebone@USC-ISIQ.ARPA>\nSam Q. Smith <SQSmith@USC-ISIQ.ARPA>\nQuincy Smith <@USC-ISIF.ARPA:Q-Smith@ISI-VAXA.ARPA>\n<joe@foo-unix.ARPA>\n<xyz@bar-unix.ARPA>", response.Response, "EXPN response"); } } } }
46.027837
267
0.701539
[ "MIT" ]
ByteDecoder/MailK
UnitTests/Net/Smtp/SmtpClientTests.cs
130,643
C#
#pragma checksum "C:\Users\miyuki\source\repos\color_test\color_test\Quiz_Grade2.xaml" "{8829d00f-11b8-4213-878b-770e8597ac16}" "8CBA967F0D3FFB8333FE758365433E610060522A55C7AA26F660F318BEC9C9CB" //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace color_test { partial class Quiz_Grade2 : global::Windows.UI.Xaml.Controls.Page { [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 10.0.19041.685")] private global::Windows.UI.Xaml.Controls.RelativePanel layoutRoot; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 10.0.19041.685")] private bool _contentLoaded; /// <summary> /// InitializeComponent() /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 10.0.19041.685")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public void InitializeComponent() { if (_contentLoaded) return; _contentLoaded = true; global::System.Uri resourceLocator = new global::System.Uri("ms-appx:///Quiz_Grade2.xaml"); global::Windows.UI.Xaml.Application.LoadComponent(this, resourceLocator, global::Windows.UI.Xaml.Controls.Primitives.ComponentResourceLocation.Application); } partial void UnloadObject(global::Windows.UI.Xaml.DependencyObject unloadableObject); } }
41.409091
195
0.636663
[ "MIT" ]
miyuki-98312/ColorQuiz
color_test/obj/ARM/Debug/Quiz_Grade2.g.i.cs
1,824
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Microsoft.MixedReality.Toolkit.Input; using Microsoft.MixedReality.Toolkit.Utilities; using Microsoft.MixedReality.Toolkit.XRSDK.Input; using System; using UnityEngine; using UnityEngine.XR; #if OCULUS_ENABLED using Unity.XR.Oculus; #endif // OCULUS_ENABLED #if OCULUSINTEGRATION_PRESENT using System.Collections.Generic; using UnityEngine; #endif // OCULUSINTEGRATION_PRESENT namespace Microsoft.MixedReality.Toolkit.XRSDK.Oculus.Input { /// <summary> /// Manages XR SDK devices on the Oculus platform. /// </summary> [MixedRealityDataProvider( typeof(IMixedRealityInputSystem), SupportedPlatforms.WindowsStandalone | SupportedPlatforms.Android, "XR SDK Oculus Device Manager", "Oculus/XRSDK/Profiles/DefaultOculusXRSDKDeviceManagerProfile.asset", "MixedRealityToolkit.Providers", true, SupportedUnityXRPipelines.XRSDK)] public class OculusXRSDKDeviceManager : XRSDKDeviceManager { /// <summary> /// Constructor. /// </summary> /// <param name="inputSystem">The <see cref="Microsoft.MixedReality.Toolkit.Input.IMixedRealityInputSystem"/> instance that receives data from this provider.</param> /// <param name="name">Friendly name of the service.</param> /// <param name="priority">Service priority. Used to determine order of instantiation.</param> /// <param name="profile">The service's configuration profile.</param> public OculusXRSDKDeviceManager( IMixedRealityInputSystem inputSystem, string name = null, uint priority = DefaultPriority, BaseMixedRealityProfile profile = null) : base(inputSystem, name, priority, profile) { } #if !OCULUSINTEGRATION_PRESENT && UNITY_EDITOR && UNITY_ANDROID public override void Initialize() { base.Initialize(); UnityEngine.Debug.Log(@"Detected a potential deployment issue for the Oculus Quest. In order to use hand tracking with the Oculus Quest, download the Oculus Integration Package from the Unity Asset Store and run the Integration tool before deploying. The tool can be found under <i>Mixed Reality > Toolkit > Utilities > Oculus > Integrate Oculus Integration Unity Modules</i>"); } #endif #if OCULUSINTEGRATION_PRESENT private readonly Dictionary<Handedness, OculusHand> trackedHands = new Dictionary<Handedness, OculusHand>(); private OVRCameraRig cameraRig; private OVRHand rightHand; private OVRSkeleton rightSkeleton; private OVRHand leftHand; private OVRSkeleton leftSkeleton; /// <summary> /// The profile that contains settings for the Oculus XRSDK Device Manager input data provider. This profile is nested under /// Input > Input Data Providers > Oculus XRSDK Device Manager in the MixedRealityToolkit object in the hierarchy. /// </summary> private OculusXRSDKDeviceManagerProfile SettingsProfile => ConfigurationProfile as OculusXRSDKDeviceManagerProfile; #endif #region IMixedRealityCapabilityCheck Implementation /// <inheritdoc /> public override bool CheckCapability(MixedRealityCapability capability) { #if OCULUSINTEGRATION_PRESENT if (capability == MixedRealityCapability.ArticulatedHand) { return true; } #endif return capability == MixedRealityCapability.MotionController; } #endregion IMixedRealityCapabilityCheck Implementation #region Controller Utilities #if OCULUSINTEGRATION_PRESENT /// <inheritdoc /> protected override GenericXRSDKController GetOrAddController(InputDevice inputDevice) { GenericXRSDKController controller = base.GetOrAddController(inputDevice); if (controller is OculusXRSDKTouchController oculusTouchController) { oculusTouchController.UseMRTKControllerVisualization = cameraRig.IsNull(); } return controller; } #endif /// <inheritdoc /> protected override Type GetControllerType(SupportedControllerType supportedControllerType) { switch (supportedControllerType) { case SupportedControllerType.ArticulatedHand: return typeof(OculusHand); case SupportedControllerType.OculusTouch: return typeof(OculusXRSDKTouchController); default: return base.GetControllerType(supportedControllerType); } } /// <inheritdoc /> protected override InputSourceType GetInputSourceType(SupportedControllerType supportedControllerType) { switch (supportedControllerType) { case SupportedControllerType.OculusTouch: return InputSourceType.Controller; case SupportedControllerType.ArticulatedHand: return InputSourceType.Hand; default: return base.GetInputSourceType(supportedControllerType); } } /// <inheritdoc /> protected override SupportedControllerType GetCurrentControllerType(InputDevice inputDevice) { if (inputDevice.characteristics.HasFlag(InputDeviceCharacteristics.HandTracking)) { if (inputDevice.characteristics.HasFlag(InputDeviceCharacteristics.Left) || inputDevice.characteristics.HasFlag(InputDeviceCharacteristics.Right)) { // If it's a hand with a reported handedness, assume articulated hand return SupportedControllerType.ArticulatedHand; } } if (inputDevice.characteristics.HasFlag(InputDeviceCharacteristics.Controller)) { return SupportedControllerType.OculusTouch; } return base.GetCurrentControllerType(inputDevice); } #endregion Controller Utilities private bool? IsActiveLoader => #if OCULUS_ENABLED LoaderHelpers.IsLoaderActive<OculusLoader>(); #else false; #endif // OCULUS_ENABLED /// <inheritdoc/> public override void Enable() { if (!IsActiveLoader.HasValue) { IsEnabled = false; EnableIfLoaderBecomesActive(); return; } else if (!IsActiveLoader.Value) { IsEnabled = false; return; } #if OCULUSINTEGRATION_PRESENT SetupInput(); ConfigurePerformancePreferences(); #endif // OCULUSINTEGRATION_PRESENT base.Enable(); } private async void EnableIfLoaderBecomesActive() { await new WaitUntil(() => IsActiveLoader.HasValue); if (IsActiveLoader.Value) { Enable(); } } #if OCULUSINTEGRATION_PRESENT /// <inheritdoc/> public override void Update() { if (!IsEnabled) { return; } base.Update(); if (OVRPlugin.GetHandTrackingEnabled()) { UpdateHands(); } else { RemoveAllHandDevices(); } } private void SetupInput() { cameraRig = GameObject.FindObjectOfType<OVRCameraRig>(); if (cameraRig == null) { var mainCamera = CameraCache.Main; // Instantiate camera rig as a child of the MixedRealityPlayspace var cameraRigObject = GameObject.Instantiate(SettingsProfile.OVRCameraRigPrefab); cameraRig = cameraRigObject.GetComponent<OVRCameraRig>(); // Ensure all related game objects are configured cameraRig.EnsureGameObjectIntegrity(); if (mainCamera != null) { // We already had a main camera MRTK probably started using, let's replace the CenterEyeAnchor MainCamera with it GameObject prefabMainCamera = cameraRig.trackingSpace.Find("CenterEyeAnchor").gameObject; prefabMainCamera.SetActive(false); mainCamera.transform.SetParent(cameraRig.trackingSpace.transform); mainCamera.name = prefabMainCamera.name; GameObject.Destroy(prefabMainCamera); } cameraRig.transform.SetParent(MixedRealityPlayspace.Transform); } else { // Ensure all related game objects are configured cameraRig.EnsureGameObjectIntegrity(); } bool useAvatarHands = SettingsProfile.RenderAvatarHandsInsteadOfController; // If using Avatar hands, deactivate ovr controller rendering foreach (var controllerHelper in cameraRig.gameObject.GetComponentsInChildren<OVRControllerHelper>()) { controllerHelper.gameObject.SetActive(!useAvatarHands); } if (useAvatarHands) { // Initialize the local avatar controller GameObject.Instantiate(SettingsProfile.LocalAvatarPrefab, cameraRig.trackingSpace); } var ovrHands = cameraRig.GetComponentsInChildren<OVRHand>(); foreach (var ovrHand in ovrHands) { // Manage Hand skeleton data var skeletonDataProvider = ovrHand as OVRSkeleton.IOVRSkeletonDataProvider; var skeletonType = skeletonDataProvider.GetSkeletonType(); var ovrSkeleton = ovrHand.GetComponent<OVRSkeleton>(); if (ovrSkeleton == null) { continue; } switch (skeletonType) { case OVRSkeleton.SkeletonType.HandLeft: leftHand = ovrHand; leftSkeleton = ovrSkeleton; break; case OVRSkeleton.SkeletonType.HandRight: rightHand = ovrHand; rightSkeleton = ovrSkeleton; break; } } } private void ConfigurePerformancePreferences() { SettingsProfile.ApplyConfiguredPerformanceSettings(); } #region Hand Utilities protected void UpdateHands() { UpdateHand(rightHand, rightSkeleton, Handedness.Right); UpdateHand(leftHand, leftSkeleton, Handedness.Left); } protected void UpdateHand(OVRHand ovrHand, OVRSkeleton ovrSkeleton, Handedness handedness) { if (ovrHand.IsTracked) { var hand = GetOrAddHand(handedness, ovrHand); hand.UpdateController(ovrHand, ovrSkeleton, cameraRig.trackingSpace); } else { RemoveHandDevice(handedness); } } private OculusHand GetOrAddHand(Handedness handedness, OVRHand ovrHand) { if (trackedHands.ContainsKey(handedness)) { return trackedHands[handedness]; } // Add new hand var pointers = RequestPointers(SupportedControllerType.ArticulatedHand, handedness); var inputSourceType = InputSourceType.Hand; var inputSource = Service?.RequestNewGenericInputSource($"Oculus Quest {handedness} Hand", pointers, inputSourceType); OculusHand handDevice = new OculusHand(TrackingState.Tracked, handedness, inputSource); handDevice.InitializeHand(ovrHand, SettingsProfile); for (int i = 0; i < handDevice.InputSource?.Pointers?.Length; i++) { handDevice.InputSource.Pointers[i].Controller = handDevice; } Service?.RaiseSourceDetected(handDevice.InputSource, handDevice); trackedHands.Add(handedness, handDevice); return handDevice; } private void RemoveHandDevice(Handedness handedness) { if (trackedHands.TryGetValue(handedness, out OculusHand hand)) { RemoveHandDevice(hand); } } private void RemoveAllHandDevices() { if (trackedHands.Count == 0) return; // Create a new list to avoid causing an error removing items from a list currently being iterated on. foreach (var hand in new List<OculusHand>(trackedHands.Values)) { RemoveHandDevice(hand); } trackedHands.Clear(); } private void RemoveHandDevice(OculusHand handDevice) { if (handDevice == null) return; CoreServices.InputSystem?.RaiseSourceLost(handDevice.InputSource, handDevice); trackedHands.Remove(handDevice.ControllerHandedness); RecyclePointers(handDevice.InputSource); } #endregion #endif // OCULUSINTEGRATION_PRESENT } }
35.47769
262
0.60657
[ "MIT" ]
Aminadad27/MixedRealityToolkit-Unity
Assets/MRTK/Providers/Oculus/XRSDK/OculusXRSDKDeviceManager.cs
13,519
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("GrayLib")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("GrayLib")] [assembly: AssemblyCopyright("Rideu Cooperation © 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("b228117e-8bc1-4737-bb83-de1e068798b2")] // 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("0.4.3.0")] [assembly: AssemblyFileVersion("0.4.3.0")]
37.540541
84
0.7473
[ "MIT" ]
Rideu/unia
GrayLib/Properties/AssemblyInfo.cs
1,392
C#
using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; namespace Standard { [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")] [StructLayout(LayoutKind.Sequential, Pack = 4)] internal class SHARDAPPIDINFOLINK { private IntPtr psl; [MarshalAs(UnmanagedType.LPWStr)] private string pszAppID; } }
25.294118
92
0.704651
[ "MIT" ]
Yerongn/HandyControl
src/Shared/Microsoft.Windows.Shell/Standard/SHARDAPPIDINFOLINK.cs
432
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.UI; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using LinkerUi.Areas.Identity; using LinkerUi.Data; using Sotsera.Blazor.Toaster.Core.Models; namespace LinkerUi { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddDbContext<ApplicationDbContext>(options => options.UseSqlite(Configuration.GetConnectionString("DefaultConnection"))); services.AddDefaultIdentity<IdentityUser>(options => { options.SignIn.RequireConfirmedAccount = false; options.Password.RequireDigit = false; options.Password.RequireNonAlphanumeric = false; }) .AddEntityFrameworkStores<ApplicationDbContext>(); services.AddRazorPages(); services.AddServerSideBlazor(); services.AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<IdentityUser>>(); services.AddSingleton<LinkService>(); services.AddToaster(config => { //example customizations config.PositionClass = Defaults.Classes.Position.TopRight; config.PreventDuplicates = true; config.NewestOnTop = false; }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapBlazorHub(); endpoints.MapFallbackToPage("/_Host"); }); } } }
36.764045
143
0.635697
[ "Apache-2.0" ]
riccardone/Linker.Ui
src/LinkerUi/Startup.cs
3,272
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.DocumentHighlighting { internal abstract partial class AbstractDocumentHighlightsService : IDocumentHighlightsService { public async Task<ImmutableArray<DocumentHighlights>> GetDocumentHighlightsAsync( Document document, int position, IImmutableSet<Document> documentsToSearch, CancellationToken cancellationToken) { var (succeeded, highlights) = await GetDocumentHighlightsInRemoteProcessAsync( document, position, documentsToSearch, cancellationToken).ConfigureAwait(false); if (succeeded) { return highlights; } return await GetDocumentHighlightsInCurrentProcessAsync( document, position, documentsToSearch, cancellationToken).ConfigureAwait(false); } private async Task<(bool succeeded, ImmutableArray<DocumentHighlights> highlights)> GetDocumentHighlightsInRemoteProcessAsync( Document document, int position, IImmutableSet<Document> documentsToSearch, CancellationToken cancellationToken) { var result = await document.Project.Solution.TryRunCodeAnalysisRemoteAsync<IList<SerializableDocumentHighlights>>( RemoteFeatureOptions.DocumentHighlightingEnabled, nameof(IRemoteDocumentHighlights.GetDocumentHighlightsAsync), new object[] { document.Id, position, documentsToSearch.Select(d => d.Id).ToArray() }, cancellationToken).ConfigureAwait(false); if (result == null) { return (succeeded: false, ImmutableArray<DocumentHighlights>.Empty); } return (true, result.SelectAsArray(h => h.Rehydrate(document.Project.Solution))); } private async Task<ImmutableArray<DocumentHighlights>> GetDocumentHighlightsInCurrentProcessAsync( Document document, int position, IImmutableSet<Document> documentsToSearch, CancellationToken cancellationToken) { var result = await TryGetEmbeddedLanguageHighlightsAsync(document, position, cancellationToken).ConfigureAwait(false); if (!result.IsDefaultOrEmpty) { return result; } // use speculative semantic model to see whether we are on a symbol we can do HR var span = new TextSpan(position, 0); var solution = document.Project.Solution; var semanticModel = await document.GetSemanticModelForSpanAsync(span, cancellationToken).ConfigureAwait(false); var symbol = await SymbolFinder.FindSymbolAtPositionAsync( semanticModel, position, solution.Workspace, cancellationToken).ConfigureAwait(false); if (symbol == null) { return ImmutableArray<DocumentHighlights>.Empty; } symbol = await GetSymbolToSearchAsync(document, position, semanticModel, symbol, cancellationToken).ConfigureAwait(false); if (symbol == null) { return ImmutableArray<DocumentHighlights>.Empty; } // Get unique tags for referenced symbols return await GetTagsForReferencedSymbolAsync( new SymbolAndProjectId(symbol, document.Project.Id), document, documentsToSearch, cancellationToken).ConfigureAwait(false); } private async Task<ImmutableArray<DocumentHighlights>> TryGetEmbeddedLanguageHighlightsAsync( Document document, int position, CancellationToken cancellationToken) { var embeddedLanguagesProvider = document.GetLanguageService<IEmbeddedLanguagesProvider>(); if (embeddedLanguagesProvider != null) { foreach (var language in embeddedLanguagesProvider.GetEmbeddedLanguages()) { var highlighter = language.Highlighter; if (highlighter != null) { var highlights = await highlighter.GetHighlightsAsync( document, position, cancellationToken).ConfigureAwait(false); if (!highlights.IsDefaultOrEmpty) { var result = ArrayBuilder<HighlightSpan>.GetInstance(); foreach (var span in highlights) { result.Add(new HighlightSpan(span, HighlightSpanKind.None)); } return ImmutableArray.Create(new DocumentHighlights( document, result.ToImmutableAndFree())); } } } } return default; } private static async Task<ISymbol> GetSymbolToSearchAsync(Document document, int position, SemanticModel semanticModel, ISymbol symbol, CancellationToken cancellationToken) { // see whether we can use the symbol as it is var currentSemanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); if (currentSemanticModel == semanticModel) { return symbol; } // get symbols from current document again return await SymbolFinder.FindSymbolAtPositionAsync(currentSemanticModel, position, document.Project.Solution.Workspace, cancellationToken).ConfigureAwait(false); } private async Task<ImmutableArray<DocumentHighlights>> GetTagsForReferencedSymbolAsync( SymbolAndProjectId symbolAndProjectId, Document document, IImmutableSet<Document> documentsToSearch, CancellationToken cancellationToken) { var symbol = symbolAndProjectId.Symbol; Contract.ThrowIfNull(symbol); if (ShouldConsiderSymbol(symbol)) { var progress = new StreamingProgressCollector( StreamingFindReferencesProgress.Instance); var options = FindReferencesSearchOptions.GetFeatureOptionsForStartingSymbol(symbol); await SymbolFinder.FindReferencesAsync( symbolAndProjectId, document.Project.Solution, progress, documentsToSearch, options, cancellationToken).ConfigureAwait(false); return await FilterAndCreateSpansAsync( progress.GetReferencedSymbols(), document, documentsToSearch, symbol, options, cancellationToken).ConfigureAwait(false); } return ImmutableArray<DocumentHighlights>.Empty; } private static bool ShouldConsiderSymbol(ISymbol symbol) { switch (symbol.Kind) { case SymbolKind.Method: switch (((IMethodSymbol)symbol).MethodKind) { case MethodKind.AnonymousFunction: case MethodKind.PropertyGet: case MethodKind.PropertySet: case MethodKind.EventAdd: case MethodKind.EventRaise: case MethodKind.EventRemove: return false; default: return true; } default: return true; } } private async Task<ImmutableArray<DocumentHighlights>> FilterAndCreateSpansAsync( IEnumerable<ReferencedSymbol> references, Document startingDocument, IImmutableSet<Document> documentsToSearch, ISymbol symbol, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var solution = startingDocument.Project.Solution; references = references.FilterToItemsToShow(options); references = references.FilterNonMatchingMethodNames(solution, symbol); references = references.FilterToAliasMatches(symbol as IAliasSymbol); if (symbol.IsConstructor()) { references = references.Where(r => r.Definition.OriginalDefinition.Equals(symbol.OriginalDefinition)); } var additionalReferences = new List<Location>(); foreach (var currentDocument in documentsToSearch) { // 'documentsToSearch' may contain documents from languages other than our own // (for example cshtml files when we're searching the cs document). Since we're // delegating to a virtual method for this language type, we have to make sure // we only process the document if it's also our language. if (currentDocument.Project.Language == startingDocument.Project.Language) { additionalReferences.AddRange(await GetAdditionalReferencesAsync(currentDocument, symbol, cancellationToken).ConfigureAwait(false)); } } return await CreateSpansAsync( solution, symbol, references, additionalReferences, documentsToSearch, cancellationToken).ConfigureAwait(false); } protected virtual Task<ImmutableArray<Location>> GetAdditionalReferencesAsync( Document document, ISymbol symbol, CancellationToken cancellationToken) { return SpecializedTasks.EmptyImmutableArray<Location>(); } private static async Task<ImmutableArray<DocumentHighlights>> CreateSpansAsync( Solution solution, ISymbol symbol, IEnumerable<ReferencedSymbol> references, IEnumerable<Location> additionalReferences, IImmutableSet<Document> documentToSearch, CancellationToken cancellationToken) { var spanSet = new HashSet<DocumentSpan>(); var tagMap = new MultiDictionary<Document, HighlightSpan>(); bool addAllDefinitions = true; // Add definitions // Filter out definitions that cannot be highlighted. e.g: alias symbols defined via project property pages. if (symbol.Kind == SymbolKind.Alias && symbol.Locations.Length > 0) { addAllDefinitions = false; if (symbol.Locations.First().IsInSource) { // For alias symbol we want to get the tag only for the alias definition, not the target symbol's definition. await AddLocationSpan(symbol.Locations.First(), solution, spanSet, tagMap, HighlightSpanKind.Definition, cancellationToken).ConfigureAwait(false); } } // Add references and definitions foreach (var reference in references) { if (addAllDefinitions && ShouldIncludeDefinition(reference.Definition)) { foreach (var location in reference.Definition.Locations) { if (location.IsInSource) { var document = solution.GetDocument(location.SourceTree); // GetDocument will return null for locations in #load'ed trees. // TODO: Remove this check and add logic to fetch the #load'ed tree's // Document once https://github.com/dotnet/roslyn/issues/5260 is fixed. if (document == null) { Debug.Assert(solution.Workspace.Kind == WorkspaceKind.Interactive || solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles); continue; } if (documentToSearch.Contains(document)) { await AddLocationSpan(location, solution, spanSet, tagMap, HighlightSpanKind.Definition, cancellationToken).ConfigureAwait(false); } } } } foreach (var referenceLocation in reference.Locations) { var referenceKind = referenceLocation.IsWrittenTo ? HighlightSpanKind.WrittenReference : HighlightSpanKind.Reference; await AddLocationSpan(referenceLocation.Location, solution, spanSet, tagMap, referenceKind, cancellationToken).ConfigureAwait(false); } } // Add additional references foreach (var location in additionalReferences) { await AddLocationSpan(location, solution, spanSet, tagMap, HighlightSpanKind.Reference, cancellationToken).ConfigureAwait(false); } var list = ArrayBuilder<DocumentHighlights>.GetInstance(tagMap.Count); foreach (var kvp in tagMap) { var spans = ArrayBuilder<HighlightSpan>.GetInstance(kvp.Value.Count); foreach (var span in kvp.Value) { spans.Add(span); } list.Add(new DocumentHighlights(kvp.Key, spans.ToImmutableAndFree())); } return list.ToImmutableAndFree(); } private static bool ShouldIncludeDefinition(ISymbol symbol) { switch (symbol.Kind) { case SymbolKind.Namespace: return false; case SymbolKind.NamedType: return !((INamedTypeSymbol)symbol).IsScriptClass; case SymbolKind.Parameter: // If it's an indexer parameter, we will have also cascaded to the accessor // one that actually receives the references var containingProperty = symbol.ContainingSymbol as IPropertySymbol; if (containingProperty != null && containingProperty.IsIndexer) { return false; } break; } return true; } private static async Task AddLocationSpan(Location location, Solution solution, HashSet<DocumentSpan> spanSet, MultiDictionary<Document, HighlightSpan> tagList, HighlightSpanKind kind, CancellationToken cancellationToken) { var span = await GetLocationSpanAsync(solution, location, cancellationToken).ConfigureAwait(false); if (span != null && !spanSet.Contains(span.Value)) { spanSet.Add(span.Value); tagList.Add(span.Value.Document, new HighlightSpan(span.Value.SourceSpan, kind)); } } private static async Task<DocumentSpan?> GetLocationSpanAsync( Solution solution, Location location, CancellationToken cancellationToken) { try { if (location != null && location.IsInSource) { var tree = location.SourceTree; var document = solution.GetDocument(tree); var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); if (syntaxFacts != null) { // Specify findInsideTrivia: true to ensure that we search within XML doc comments. var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(location.SourceSpan.Start, findInsideTrivia: true); return syntaxFacts.IsGenericName(token.Parent) || syntaxFacts.IsIndexerMemberCRef(token.Parent) ? new DocumentSpan(document, token.Span) : new DocumentSpan(document, location.SourceSpan); } } } catch (NullReferenceException e) when (FatalError.ReportWithoutCrash(e)) { // We currently are seeing a strange null references crash in this code. We have // a strong belief that this is recoverable, but we'd like to know why it is // happening. This exception filter allows us to report the issue and continue // without damaging the user experience. Once we get more crash reports, we // can figure out the root cause and address appropriately. This is preferable // to just using conditionl access operators to be resilient (as we won't actually // know why this is happening). } return null; } } }
45.958656
229
0.598392
[ "Apache-2.0" ]
AdamSpeight2008/roslyn-1
src/Features/Core/Portable/DocumentHighlighting/AbstractDocumentHighlightsService.cs
17,788
C#
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace trainingDiaryBackend.Migrations { public partial class initial : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "food", columns: table => new { id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), description = table.Column<string>(maxLength: 500, nullable: true), calories = table.Column<double>(nullable: true), carbs = table.Column<double>(nullable: true), fats = table.Column<double>(nullable: true), proteins = table.Column<double>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_food", x => x.id); }); migrationBuilder.CreateTable( name: "person", columns: table => new { id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), userName = table.Column<string>(maxLength: 50, nullable: false), email = table.Column<string>(maxLength: 320, nullable: false) }, constraints: table => { table.PrimaryKey("PK_person", x => x.id); }); migrationBuilder.CreateTable( name: "meal", columns: table => new { id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), personId = table.Column<int>(nullable: false), name = table.Column<string>(maxLength: 100, nullable: false), description = table.Column<string>(maxLength: 500, nullable: true), timestamp = table.Column<DateTime>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_meal", x => x.id); table.ForeignKey( name: "FK_meal_person_personId", column: x => x.personId, principalTable: "person", principalColumn: "id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "weight", columns: table => new { id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), personId = table.Column<int>(nullable: false), amount = table.Column<double>(nullable: false), timestamp = table.Column<DateTime>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_weight", x => x.id); table.ForeignKey( name: "FK_weight_person_personId", column: x => x.personId, principalTable: "person", principalColumn: "id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_meal_personId", table: "meal", column: "personId"); migrationBuilder.CreateIndex( name: "IX_person_email", table: "person", column: "email", unique: true); migrationBuilder.CreateIndex( name: "IX_weight_personId", table: "weight", column: "personId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "food"); migrationBuilder.DropTable( name: "meal"); migrationBuilder.DropTable( name: "weight"); migrationBuilder.DropTable( name: "person"); } } }
37.863248
87
0.459594
[ "Apache-2.0" ]
Pulssi/training_diary_backend
src/training_diary_API/Migrations/20220502201641_initial.cs
4,432
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // using System; using System.IO; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Xunit; using Xunit.Abstractions; namespace AutoRest.CSharp.Unit.Tests { public class Bug1288 : BugTest { public Bug1288(ITestOutputHelper output) : base(output) { } /// <summary> /// https://github.com/Azure/autorest/issues/1288 /// Support format:'char' for single character strings. /// </summary> [Fact] public async Task CompositeSwaggerWithPayloadFlattening() { // simplified test pattern for unit testing aspects of code generation using (var fileSystem = GenerateCodeForTestFromSpec(modeler: "CompositeSwagger")) { // Expected Files Assert.True(fileSystem.FileExists(Path.Combine("CompositeModel.cs"))); Assert.True(fileSystem.FileExists(Path.Combine("Models", "Param1.cs"))); var result = await Compile(fileSystem); // filter the warnings var warnings = result.Messages.Where( each => each.Severity == DiagnosticSeverity.Warning && !SuppressWarnings.Contains(each.Id)).ToArray(); // use this to dump the files to disk for examination // fileSystem.SaveFilesToTemp("bug1288"); // Or just use this to see the generated code in VsCode :D // ShowGeneratedCode(fileSystem); // filter the errors var errors = result.Messages.Where(each => each.Severity == DiagnosticSeverity.Error).ToArray(); Write(warnings, fileSystem); Write(errors, fileSystem); // use this to write out all the messages, even hidden ones. // Write(result.Messages, fileSystem); // Don't proceed unless we have zero Warnings. Assert.Empty(warnings); // Don't proceed unless we have zero Errors. Assert.Empty(errors); // Should also succeed. Assert.True(result.Succeeded); // try to load the assembly var asm = LoadAssembly(result.Output); Assert.NotNull(asm); // verify that we have the composite class we expected var testCompositeObject = asm.ExportedTypes.FirstOrDefault(each => each.FullName == "Test.CompositeModel"); Assert.NotNull(testCompositeObject); // verify that we have the class we expected var testObject = asm.ExportedTypes.FirstOrDefault(each => each.FullName == "Test.Models.Param1"); Assert.NotNull(testObject); // verify the property is generated var property1 = testObject.GetProperty("Prop1"); Assert.NotNull(property1); // verify the property is generated var property2 = testObject.GetProperty("Prop2"); Assert.NotNull(property2); } } } }
37.933333
123
0.572935
[ "MIT" ]
bloudraak/autorest
src/generator/AutoRest.CSharp.Unit.Tests/Bug1288.cs
3,416
C#
using Avalonia.Controls; using DesktopUI2.Views.Filters; using System; using System.Collections.Generic; using System.Text; namespace DesktopUI2.Models.Filters { public class AllSelectionFilter : ISelectionFilter { public string Type => typeof(ListSelectionFilter).ToString(); public string Name { get; set; } public string Slug { get; set; } public string Icon { get; set; } public string Description { get; set; } public List<string> Selection { get; set; } = new List<string>(); public UserControl View { get; set; } = new AllFilterView(); public string Summary { get { return "Everything"; } } } }
23.37931
69
0.662242
[ "Apache-2.0" ]
OswaldoHernandezB/speckle-sharp
DesktopUI2/DesktopUI2/Models/Filters/AllSelectionFilter.cs
680
C#
namespace CG.Contracts.CodeFirstConventions { using System.Data.Entity.ModelConfiguration.Configuration; using System.Data.Entity.ModelConfiguration.Conventions; using CG.Contracts.DataAnnotations; public class IsUnicodeAttributeConvention : PrimitivePropertyAttributeConfigurationConvention<IsUnicodeAttribute> { public override void Apply( ConventionPrimitivePropertyConfiguration configuration, IsUnicodeAttribute attribute) { configuration.IsUnicode(attribute.IsUnicode); } } }
32.944444
78
0.711636
[ "MIT" ]
ASP-MVC/CodeGist-System
CG/CG.Contracts/CodeFirstConventions/IsUnicodeAttributeConvention.cs
595
C#
using System; using System.Diagnostics; using System.Reflection; namespace Puresharp { public partial class Weave { public partial class Connection : IConnection { [DebuggerBrowsable(DebuggerBrowsableState.Never)] private Aspect m_Aspect; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private MethodBase m_Method; internal Connection(Aspect aspect, MethodBase method) { this.m_Aspect = aspect; this.m_Method = method; } public Aspect Aspect { get { return this.m_Aspect; } } public MethodBase Method { get { return this.m_Method; } } } } }
23.057143
65
0.535316
[ "MIT" ]
Virtuoze/Puresharp
Puresharp/Puresharp/Weave/Weave.Connection.cs
809
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; namespace ErikEJ.SqlCeToolbox.ToolWindows { // Thanks to http://www.codeproject.com/KB/grid/ExtendedDataGridView.aspx partial class PanelQuickSearch : UserControl { public PanelQuickSearch() { InitializeComponent(); Dock = DockStyle.Bottom; } protected override void OnLoad(EventArgs e) { base.OnLoad(e); lblQuickFind.Location = new Point(btnClose .Right, GetY(lblQuickFind)); txtToFind .Location = new Point(lblQuickFind.Right, GetY(txtToFind)); lblOn .Location = new Point(txtToFind .Right, GetY(lblOn)); lblCol .Location = new Point(lblOn .Right, GetY(lblCol)); } int GetY(Control control) { return (Height - control.Height) / 2; } private void txtToFind_TextChanged(object sender, EventArgs e) { OnSearchChanged(txtToFind.Text); } public delegate void SearchHandler(string search); public event SearchHandler SearchChanged; public void OnSearchChanged(string search) { if (SearchChanged != null && !string.IsNullOrEmpty(search)) SearchChanged(search); } protected override void OnLeave(EventArgs e) { base.OnLeave(e); Hide(); } protected override void OnGotFocus(EventArgs e) { base.OnGotFocus(e); txtToFind.Focus(); } private void txtToFind_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Escape) Hide(); } public string Search { get { return txtToFind.Text; } set { txtToFind.Text = value; } } public string Column { get { return lblCol.Text; } set { lblCol.Text = value; } } private void btnClose_Click(object sender, EventArgs e) { Hide(); } } }
26.16092
86
0.558875
[ "Apache-2.0" ]
BekoSan/SqlCeToolbox
src/GUI/SqlCe40ToolboxExe/ToolWindows/PanelQuickSearch.cs
2,276
C#
using System; namespace IngameScript { /// <summary> /// Lazy-allocation encapsulation of the current date and time. /// </summary> public class Datestamp { public static Datestamp Minutes { get; } = new Datestamp("dd MMM HH:mm"); public static Datestamp Seconds { get; } = new Datestamp("dd MMM HH:mm:ss"); private readonly string format; private Datestamp(string format) { this.format = format; } public override string ToString() => DateTime.Now.ToString(format); } }
25.652174
85
0.586441
[ "Unlicense" ]
alex-davidson/SEScriptDev
Shared.Core/Datestamp.cs
592
C#
namespace Edile { /// <summary> /// The raw data for one aspect of the object. /// </summary> public abstract class Component { public Component(int entity_id) { this.EntityID = entity_id; } public readonly int EntityID; } }
15.25
47
0.663934
[ "Apache-2.0" ]
DevRect/Edile
Edile/Component/Component.cs
246
C#
using System.Collections.Generic; using System.ComponentModel; namespace ActivityMonitor.WinApp.ViewModels { public class PropertyChangedEventArgsCache { private readonly Dictionary<string, PropertyChangedEventArgs> _Cache = new(); public PropertyChangedEventArgs Get(string propertyName) { if (!_Cache.TryGetValue(propertyName, out var eventArgs)) { eventArgs = new PropertyChangedEventArgs(propertyName); _Cache.Add(propertyName, eventArgs); } return eventArgs; } } }
28.380952
85
0.651007
[ "MIT" ]
suzu-devworks/activity-monitor-dotnet
src/ActivityMonitor.WinApp/ViewModels/PropertyChangedEventArgsCache.cs
596
C#
namespace Battleships.Logic.Contracts { public interface IEngine { void Run(); } }
13
38
0.605769
[ "MIT" ]
svetlai/Battleships
Battleships.Logic/Contracts/IEngine.cs
106
C#
using System.Collections.Generic; using SeptemberUIChallenge.Data.Models; namespace SeptemberUIChallenge.Data.Infrastructure { public interface IUserRepository { void AddFavouriteUser(UserDetails user); IEnumerable<UserDetails> GetAllFavouritesUsers(); } }
25.909091
57
0.768421
[ "MIT" ]
bbenetskyy/XamainFormsSeptemberUIChallenge
SeptemberUIChallenge/SeptemberUIChallenge.Data/Infrastructure/IUserRepository.cs
285
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.Lclb.Cllb.Interfaces.Models { using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// Microsoft.Dynamics.CRM.kbarticletemplate /// </summary> public partial class MicrosoftDynamicsCRMkbarticletemplate { /// <summary> /// Initializes a new instance of the /// MicrosoftDynamicsCRMkbarticletemplate class. /// </summary> public MicrosoftDynamicsCRMkbarticletemplate() { CustomInit(); } /// <summary> /// Initializes a new instance of the /// MicrosoftDynamicsCRMkbarticletemplate class. /// </summary> /// <param name="componentstate">For internal use only.</param> /// <param name="overriddencreatedon">Date and time that the record was /// migrated.</param> /// <param name="_createdonbehalfbyValue">Unique identifier of the /// delegate user who created the kbarticletemplate.</param> /// <param name="iscustomizable">Information that specifies whether /// this component can be customized.</param> /// <param name="description">Description of the knowledge base article /// template.</param> /// <param name="introducedversion">Version in which the form is /// introduced.</param> /// <param name="_modifiedbyValue">Unique identifier of the user who /// last modified the knowledge base article template.</param> /// <param name="modifiedon">Date and time when the knowledge base /// article template was last modified.</param> /// <param name="overwritetime">For internal use only.</param> /// <param name="solutionid">Unique identifier of the associated /// solution.</param> /// <param name="structurexml">XML structure of the knowledge base /// article.</param> /// <param name="_modifiedonbehalfbyValue">Unique identifier of the /// delegate user who last modified the kbarticletemplate.</param> /// <param name="title">Title of the knowledge base article /// template.</param> /// <param name="createdon">Date and time when the knowledge base /// article template was created.</param> /// <param name="importsequencenumber">Unique identifier of the data /// import or data migration that created this record.</param> /// <param name="kbarticletemplateidunique">For internal use /// only.</param> /// <param name="languagecode">Language of the Article Template</param> /// <param name="kbarticletemplateid">Unique identifier of the /// knowledge base article template.</param> /// <param name="isactive">Information about whether the knowledge base /// article is active.</param> /// <param name="formatxml">XML format of the knowledge base article /// template.</param> /// <param name="_organizationidValue">Unique identifier of the /// organization associated with the template.</param> /// <param name="_createdbyValue">Unique identifier of the user who /// created the knowledge base article template.</param> public MicrosoftDynamicsCRMkbarticletemplate(int? componentstate = default(int?), System.DateTimeOffset? overriddencreatedon = default(System.DateTimeOffset?), string _createdonbehalfbyValue = default(string), string iscustomizable = default(string), string description = default(string), string introducedversion = default(string), string _modifiedbyValue = default(string), System.DateTimeOffset? modifiedon = default(System.DateTimeOffset?), System.DateTimeOffset? overwritetime = default(System.DateTimeOffset?), string solutionid = default(string), string structurexml = default(string), string _modifiedonbehalfbyValue = default(string), string versionnumber = default(string), string title = default(string), System.DateTimeOffset? createdon = default(System.DateTimeOffset?), int? importsequencenumber = default(int?), string kbarticletemplateidunique = default(string), int? languagecode = default(int?), string kbarticletemplateid = default(string), bool? isactive = default(bool?), string formatxml = default(string), bool? ismanaged = default(bool?), string _organizationidValue = default(string), string _createdbyValue = default(string), MicrosoftDynamicsCRMsystemuser createdby = default(MicrosoftDynamicsCRMsystemuser), IList<MicrosoftDynamicsCRMasyncoperation> kbArticleTemplateAsyncOperations = default(IList<MicrosoftDynamicsCRMasyncoperation>), IList<MicrosoftDynamicsCRMkbarticle> kbArticleTemplateKbArticles = default(IList<MicrosoftDynamicsCRMkbarticle>), MicrosoftDynamicsCRMsystemuser createdonbehalfby = default(MicrosoftDynamicsCRMsystemuser), IList<MicrosoftDynamicsCRMsyncerror> kbArticleTemplateSyncErrors = default(IList<MicrosoftDynamicsCRMsyncerror>), IList<MicrosoftDynamicsCRMbulkdeletefailure> kbArticleTemplateBulkDeleteFailures = default(IList<MicrosoftDynamicsCRMbulkdeletefailure>), MicrosoftDynamicsCRMorganization organizationid = default(MicrosoftDynamicsCRMorganization), MicrosoftDynamicsCRMsystemuser modifiedonbehalfby = default(MicrosoftDynamicsCRMsystemuser), MicrosoftDynamicsCRMsystemuser modifiedby = default(MicrosoftDynamicsCRMsystemuser)) { Componentstate = componentstate; Overriddencreatedon = overriddencreatedon; this._createdonbehalfbyValue = _createdonbehalfbyValue; Iscustomizable = iscustomizable; Description = description; Introducedversion = introducedversion; this._modifiedbyValue = _modifiedbyValue; Modifiedon = modifiedon; Overwritetime = overwritetime; Solutionid = solutionid; Structurexml = structurexml; this._modifiedonbehalfbyValue = _modifiedonbehalfbyValue; Versionnumber = versionnumber; Title = title; Createdon = createdon; Importsequencenumber = importsequencenumber; Kbarticletemplateidunique = kbarticletemplateidunique; Languagecode = languagecode; Kbarticletemplateid = kbarticletemplateid; Isactive = isactive; Formatxml = formatxml; Ismanaged = ismanaged; this._organizationidValue = _organizationidValue; this._createdbyValue = _createdbyValue; Createdby = createdby; KbArticleTemplateAsyncOperations = kbArticleTemplateAsyncOperations; KbArticleTemplateKbArticles = kbArticleTemplateKbArticles; Createdonbehalfby = createdonbehalfby; KbArticleTemplateSyncErrors = kbArticleTemplateSyncErrors; KbArticleTemplateBulkDeleteFailures = kbArticleTemplateBulkDeleteFailures; Organizationid = organizationid; Modifiedonbehalfby = modifiedonbehalfby; Modifiedby = modifiedby; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets for internal use only. /// </summary> [JsonProperty(PropertyName = "componentstate")] public int? Componentstate { get; set; } /// <summary> /// Gets or sets date and time that the record was migrated. /// </summary> [JsonProperty(PropertyName = "overriddencreatedon")] public System.DateTimeOffset? Overriddencreatedon { get; set; } /// <summary> /// Gets or sets unique identifier of the delegate user who created the /// kbarticletemplate. /// </summary> [JsonProperty(PropertyName = "_createdonbehalfby_value")] public string _createdonbehalfbyValue { get; set; } /// <summary> /// Gets or sets information that specifies whether this component can /// be customized. /// </summary> [JsonProperty(PropertyName = "iscustomizable")] public string Iscustomizable { get; set; } /// <summary> /// Gets or sets description of the knowledge base article template. /// </summary> [JsonProperty(PropertyName = "description")] public string Description { get; set; } /// <summary> /// Gets or sets version in which the form is introduced. /// </summary> [JsonProperty(PropertyName = "introducedversion")] public string Introducedversion { get; set; } /// <summary> /// Gets or sets unique identifier of the user who last modified the /// knowledge base article template. /// </summary> [JsonProperty(PropertyName = "_modifiedby_value")] public string _modifiedbyValue { get; set; } /// <summary> /// Gets or sets date and time when the knowledge base article template /// was last modified. /// </summary> [JsonProperty(PropertyName = "modifiedon")] public System.DateTimeOffset? Modifiedon { get; set; } /// <summary> /// Gets or sets for internal use only. /// </summary> [JsonProperty(PropertyName = "overwritetime")] public System.DateTimeOffset? Overwritetime { get; set; } /// <summary> /// Gets or sets unique identifier of the associated solution. /// </summary> [JsonProperty(PropertyName = "solutionid")] public string Solutionid { get; set; } /// <summary> /// Gets or sets XML structure of the knowledge base article. /// </summary> [JsonProperty(PropertyName = "structurexml")] public string Structurexml { get; set; } /// <summary> /// Gets or sets unique identifier of the delegate user who last /// modified the kbarticletemplate. /// </summary> [JsonProperty(PropertyName = "_modifiedonbehalfby_value")] public string _modifiedonbehalfbyValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "versionnumber")] public string Versionnumber { get; set; } /// <summary> /// Gets or sets title of the knowledge base article template. /// </summary> [JsonProperty(PropertyName = "title")] public string Title { get; set; } /// <summary> /// Gets or sets date and time when the knowledge base article template /// was created. /// </summary> [JsonProperty(PropertyName = "createdon")] public System.DateTimeOffset? Createdon { get; set; } /// <summary> /// Gets or sets unique identifier of the data import or data migration /// that created this record. /// </summary> [JsonProperty(PropertyName = "importsequencenumber")] public int? Importsequencenumber { get; set; } /// <summary> /// Gets or sets for internal use only. /// </summary> [JsonProperty(PropertyName = "kbarticletemplateidunique")] public string Kbarticletemplateidunique { get; set; } /// <summary> /// Gets or sets language of the Article Template /// </summary> [JsonProperty(PropertyName = "languagecode")] public int? Languagecode { get; set; } /// <summary> /// Gets or sets unique identifier of the knowledge base article /// template. /// </summary> [JsonProperty(PropertyName = "kbarticletemplateid")] public string Kbarticletemplateid { get; set; } /// <summary> /// Gets or sets information about whether the knowledge base article /// is active. /// </summary> [JsonProperty(PropertyName = "isactive")] public bool? Isactive { get; set; } /// <summary> /// Gets or sets XML format of the knowledge base article template. /// </summary> [JsonProperty(PropertyName = "formatxml")] public string Formatxml { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "ismanaged")] public bool? Ismanaged { get; set; } /// <summary> /// Gets or sets unique identifier of the organization associated with /// the template. /// </summary> [JsonProperty(PropertyName = "_organizationid_value")] public string _organizationidValue { get; set; } /// <summary> /// Gets or sets unique identifier of the user who created the /// knowledge base article template. /// </summary> [JsonProperty(PropertyName = "_createdby_value")] public string _createdbyValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "createdby")] public MicrosoftDynamicsCRMsystemuser Createdby { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "KbArticleTemplate_AsyncOperations")] public IList<MicrosoftDynamicsCRMasyncoperation> KbArticleTemplateAsyncOperations { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "kb_article_template_kb_articles")] public IList<MicrosoftDynamicsCRMkbarticle> KbArticleTemplateKbArticles { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "createdonbehalfby")] public MicrosoftDynamicsCRMsystemuser Createdonbehalfby { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "KbArticleTemplate_SyncErrors")] public IList<MicrosoftDynamicsCRMsyncerror> KbArticleTemplateSyncErrors { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "KbArticleTemplate_BulkDeleteFailures")] public IList<MicrosoftDynamicsCRMbulkdeletefailure> KbArticleTemplateBulkDeleteFailures { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "organizationid")] public MicrosoftDynamicsCRMorganization Organizationid { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "modifiedonbehalfby")] public MicrosoftDynamicsCRMsystemuser Modifiedonbehalfby { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "modifiedby")] public MicrosoftDynamicsCRMsystemuser Modifiedby { get; set; } } }
47.063291
2,101
0.652098
[ "Apache-2.0" ]
ElizabethWolfe/jag-lcrb-carla-public
cllc-interfaces/Dynamics-Autorest/Models/MicrosoftDynamicsCRMkbarticletemplate.cs
14,872
C#
using System.Collections.Generic; using System.Runtime.Serialization; // ReSharper disable once CheckNamespace namespace Sentry.Protocol { /// <summary> /// A frame of a stacktrace. /// </summary> /// <see href="https://docs.sentry.io/clientdev/interfaces/stacktrace/"/> [DataContract] public class SentryStackFrame { [DataMember(Name = "pre_context", EmitDefaultValue = false)] internal List<string>? InternalPreContext { get; private set; } [DataMember(Name = "post_context", EmitDefaultValue = false)] internal List<string>? InternalPostContext { get; private set; } [DataMember(Name = "vars", EmitDefaultValue = false)] internal Dictionary<string, string>? InternalVars { get; private set; } [DataMember(Name = "frames_omitted ", EmitDefaultValue = false)] internal List<int>? InternalFramesOmitted { get; private set; } /// <summary> /// The relative file path to the call. /// </summary> [DataMember(Name = "filename", EmitDefaultValue = false)] public string? FileName { get; set; } /// <summary> /// The name of the function being called. /// </summary> [DataMember(Name = "function", EmitDefaultValue = false)] public string? Function { get; set; } /// <summary> /// Platform-specific module path. /// </summary> [DataMember(Name = "module", EmitDefaultValue = false)] public string? Module { get; set; } // Optional fields /// <summary> /// Module Version Id. /// </summary> /// <remarks>Used by the Mono AOT compiler</remarks> [DataMember(Name = "mvid", EmitDefaultValue = false)] public string? ModuleVersionId { get; set; } /// <summary> /// AOT Id. /// </summary> /// <remarks>Used by the Mono AOT compiler</remarks> [DataMember(Name = "aotid", EmitDefaultValue = false)] public string? AotId { get; set; } /// <summary> /// Method Index. /// </summary> /// <remarks>Used by the Mono AOT compiler</remarks> [DataMember(Name = "method_index", EmitDefaultValue = false)] public string? MethodIndex { get; set; } /// <summary> /// Is IL offset. /// </summary> /// <remarks>Used by the Mono AOT compiler</remarks> [DataMember(Name = "is_il_offset", EmitDefaultValue = false)] public bool? IsILOffset { get; set; } /// <summary> /// The line number of the call. /// </summary> [DataMember(Name = "lineno", EmitDefaultValue = false)] public int? LineNumber { get; set; } /// <summary> /// The column number of the call. /// </summary> [DataMember(Name = "colno", EmitDefaultValue = false)] public int? ColumnNumber { get; set; } /// <summary> /// The absolute path to filename. /// </summary> [DataMember(Name = "abs_path", EmitDefaultValue = false)] public string? AbsolutePath { get; set; } /// <summary> /// Source code in filename at line number. /// </summary> [DataMember(Name = "context_line", EmitDefaultValue = false)] public string? ContextLine { get; set; } /// <summary> /// A list of source code lines before context_line (in order) – usually [lineno - 5:lineno]. /// </summary> public IList<string> PreContext => InternalPreContext ??= new List<string>(); /// <summary> /// A list of source code lines after context_line (in order) – usually [lineno + 1:lineno + 5]. /// </summary> public IList<string> PostContext => InternalPostContext ??= new List<string>(); /// <summary> /// Signifies whether this frame is related to the execution of the relevant code in this stacktrace. /// </summary> /// <example> /// For example, the frames that might power the framework’s web server of your app are probably not relevant, /// however calls to the framework’s library once you start handling code likely are. /// </example> [DataMember(Name = "in_app", EmitDefaultValue = false)] public bool? InApp { get; set; } /// <summary> /// A mapping of variables which were available within this frame (usually context-locals). /// </summary> public IDictionary<string, string> Vars => InternalVars ??= new Dictionary<string, string>(); /// <summary> /// Which frames were omitted, if any. /// </summary> /// <remarks> /// If the list of frames is large, you can explicitly tell the system that you’ve omitted a range of frames. /// The frames_omitted must be a single tuple two values: start and end. /// </remarks> /// <example> /// If you only removed the 8th frame, the value would be (8, 9), meaning it started at the 8th frame, /// and went until the 9th (the number of frames omitted is end-start). /// The values should be based on a one-index. /// </example> public IList<int> FramesOmitted => InternalFramesOmitted ??= new List<int>(); /// <summary> /// The assembly where the code resides. /// </summary> [DataMember(Name = "package", EmitDefaultValue = false)] public string? Package { get; set; } /// <summary> /// This can override the platform for a single frame. Otherwise the platform of the event is assumed. /// </summary> [DataMember(Name = "platform", EmitDefaultValue = false)] public string? Platform { get; set; } /// <summary> /// Optionally an address of the debug image to reference. /// If this is set and a known image is defined by debug_meta then symbolication can take place. /// </summary> [DataMember(Name = "image_addr", EmitDefaultValue = false)] public long ImageAddress { get; set; } /// <summary> /// An optional address that points to a symbol. /// We actually use the instruction address for symbolication but this can be used to calculate an instruction offset automatically. /// </summary> [DataMember(Name = "symbol_addr", EmitDefaultValue = false)] public long? SymbolAddress { get; set; } /// <summary> /// The instruction offset. /// </summary> /// <remarks> /// The official docs refer to it as 'The difference between instruction address and symbol address in bytes.' /// In .NET this means the IL Offset within the assembly. /// </remarks> [DataMember(Name = "instruction_offset", EmitDefaultValue = false)] public long? InstructionOffset { get; set; } } }
39.867816
140
0.591754
[ "MIT" ]
lucas-zimerman/sentry-dotnet-xamsample
src/Sentry.Protocol/Exceptions/SentryStackFrame.cs
6,947
C#
using System; using Moq; using NUnit.Framework; using WhenItsDone.Data.Contracts; using WhenItsDone.Data.UnitsOfWork.Factories; using WhenItsDone.Models.Contracts; using WhenItsDone.Services.Abstraction; namespace WhenItsDone.Services.Tests.AbstractionTests.GenericAsyncServiceTests { [TestFixture] public class Add_Should { [Test] public void ShouldThrowArgumentNullException_WhenItemParameterIsNull() { var asyncRepository = new Mock<IAsyncRepository<IDbModel>>(); var unitOfWorkFactory = new Mock<IDisposableUnitOfWorkFactory>(); var genericAsyncService = new GenericAsyncService<IDbModel>(asyncRepository.Object, unitOfWorkFactory.Object); IDbModel invalidItem = null; Assert.That( () => genericAsyncService.Add(invalidItem), Throws.InstanceOf<ArgumentNullException>().With.Message.Contains("Invalid item to add!")); } [Test] public void ShouldInvokeAsyncRepositoryAddMethodOnce_WhenParametersAreCorrect() { var mockAsyncRepository = new Mock<IAsyncRepository<IDbModel>>(); var mockUnitOfWork = new Mock<IDisposableUnitOfWork>(); var mockUnitOfWorkFactory = new Mock<IDisposableUnitOfWorkFactory>(); mockUnitOfWorkFactory.Setup(factory => factory.CreateUnitOfWork()).Returns(mockUnitOfWork.Object); var genericAsyncService = new GenericAsyncService<IDbModel>(mockAsyncRepository.Object, mockUnitOfWorkFactory.Object); var validItemToAdd = new Mock<IDbModel>(); genericAsyncService.Add(validItemToAdd.Object); mockAsyncRepository.Verify(repo => repo.Add(It.IsAny<IDbModel>()), Times.Once); } [Test] public void ShouldInvokeAsyncRepositoryAddMethodWithCorrectItem_WhenParametersAreCorrect() { var mockAsyncRepository = new Mock<IAsyncRepository<IDbModel>>(); var mockUnitOfWork = new Mock<IDisposableUnitOfWork>(); var mockUnitOfWorkFactory = new Mock<IDisposableUnitOfWorkFactory>(); mockUnitOfWorkFactory.Setup(factory => factory.CreateUnitOfWork()).Returns(mockUnitOfWork.Object); var genericAsyncService = new GenericAsyncService<IDbModel>(mockAsyncRepository.Object, mockUnitOfWorkFactory.Object); var validItemToAdd = new Mock<IDbModel>(); genericAsyncService.Add(validItemToAdd.Object); mockAsyncRepository.Verify(repo => repo.Add(validItemToAdd.Object), Times.Once); } [Test] public void ShouldInvokeIDisposableUnitOfWorkFactoryCreateUnitOfWorkMethodOnce_WhenParametersAreCorrect() { var mockAsyncRepository = new Mock<IAsyncRepository<IDbModel>>(); var mockUnitOfWork = new Mock<IDisposableUnitOfWork>(); var mockUnitOfWorkFactory = new Mock<IDisposableUnitOfWorkFactory>(); mockUnitOfWorkFactory.Setup(factory => factory.CreateUnitOfWork()).Returns(mockUnitOfWork.Object); var genericAsyncService = new GenericAsyncService<IDbModel>(mockAsyncRepository.Object, mockUnitOfWorkFactory.Object); var validItemToAdd = new Mock<IDbModel>(); genericAsyncService.Add(validItemToAdd.Object); mockUnitOfWorkFactory.Verify(repo => repo.CreateUnitOfWork(), Times.Once); } [Test] public void ShouldInvokeUnitOfWorkSaveChangesAsyncMethodOnce_WhenParametersAreCorrect() { var mockAsyncRepository = new Mock<IAsyncRepository<IDbModel>>(); var mockUnitOfWork = new Mock<IDisposableUnitOfWork>(); var mockUnitOfWorkFactory = new Mock<IDisposableUnitOfWorkFactory>(); mockUnitOfWorkFactory.Setup(factory => factory.CreateUnitOfWork()).Returns(mockUnitOfWork.Object); var genericAsyncService = new GenericAsyncService<IDbModel>(mockAsyncRepository.Object, mockUnitOfWorkFactory.Object); var validItemToAdd = new Mock<IDbModel>(); genericAsyncService.Add(validItemToAdd.Object); mockUnitOfWork.Verify(repo => repo.SaveChangesAsync(), Times.Once); } [Test] public void ShouldReturnTheCorrectItem_WhenParametersAreCorrect() { var mockAsyncRepository = new Mock<IAsyncRepository<IDbModel>>(); var mockUnitOfWork = new Mock<IDisposableUnitOfWork>(); var mockUnitOfWorkFactory = new Mock<IDisposableUnitOfWorkFactory>(); mockUnitOfWorkFactory.Setup(factory => factory.CreateUnitOfWork()).Returns(mockUnitOfWork.Object); var genericAsyncService = new GenericAsyncService<IDbModel>(mockAsyncRepository.Object, mockUnitOfWorkFactory.Object); var validItemToAdd = new Mock<IDbModel>(); var actualResult = genericAsyncService.Add(validItemToAdd.Object); Assert.That(actualResult, Is.SameAs(validItemToAdd.Object)); } } }
42.854701
130
0.699043
[ "MIT" ]
army-of-two/when-its-done
WhenItsDone/Tests/LibTests/WhenItsDone.Services.Tests/AbstractionTests/GenericAsyncServiceTests/Add_Should.cs
5,016
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: EntityRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type Windows81WifiImportConfigurationRequest. /// </summary> public partial class Windows81WifiImportConfigurationRequest : BaseRequest, IWindows81WifiImportConfigurationRequest { /// <summary> /// Constructs a new Windows81WifiImportConfigurationRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public Windows81WifiImportConfigurationRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified Windows81WifiImportConfiguration using POST. /// </summary> /// <param name="windows81WifiImportConfigurationToCreate">The Windows81WifiImportConfiguration to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created Windows81WifiImportConfiguration.</returns> public async System.Threading.Tasks.Task<Windows81WifiImportConfiguration> CreateAsync(Windows81WifiImportConfiguration windows81WifiImportConfigurationToCreate, CancellationToken cancellationToken = default) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.Method = HttpMethods.POST; var newEntity = await this.SendAsync<Windows81WifiImportConfiguration>(windows81WifiImportConfigurationToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Creates the specified Windows81WifiImportConfiguration using POST and returns a <see cref="GraphResponse{Windows81WifiImportConfiguration}"/> object. /// </summary> /// <param name="windows81WifiImportConfigurationToCreate">The Windows81WifiImportConfiguration to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The <see cref="GraphResponse{Windows81WifiImportConfiguration}"/> object of the request.</returns> public System.Threading.Tasks.Task<GraphResponse<Windows81WifiImportConfiguration>> CreateResponseAsync(Windows81WifiImportConfiguration windows81WifiImportConfigurationToCreate, CancellationToken cancellationToken = default) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.Method = HttpMethods.POST; return this.SendAsyncWithGraphResponse<Windows81WifiImportConfiguration>(windows81WifiImportConfigurationToCreate, cancellationToken); } /// <summary> /// Deletes the specified Windows81WifiImportConfiguration. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken = default) { this.Method = HttpMethods.DELETE; await this.SendAsync<Windows81WifiImportConfiguration>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Deletes the specified Windows81WifiImportConfiguration and returns a <see cref="GraphResponse"/> object. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task of <see cref="GraphResponse"/> to await.</returns> public System.Threading.Tasks.Task<GraphResponse> DeleteResponseAsync(CancellationToken cancellationToken = default) { this.Method = HttpMethods.DELETE; return this.SendAsyncWithGraphResponse(null, cancellationToken); } /// <summary> /// Gets the specified Windows81WifiImportConfiguration. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The Windows81WifiImportConfiguration.</returns> public async System.Threading.Tasks.Task<Windows81WifiImportConfiguration> GetAsync(CancellationToken cancellationToken = default) { this.Method = HttpMethods.GET; var retrievedEntity = await this.SendAsync<Windows81WifiImportConfiguration>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Gets the specified Windows81WifiImportConfiguration and returns a <see cref="GraphResponse{Windows81WifiImportConfiguration}"/> object. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The <see cref="GraphResponse{Windows81WifiImportConfiguration}"/> object of the request.</returns> public System.Threading.Tasks.Task<GraphResponse<Windows81WifiImportConfiguration>> GetResponseAsync(CancellationToken cancellationToken = default) { this.Method = HttpMethods.GET; return this.SendAsyncWithGraphResponse<Windows81WifiImportConfiguration>(null, cancellationToken); } /// <summary> /// Updates the specified Windows81WifiImportConfiguration using PATCH. /// </summary> /// <param name="windows81WifiImportConfigurationToUpdate">The Windows81WifiImportConfiguration to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <exception cref="ClientException">Thrown when an object returned in a response is used for updating an object in Microsoft Graph.</exception> /// <returns>The updated Windows81WifiImportConfiguration.</returns> public async System.Threading.Tasks.Task<Windows81WifiImportConfiguration> UpdateAsync(Windows81WifiImportConfiguration windows81WifiImportConfigurationToUpdate, CancellationToken cancellationToken = default) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.Method = HttpMethods.PATCH; var updatedEntity = await this.SendAsync<Windows81WifiImportConfiguration>(windows81WifiImportConfigurationToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Updates the specified Windows81WifiImportConfiguration using PATCH and returns a <see cref="GraphResponse{Windows81WifiImportConfiguration}"/> object. /// </summary> /// <param name="windows81WifiImportConfigurationToUpdate">The Windows81WifiImportConfiguration to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <exception cref="ClientException">Thrown when an object returned in a response is used for updating an object in Microsoft Graph.</exception> /// <returns>The <see cref="GraphResponse{Windows81WifiImportConfiguration}"/> object of the request.</returns> public System.Threading.Tasks.Task<GraphResponse<Windows81WifiImportConfiguration>> UpdateResponseAsync(Windows81WifiImportConfiguration windows81WifiImportConfigurationToUpdate, CancellationToken cancellationToken = default) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.Method = HttpMethods.PATCH; return this.SendAsyncWithGraphResponse<Windows81WifiImportConfiguration>(windows81WifiImportConfigurationToUpdate, cancellationToken); } /// <summary> /// Updates the specified Windows81WifiImportConfiguration using PUT. /// </summary> /// <param name="windows81WifiImportConfigurationToUpdate">The Windows81WifiImportConfiguration object to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task<Windows81WifiImportConfiguration> PutAsync(Windows81WifiImportConfiguration windows81WifiImportConfigurationToUpdate, CancellationToken cancellationToken = default) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.Method = HttpMethods.PUT; var updatedEntity = await this.SendAsync<Windows81WifiImportConfiguration>(windows81WifiImportConfigurationToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Updates the specified Windows81WifiImportConfiguration using PUT and returns a <see cref="GraphResponse{Windows81WifiImportConfiguration}"/> object. /// </summary> /// <param name="windows81WifiImportConfigurationToUpdate">The Windows81WifiImportConfiguration object to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await of <see cref="GraphResponse{Windows81WifiImportConfiguration}"/>.</returns> public System.Threading.Tasks.Task<GraphResponse<Windows81WifiImportConfiguration>> PutResponseAsync(Windows81WifiImportConfiguration windows81WifiImportConfigurationToUpdate, CancellationToken cancellationToken = default) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.Method = HttpMethods.PUT; return this.SendAsyncWithGraphResponse<Windows81WifiImportConfiguration>(windows81WifiImportConfigurationToUpdate, cancellationToken); } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IWindows81WifiImportConfigurationRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IWindows81WifiImportConfigurationRequest Expand(Expression<Func<Windows81WifiImportConfiguration, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IWindows81WifiImportConfigurationRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IWindows81WifiImportConfigurationRequest Select(Expression<Func<Windows81WifiImportConfiguration, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="windows81WifiImportConfigurationToInitialize">The <see cref="Windows81WifiImportConfiguration"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(Windows81WifiImportConfiguration windows81WifiImportConfigurationToInitialize) { } } }
56.38
233
0.683079
[ "MIT" ]
ScriptBox99/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/requests/Windows81WifiImportConfigurationRequest.cs
14,095
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Buffers; using System.Diagnostics; using System.IO; using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; using System.Threading; using System.Threading.Tasks; namespace System.Net.WebSockets { /// <summary>A managed implementation of a web socket that sends and receives data via a <see cref="Stream"/>.</summary> /// <remarks> /// Thread-safety: /// - It's acceptable to call ReceiveAsync and SendAsync in parallel. One of each may run concurrently. /// - It's acceptable to have a pending ReceiveAsync while CloseOutputAsync or CloseAsync is called. /// - Attempting to invoke any other operations in parallel may corrupt the instance. Attempting to invoke /// a send operation while another is in progress or a receive operation while another is in progress will /// result in an exception. /// </remarks> internal sealed partial class ManagedWebSocket : WebSocket { /// <summary>Creates a <see cref="ManagedWebSocket"/> from a <see cref="Stream"/> connected to a websocket endpoint.</summary> /// <param name="stream">The connected Stream.</param> /// <param name="isServer">true if this is the server-side of the connection; false if this is the client-side of the connection.</param> /// <param name="subprotocol">The agreed upon subprotocol for the connection.</param> /// <param name="keepAliveInterval">The interval to use for keep-alive pings.</param> /// <returns>The created <see cref="ManagedWebSocket"/> instance.</returns> public static ManagedWebSocket CreateFromConnectedStream( Stream stream, bool isServer, string subprotocol, TimeSpan keepAliveInterval) { return new ManagedWebSocket(stream, isServer, subprotocol, keepAliveInterval); } /// <summary>Thread-safe random number generator used to generate masks for each send.</summary> private static readonly RandomNumberGenerator s_random = RandomNumberGenerator.Create(); /// <summary>Encoding for the payload of text messages: UTF8 encoding that throws if invalid bytes are discovered, per the RFC.</summary> private static readonly UTF8Encoding s_textEncoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); /// <summary>Valid states to be in when calling SendAsync.</summary> private static readonly WebSocketState[] s_validSendStates = { WebSocketState.Open, WebSocketState.CloseReceived }; /// <summary>Valid states to be in when calling ReceiveAsync.</summary> private static readonly WebSocketState[] s_validReceiveStates = { WebSocketState.Open, WebSocketState.CloseSent }; /// <summary>Valid states to be in when calling CloseOutputAsync.</summary> private static readonly WebSocketState[] s_validCloseOutputStates = { WebSocketState.Open, WebSocketState.CloseReceived }; /// <summary>Valid states to be in when calling CloseAsync.</summary> private static readonly WebSocketState[] s_validCloseStates = { WebSocketState.Open, WebSocketState.CloseReceived, WebSocketState.CloseSent }; /// <summary>Successfully completed task representing a close message.</summary> private static readonly Task<WebSocketReceiveResult> s_cachedCloseTask = Task.FromResult(new WebSocketReceiveResult(0, WebSocketMessageType.Close, true)); /// <summary>The maximum size in bytes of a message frame header that includes mask bytes.</summary> internal const int MaxMessageHeaderLength = 14; /// <summary>The maximum size of a control message payload.</summary> private const int MaxControlPayloadLength = 125; /// <summary>Length of the mask XOR'd with the payload data.</summary> private const int MaskLength = 4; /// <summary>The stream used to communicate with the remote server.</summary> private readonly Stream _stream; /// <summary> /// true if this is the server-side of the connection; false if it's client. /// This impacts masking behavior: clients always mask payloads they send and /// expect to always receive unmasked payloads, whereas servers always send /// unmasked payloads and expect to always receive masked payloads. /// </summary> private readonly bool _isServer = false; /// <summary>The agreed upon subprotocol with the server.</summary> private readonly string _subprotocol; /// <summary>Timer used to send periodic pings to the server, at the interval specified</summary> private readonly Timer _keepAliveTimer; /// <summary>CancellationTokenSource used to abort all current and future operations when anything is canceled or any error occurs.</summary> private readonly CancellationTokenSource _abortSource = new CancellationTokenSource(); /// <summary>Buffer used for reading data from the network.</summary> private Memory<byte> _receiveBuffer; /// <summary> /// Tracks the state of the validity of the UTF8 encoding of text payloads. Text may be split across fragments. /// </summary> private readonly Utf8MessageState _utf8TextState = new Utf8MessageState(); /// <summary> /// Semaphore used to ensure that calls to SendFrameAsync don't run concurrently. /// </summary> private readonly SemaphoreSlim _sendFrameAsyncLock = new SemaphoreSlim(1, 1); // We maintain the current WebSocketState in _state. However, we separately maintain _sentCloseFrame and _receivedCloseFrame // as there isn't a strict ordering between CloseSent and CloseReceived. If we receive a close frame from the server, we need to // transition to CloseReceived even if we're currently in CloseSent, and if we send a close frame, we need to transition to // CloseSent even if we're currently in CloseReceived. /// <summary>The current state of the web socket in the protocol.</summary> private WebSocketState _state = WebSocketState.Open; /// <summary>true if Dispose has been called; otherwise, false.</summary> private bool _disposed; /// <summary>Whether we've ever sent a close frame.</summary> private bool _sentCloseFrame; /// <summary>Whether we've ever received a close frame.</summary> private bool _receivedCloseFrame; /// <summary>The reason for the close, as sent by the server, or null if not yet closed.</summary> private WebSocketCloseStatus? _closeStatus = null; /// <summary>A description of the close reason as sent by the server, or null if not yet closed.</summary> private string _closeStatusDescription = null; /// <summary> /// The last header received in a ReceiveAsync. If ReceiveAsync got a header but then /// returned fewer bytes than was indicated in the header, subsequent ReceiveAsync calls /// will use the data from the header to construct the subsequent receive results, and /// the payload length in this header will be decremented to indicate the number of bytes /// remaining to be received for that header. As a result, between fragments, the payload /// length in this header should be 0. /// </summary> private MessageHeader _lastReceiveHeader = new MessageHeader { Opcode = MessageOpcode.Text, Fin = true }; /// <summary>The offset of the next available byte in the _receiveBuffer.</summary> private int _receiveBufferOffset = 0; /// <summary>The number of bytes available in the _receiveBuffer.</summary> private int _receiveBufferCount = 0; /// <summary> /// When dealing with partially read fragments of binary/text messages, a mask previously received may still /// apply, and the first new byte received may not correspond to the 0th position in the mask. This value is /// the next offset into the mask that should be applied. /// </summary> private int _receivedMaskOffsetOffset = 0; /// <summary> /// Temporary send buffer. This should be released back to the ArrayPool once it's /// no longer needed for the current send operation. It is stored as an instance /// field to minimize needing to pass it around and to avoid it becoming a field on /// various async state machine objects. /// </summary> private byte[] _sendBuffer; /// <summary> /// Whether the last SendAsync had endOfMessage==false. We need to track this so that we /// can send the subsequent message with a continuation opcode if the last message was a fragment. /// </summary> private bool _lastSendWasFragment; /// <summary> /// The task returned from the last ReceiveAsync(ArraySegment, ...) operation to not complete synchronously. /// If this is not null and not completed when a subsequent ReceiveAsync is issued, an exception occurs. /// </summary> private Task _lastReceiveAsync = Task.CompletedTask; /// <summary>Lock used to protect update and check-and-update operations on _state.</summary> private object StateUpdateLock => _abortSource; /// <summary> /// We need to coordinate between receives and close operations happening concurrently, as a ReceiveAsync may /// be pending while a Close{Output}Async is issued, which itself needs to loop until a close frame is received. /// As such, we need thread-safety in the management of <see cref="_lastReceiveAsync"/>. /// </summary> private object ReceiveAsyncLock => _utf8TextState; // some object, as we're simply lock'ing on it /// <summary>Initializes the websocket.</summary> /// <param name="stream">The connected Stream.</param> /// <param name="isServer">true if this is the server-side of the connection; false if this is the client-side of the connection.</param> /// <param name="subprotocol">The agreed upon subprotocol for the connection.</param> /// <param name="keepAliveInterval">The interval to use for keep-alive pings.</param> private ManagedWebSocket(Stream stream, bool isServer, string subprotocol, TimeSpan keepAliveInterval) { Debug.Assert(StateUpdateLock != null, $"Expected {nameof(StateUpdateLock)} to be non-null"); Debug.Assert(ReceiveAsyncLock != null, $"Expected {nameof(ReceiveAsyncLock)} to be non-null"); Debug.Assert(StateUpdateLock != ReceiveAsyncLock, "Locks should be different objects"); Debug.Assert(stream != null, $"Expected non-null stream"); Debug.Assert(stream.CanRead, $"Expected readable stream"); Debug.Assert(stream.CanWrite, $"Expected writeable stream"); Debug.Assert(keepAliveInterval == Timeout.InfiniteTimeSpan || keepAliveInterval >= TimeSpan.Zero, $"Invalid keepalive interval: {keepAliveInterval}"); _stream = stream; _isServer = isServer; _subprotocol = subprotocol; // Create a buffer just large enough to handle received packet headers (at most 14 bytes) and // control payloads (at most 125 bytes). Message payloads are read directly into the buffer // supplied to ReceiveAsync. const int ReceiveBufferMinLength = MaxControlPayloadLength; _receiveBuffer = new byte[ReceiveBufferMinLength]; // Set up the abort source so that if it's triggered, we transition the instance appropriately. _abortSource.Token.Register(s => { var thisRef = (ManagedWebSocket)s; lock (thisRef.StateUpdateLock) { WebSocketState state = thisRef._state; if (state != WebSocketState.Closed && state != WebSocketState.Aborted) { thisRef._state = state != WebSocketState.None && state != WebSocketState.Connecting ? WebSocketState.Aborted : WebSocketState.Closed; } } }, this); // Now that we're opened, initiate the keep alive timer to send periodic pings if (keepAliveInterval > TimeSpan.Zero) { _keepAliveTimer = new Timer(s => ((ManagedWebSocket)s).SendKeepAliveFrameAsync(), this, keepAliveInterval, keepAliveInterval); } } public override void Dispose() { lock (StateUpdateLock) { DisposeCore(); } } private void DisposeCore() { Debug.Assert(Monitor.IsEntered(StateUpdateLock), $"Expected {nameof(StateUpdateLock)} to be held"); if (!_disposed) { _disposed = true; _keepAliveTimer?.Dispose(); _stream?.Dispose(); if (_state < WebSocketState.Aborted) { _state = WebSocketState.Closed; } } } public override WebSocketCloseStatus? CloseStatus => _closeStatus; public override string CloseStatusDescription => _closeStatusDescription; public override WebSocketState State => _state; public override string SubProtocol => _subprotocol; public override Task SendAsync(ArraySegment<byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken) { if (messageType != WebSocketMessageType.Text && messageType != WebSocketMessageType.Binary) { throw new ArgumentException(SR.Format( SR.net_WebSockets_Argument_InvalidMessageType, nameof(WebSocketMessageType.Close), nameof(SendAsync), nameof(WebSocketMessageType.Binary), nameof(WebSocketMessageType.Text), nameof(CloseOutputAsync)), nameof(messageType)); } WebSocketValidate.ValidateArraySegment(buffer, nameof(buffer)); return SendPrivateAsync((ReadOnlyMemory<byte>)buffer, messageType, endOfMessage, cancellationToken).AsTask(); } private ValueTask SendPrivateAsync(ReadOnlyMemory<byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken) { if (messageType != WebSocketMessageType.Text && messageType != WebSocketMessageType.Binary) { throw new ArgumentException(SR.Format( SR.net_WebSockets_Argument_InvalidMessageType, nameof(WebSocketMessageType.Close), nameof(SendAsync), nameof(WebSocketMessageType.Binary), nameof(WebSocketMessageType.Text), nameof(CloseOutputAsync)), nameof(messageType)); } try { WebSocketValidate.ThrowIfInvalidState(_state, _disposed, s_validSendStates); } catch (Exception exc) { return new ValueTask(Task.FromException(exc)); } MessageOpcode opcode = _lastSendWasFragment ? MessageOpcode.Continuation : messageType == WebSocketMessageType.Binary ? MessageOpcode.Binary : MessageOpcode.Text; ValueTask t = SendFrameAsync(opcode, endOfMessage, buffer, cancellationToken); _lastSendWasFragment = !endOfMessage; return t; } public override Task<WebSocketReceiveResult> ReceiveAsync(ArraySegment<byte> buffer, CancellationToken cancellationToken) { WebSocketValidate.ValidateArraySegment(buffer, nameof(buffer)); try { WebSocketValidate.ThrowIfInvalidState(_state, _disposed, s_validReceiveStates); Debug.Assert(!Monitor.IsEntered(StateUpdateLock), $"{nameof(StateUpdateLock)} must never be held when acquiring {nameof(ReceiveAsyncLock)}"); lock (ReceiveAsyncLock) // synchronize with receives in CloseAsync { ThrowIfOperationInProgress(_lastReceiveAsync.IsCompleted); Task<WebSocketReceiveResult> t = ReceiveAsyncPrivate<WebSocketReceiveResultGetter,WebSocketReceiveResult>(buffer, cancellationToken).AsTask(); _lastReceiveAsync = t; return t; } } catch (Exception exc) { return Task.FromException<WebSocketReceiveResult>(exc); } } public override Task CloseAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken) { WebSocketValidate.ValidateCloseStatus(closeStatus, statusDescription); try { WebSocketValidate.ThrowIfInvalidState(_state, _disposed, s_validCloseStates); } catch (Exception exc) { return Task.FromException(exc); } return CloseAsyncPrivate(closeStatus, statusDescription, cancellationToken); } public override Task CloseOutputAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken) { WebSocketValidate.ValidateCloseStatus(closeStatus, statusDescription); try { WebSocketValidate.ThrowIfInvalidState(_state, _disposed, s_validCloseOutputStates); } catch (Exception exc) { return Task.FromException(exc); } return SendCloseFrameAsync(closeStatus, statusDescription, cancellationToken); } public override void Abort() { _abortSource.Cancel(); Dispose(); // forcibly tear down connection } /// <summary>Sends a websocket frame to the network.</summary> /// <param name="opcode">The opcode for the message.</param> /// <param name="endOfMessage">The value of the FIN bit for the message.</param> /// <param name="payloadBuffer">The buffer containing the payload data fro the message.</param> /// <param name="cancellationToken">The CancellationToken to use to cancel the websocket.</param> private ValueTask SendFrameAsync(MessageOpcode opcode, bool endOfMessage, ReadOnlyMemory<byte> payloadBuffer, CancellationToken cancellationToken) { // If a cancelable cancellation token was provided, that would require registering with it, which means more state we have to // pass around (the CancellationTokenRegistration), so if it is cancelable, just immediately go to the fallback path. // Similarly, it should be rare that there are multiple outstanding calls to SendFrameAsync, but if there are, again // fall back to the fallback path. return cancellationToken.CanBeCanceled || !_sendFrameAsyncLock.Wait(0) ? new ValueTask(SendFrameFallbackAsync(opcode, endOfMessage, payloadBuffer, cancellationToken)) : SendFrameLockAcquiredNonCancelableAsync(opcode, endOfMessage, payloadBuffer); } /// <summary>Sends a websocket frame to the network. The caller must hold the sending lock.</summary> /// <param name="opcode">The opcode for the message.</param> /// <param name="endOfMessage">The value of the FIN bit for the message.</param> /// <param name="payloadBuffer">The buffer containing the payload data fro the message.</param> private ValueTask SendFrameLockAcquiredNonCancelableAsync(MessageOpcode opcode, bool endOfMessage, ReadOnlyMemory<byte> payloadBuffer) { Debug.Assert(_sendFrameAsyncLock.CurrentCount == 0, "Caller should hold the _sendFrameAsyncLock"); // If we get here, the cancellation token is not cancelable so we don't have to worry about it, // and we own the semaphore, so we don't need to asynchronously wait for it. ValueTask writeTask = default; bool releaseSemaphoreAndSendBuffer = true; try { // Write the payload synchronously to the buffer, then write that buffer out to the network. int sendBytes = WriteFrameToSendBuffer(opcode, endOfMessage, payloadBuffer.Span); writeTask = _stream.WriteAsync(new ReadOnlyMemory<byte>(_sendBuffer, 0, sendBytes)); // If the operation happens to complete synchronously (or, more specifically, by // the time we get from the previous line to here), release the semaphore, return // the task, and we're done. if (writeTask.IsCompleted) { return writeTask; } // Up until this point, if an exception occurred (such as when accessing _stream or when // calling GetResult), we want to release the semaphore and the send buffer. After this point, // both need to be held until writeTask completes. releaseSemaphoreAndSendBuffer = false; } catch (Exception exc) { return new ValueTask(Task.FromException( exc is OperationCanceledException ? exc : _state == WebSocketState.Aborted ? CreateOperationCanceledException(exc) : new WebSocketException(WebSocketError.ConnectionClosedPrematurely, exc))); } finally { if (releaseSemaphoreAndSendBuffer) { _sendFrameAsyncLock.Release(); ReleaseSendBuffer(); } } return new ValueTask(WaitForWriteTaskAsync(writeTask)); } private async Task WaitForWriteTaskAsync(ValueTask writeTask) { try { await writeTask.ConfigureAwait(false); } catch (Exception exc) when (!(exc is OperationCanceledException)) { throw _state == WebSocketState.Aborted ? CreateOperationCanceledException(exc) : new WebSocketException(WebSocketError.ConnectionClosedPrematurely, exc); } finally { _sendFrameAsyncLock.Release(); ReleaseSendBuffer(); } } private async Task SendFrameFallbackAsync(MessageOpcode opcode, bool endOfMessage, ReadOnlyMemory<byte> payloadBuffer, CancellationToken cancellationToken) { await _sendFrameAsyncLock.WaitAsync().ConfigureAwait(false); try { int sendBytes = WriteFrameToSendBuffer(opcode, endOfMessage, payloadBuffer.Span); using (cancellationToken.Register(s => ((ManagedWebSocket)s).Abort(), this)) { await _stream.WriteAsync(new ReadOnlyMemory<byte>(_sendBuffer, 0, sendBytes), default).ConfigureAwait(false); } } catch (Exception exc) when (!(exc is OperationCanceledException)) { throw _state == WebSocketState.Aborted ? CreateOperationCanceledException(exc, cancellationToken) : new WebSocketException(WebSocketError.ConnectionClosedPrematurely, exc); } finally { _sendFrameAsyncLock.Release(); ReleaseSendBuffer(); } } /// <summary>Writes a frame into the send buffer, which can then be sent over the network.</summary> private int WriteFrameToSendBuffer(MessageOpcode opcode, bool endOfMessage, ReadOnlySpan<byte> payloadBuffer) { // Ensure we have a _sendBuffer. AllocateSendBuffer(payloadBuffer.Length + MaxMessageHeaderLength); // Write the message header data to the buffer. int headerLength; int? maskOffset = null; if (_isServer) { // The server doesn't send a mask, so the mask offset returned by WriteHeader // is actually the end of the header. headerLength = WriteHeader(opcode, _sendBuffer, payloadBuffer, endOfMessage, useMask: false); } else { // We need to know where the mask starts so that we can use the mask to manipulate the payload data, // and we need to know the total length for sending it on the wire. maskOffset = WriteHeader(opcode, _sendBuffer, payloadBuffer, endOfMessage, useMask: true); headerLength = maskOffset.GetValueOrDefault() + MaskLength; } // Write the payload if (payloadBuffer.Length > 0) { payloadBuffer.CopyTo(new Span<byte>(_sendBuffer, headerLength, payloadBuffer.Length)); // If we added a mask to the header, XOR the payload with the mask. We do the manipulation in the send buffer so as to avoid // changing the data in the caller-supplied payload buffer. if (maskOffset.HasValue) { ApplyMask(new Span<byte>(_sendBuffer, headerLength, payloadBuffer.Length), _sendBuffer, maskOffset.Value, 0); } } // Return the number of bytes in the send buffer return headerLength + payloadBuffer.Length; } private void SendKeepAliveFrameAsync() { bool acquiredLock = _sendFrameAsyncLock.Wait(0); if (acquiredLock) { // This exists purely to keep the connection alive; don't wait for the result, and ignore any failures. // The call will handle releasing the lock. ValueTask t = SendFrameLockAcquiredNonCancelableAsync(MessageOpcode.Ping, true, Memory<byte>.Empty); if (t.IsCompletedSuccessfully) { t.GetAwaiter().GetResult(); } else { // "Observe" any exception, ignoring it to prevent the unobserved exception event from being raised. t.AsTask().ContinueWith(p => { Exception ignored = p.Exception; }, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } } else { // If the lock is already held, something is already getting sent, // so there's no need to send a keep-alive ping. } } private static int WriteHeader(MessageOpcode opcode, byte[] sendBuffer, ReadOnlySpan<byte> payload, bool endOfMessage, bool useMask) { // Client header format: // 1 bit - FIN - 1 if this is the final fragment in the message (it could be the only fragment), otherwise 0 // 1 bit - RSV1 - Reserved - 0 // 1 bit - RSV2 - Reserved - 0 // 1 bit - RSV3 - Reserved - 0 // 4 bits - Opcode - How to interpret the payload // - 0x0 - continuation // - 0x1 - text // - 0x2 - binary // - 0x8 - connection close // - 0x9 - ping // - 0xA - pong // - (0x3 to 0x7, 0xB-0xF - reserved) // 1 bit - Masked - 1 if the payload is masked, 0 if it's not. Must be 1 for the client // 7 bits, 7+16 bits, or 7+64 bits - Payload length // - For length 0 through 125, 7 bits storing the length // - For lengths 126 through 2^16, 7 bits storing the value 126, followed by 16 bits storing the length // - For lengths 2^16+1 through 2^64, 7 bits storing the value 127, followed by 64 bytes storing the length // 0 or 4 bytes - Mask, if Masked is 1 - random value XOR'd with each 4 bytes of the payload, round-robin // Length bytes - Payload data Debug.Assert(sendBuffer.Length >= MaxMessageHeaderLength, $"Expected sendBuffer to be at least {MaxMessageHeaderLength}, got {sendBuffer.Length}"); sendBuffer[0] = (byte)opcode; // 4 bits for the opcode if (endOfMessage) { sendBuffer[0] |= 0x80; // 1 bit for FIN } // Store the payload length. int maskOffset; if (payload.Length <= 125) { sendBuffer[1] = (byte)payload.Length; maskOffset = 2; // no additional payload length } else if (payload.Length <= ushort.MaxValue) { sendBuffer[1] = 126; sendBuffer[2] = (byte)(payload.Length / 256); sendBuffer[3] = unchecked((byte)payload.Length); maskOffset = 2 + sizeof(ushort); // additional 2 bytes for 16-bit length } else { sendBuffer[1] = 127; int length = payload.Length; for (int i = 9; i >= 2; i--) { sendBuffer[i] = unchecked((byte)length); length = length / 256; } maskOffset = 2 + sizeof(ulong); // additional 8 bytes for 64-bit length } if (useMask) { // Generate the mask. sendBuffer[1] |= 0x80; WriteRandomMask(sendBuffer, maskOffset); } // Return the position of the mask. return maskOffset; } /// <summary>Writes a 4-byte random mask to the specified buffer at the specified offset.</summary> /// <param name="buffer">The buffer to which to write the mask.</param> /// <param name="offset">The offset into the buffer at which to write the mask.</param> private static void WriteRandomMask(byte[] buffer, int offset) => s_random.GetBytes(buffer, offset, MaskLength); /// <summary> /// Receive the next text, binary, continuation, or close message, returning information about it and /// writing its payload into the supplied buffer. Other control messages may be consumed and processed /// as part of this operation, but data about them will not be returned. /// </summary> /// <param name="payloadBuffer">The buffer into which payload data should be written.</param> /// <param name="cancellationToken">The CancellationToken used to cancel the websocket.</param> /// <param name="resultGetter">Used to get the result. Allows the same method to be used with both <see cref="WebSocketReceiveResult"/> and <see cref="ValueWebSocketReceiveResult"/>.</param> /// <returns>Information about the received message.</returns> private async ValueTask<TWebSocketReceiveResult> ReceiveAsyncPrivate<TWebSocketReceiveResultGetter, TWebSocketReceiveResult>( Memory<byte> payloadBuffer, CancellationToken cancellationToken, TWebSocketReceiveResultGetter resultGetter = default) where TWebSocketReceiveResultGetter : struct, IWebSocketReceiveResultGetter<TWebSocketReceiveResult> // constrained to avoid boxing and enable inlining { // This is a long method. While splitting it up into pieces would arguably help with readability, doing so would // also result in more allocations, as each async method that yields ends up with multiple allocations. The impact // of those allocations is amortized across all of the awaits in the method, and since we generally expect a receive // operation to require at most a single yield (while waiting for data to arrive), it's more efficient to have // everything in the one method. We do separate out pieces for handling close and ping/pong messages, as we expect // those to be much less frequent (e.g. we should only get one close per websocket), and thus we can afford to pay // a bit more for readability and maintainability. CancellationTokenRegistration registration = cancellationToken.Register(s => ((ManagedWebSocket)s).Abort(), this); try { while (true) // in case we get control frames that should be ignored from the user's perspective { // Get the last received header. If its payload length is non-zero, that means we previously // received the header but were only able to read a part of the fragment, so we should skip // reading another header and just proceed to use that same header and read more data associated // with it. If instead its payload length is zero, then we've completed the processing of // thta message, and we should read the next header. MessageHeader header = _lastReceiveHeader; if (header.PayloadLength == 0) { if (_receiveBufferCount < (_isServer ? (MaxMessageHeaderLength - MaskLength) : MaxMessageHeaderLength)) { // Make sure we have the first two bytes, which includes the start of the payload length. if (_receiveBufferCount < 2) { await EnsureBufferContainsAsync(2, throwOnPrematureClosure: true).ConfigureAwait(false); } // Then make sure we have the full header based on the payload length. // If this is the server, we also need room for the received mask. long payloadLength = _receiveBuffer.Span[_receiveBufferOffset + 1] & 0x7F; if (_isServer || payloadLength > 125) { int minNeeded = 2 + (_isServer ? MaskLength : 0) + (payloadLength <= 125 ? 0 : payloadLength == 126 ? sizeof(ushort) : sizeof(ulong)); // additional 2 or 8 bytes for 16-bit or 64-bit length await EnsureBufferContainsAsync(minNeeded).ConfigureAwait(false); } } if (!TryParseMessageHeaderFromReceiveBuffer(out header)) { await CloseWithReceiveErrorAndThrowAsync(WebSocketCloseStatus.ProtocolError, WebSocketError.Faulted).ConfigureAwait(false); } _receivedMaskOffsetOffset = 0; } // If the header represents a ping or a pong, it's a control message meant // to be transparent to the user, so handle it and then loop around to read again. // Alternatively, if it's a close message, handle it and exit. if (header.Opcode == MessageOpcode.Ping || header.Opcode == MessageOpcode.Pong) { await HandleReceivedPingPongAsync(header).ConfigureAwait(false); continue; } else if (header.Opcode == MessageOpcode.Close) { await HandleReceivedCloseAsync(header).ConfigureAwait(false); return resultGetter.GetResult(0, WebSocketMessageType.Close, true, _closeStatus, _closeStatusDescription); } // If this is a continuation, replace the opcode with the one of the message it's continuing if (header.Opcode == MessageOpcode.Continuation) { header.Opcode = _lastReceiveHeader.Opcode; } // The message should now be a binary or text message. Handle it by reading the payload and returning the contents. Debug.Assert(header.Opcode == MessageOpcode.Binary || header.Opcode == MessageOpcode.Text, $"Unexpected opcode {header.Opcode}"); // If there's no data to read, return an appropriate result. if (header.PayloadLength == 0 || payloadBuffer.Length == 0) { _lastReceiveHeader = header; return resultGetter.GetResult( 0, header.Opcode == MessageOpcode.Text ? WebSocketMessageType.Text : WebSocketMessageType.Binary, header.Fin && header.PayloadLength == 0, null, null); } // Otherwise, read as much of the payload as we can efficiently, and upate the header to reflect how much data // remains for future reads. We first need to copy any data that may be lingering in the receive buffer // into the destination; then to minimize ReceiveAsync calls, we want to read as much as we can, stopping // only when we've either read the whole message or when we've filled the payload buffer. // First copy any data lingering in the receive buffer. int totalBytesReceived = 0; if (_receiveBufferCount > 0) { int receiveBufferBytesToCopy = Math.Min(payloadBuffer.Length, (int)Math.Min(header.PayloadLength, _receiveBufferCount)); Debug.Assert(receiveBufferBytesToCopy > 0); _receiveBuffer.Span.Slice(_receiveBufferOffset, receiveBufferBytesToCopy).CopyTo(payloadBuffer.Span); ConsumeFromBuffer(receiveBufferBytesToCopy); totalBytesReceived += receiveBufferBytesToCopy; Debug.Assert( _receiveBufferCount == 0 || totalBytesReceived == payloadBuffer.Length || totalBytesReceived == header.PayloadLength); } // Then read directly into the payload buffer until we've hit a limit. while (totalBytesReceived < payloadBuffer.Length && totalBytesReceived < header.PayloadLength) { int numBytesRead = await _stream.ReadAsync(payloadBuffer.Slice( totalBytesReceived, (int)Math.Min(payloadBuffer.Length, header.PayloadLength) - totalBytesReceived)).ConfigureAwait(false); if (numBytesRead <= 0) { ThrowIfEOFUnexpected(throwOnPrematureClosure: true); break; } totalBytesReceived += numBytesRead; } if (_isServer) { _receivedMaskOffsetOffset = ApplyMask(payloadBuffer.Span.Slice(0, totalBytesReceived), header.Mask, _receivedMaskOffsetOffset); } header.PayloadLength -= totalBytesReceived; // If this a text message, validate that it contains valid UTF8. if (header.Opcode == MessageOpcode.Text && !TryValidateUtf8(payloadBuffer.Span.Slice(0, totalBytesReceived), header.Fin, _utf8TextState)) { await CloseWithReceiveErrorAndThrowAsync(WebSocketCloseStatus.InvalidPayloadData, WebSocketError.Faulted).ConfigureAwait(false); } _lastReceiveHeader = header; return resultGetter.GetResult( totalBytesReceived, header.Opcode == MessageOpcode.Text ? WebSocketMessageType.Text : WebSocketMessageType.Binary, header.Fin && header.PayloadLength == 0, null, null); } } catch (Exception exc) when (!(exc is OperationCanceledException)) { if (_state == WebSocketState.Aborted) { throw new OperationCanceledException(nameof(WebSocketState.Aborted), exc); } _abortSource.Cancel(); throw new WebSocketException(WebSocketError.ConnectionClosedPrematurely, exc); } finally { registration.Dispose(); } } /// <summary>Processes a received close message.</summary> /// <param name="header">The message header.</param> /// <returns>The received result message.</returns> private async Task HandleReceivedCloseAsync(MessageHeader header) { lock (StateUpdateLock) { _receivedCloseFrame = true; if (_state < WebSocketState.CloseReceived) { _state = WebSocketState.CloseReceived; } } WebSocketCloseStatus closeStatus = WebSocketCloseStatus.NormalClosure; string closeStatusDescription = string.Empty; // Handle any payload by parsing it into the close status and description. if (header.PayloadLength == 1) { // The close payload length can be 0 or >= 2, but not 1. await CloseWithReceiveErrorAndThrowAsync(WebSocketCloseStatus.ProtocolError, WebSocketError.Faulted).ConfigureAwait(false); } else if (header.PayloadLength >= 2) { if (_receiveBufferCount < header.PayloadLength) { await EnsureBufferContainsAsync((int)header.PayloadLength).ConfigureAwait(false); } if (_isServer) { ApplyMask(_receiveBuffer.Span.Slice(_receiveBufferOffset, (int)header.PayloadLength), header.Mask, 0); } closeStatus = (WebSocketCloseStatus)(_receiveBuffer.Span[_receiveBufferOffset] << 8 | _receiveBuffer.Span[_receiveBufferOffset + 1]); if (!IsValidCloseStatus(closeStatus)) { await CloseWithReceiveErrorAndThrowAsync(WebSocketCloseStatus.ProtocolError, WebSocketError.Faulted).ConfigureAwait(false); } if (header.PayloadLength > 2) { try { closeStatusDescription = s_textEncoding.GetString(_receiveBuffer.Span.Slice(_receiveBufferOffset + 2, (int)header.PayloadLength - 2)); } catch (DecoderFallbackException exc) { await CloseWithReceiveErrorAndThrowAsync(WebSocketCloseStatus.ProtocolError, WebSocketError.Faulted, exc).ConfigureAwait(false); } } ConsumeFromBuffer((int)header.PayloadLength); } // Store the close status and description onto the instance. _closeStatus = closeStatus; _closeStatusDescription = closeStatusDescription; if (!_isServer && _sentCloseFrame) { await WaitForServerToCloseConnectionAsync().ConfigureAwait(false); } } /// <summary>Issues a read on the stream to wait for EOF.</summary> private async Task WaitForServerToCloseConnectionAsync() { // Per RFC 6455 7.1.1, try to let the server close the connection. We give it up to a second. // We simply issue a read and don't care what we get back; we could validate that we don't get // additional data, but at this point we're about to close the connection and we're just stalling // to try to get the server to close first. ValueTask<int> finalReadTask = _stream.ReadAsync(_receiveBuffer, default); if (!finalReadTask.IsCompletedSuccessfully) { const int WaitForCloseTimeoutMs = 1_000; // arbitrary amount of time to give the server (same as netfx) using (var finalCts = new CancellationTokenSource(WaitForCloseTimeoutMs)) using (finalCts.Token.Register(s => ((ManagedWebSocket)s).Abort(), this)) { try { await finalReadTask.ConfigureAwait(false); } catch { // Eat any resulting exceptions. We were going to close the connection, anyway. // TODO #24057: Log the exception to NetEventSource. } } } } /// <summary>Processes a received ping or pong message.</summary> /// <param name="header">The message header.</param> private async Task HandleReceivedPingPongAsync(MessageHeader header) { // Consume any (optional) payload associated with the ping/pong. if (header.PayloadLength > 0 && _receiveBufferCount < header.PayloadLength) { await EnsureBufferContainsAsync((int)header.PayloadLength).ConfigureAwait(false); } // If this was a ping, send back a pong response. if (header.Opcode == MessageOpcode.Ping) { if (_isServer) { ApplyMask(_receiveBuffer.Span.Slice(_receiveBufferOffset, (int)header.PayloadLength), header.Mask, 0); } await SendFrameAsync( MessageOpcode.Pong, true, _receiveBuffer.Slice(_receiveBufferOffset, (int)header.PayloadLength), default).ConfigureAwait(false); } // Regardless of whether it was a ping or pong, we no longer need the payload. if (header.PayloadLength > 0) { ConsumeFromBuffer((int)header.PayloadLength); } } /// <summary>Check whether a close status is valid according to the RFC.</summary> /// <param name="closeStatus">The status to validate.</param> /// <returns>true if the status if valid; otherwise, false.</returns> private static bool IsValidCloseStatus(WebSocketCloseStatus closeStatus) { // 0-999: "not used" // 1000-2999: reserved for the protocol; we need to check individual codes manually // 3000-3999: reserved for use by higher-level code // 4000-4999: reserved for private use // 5000-: not mentioned in RFC if (closeStatus < (WebSocketCloseStatus)1000 || closeStatus >= (WebSocketCloseStatus)5000) { return false; } if (closeStatus >= (WebSocketCloseStatus)3000) { return true; } switch (closeStatus) // check for the 1000-2999 range known codes { case WebSocketCloseStatus.EndpointUnavailable: case WebSocketCloseStatus.InternalServerError: case WebSocketCloseStatus.InvalidMessageType: case WebSocketCloseStatus.InvalidPayloadData: case WebSocketCloseStatus.MandatoryExtension: case WebSocketCloseStatus.MessageTooBig: case WebSocketCloseStatus.NormalClosure: case WebSocketCloseStatus.PolicyViolation: case WebSocketCloseStatus.ProtocolError: return true; default: return false; } } /// <summary>Send a close message to the server and throw an exception, in response to getting bad data from the server.</summary> /// <param name="closeStatus">The close status code to use.</param> /// <param name="error">The error reason.</param> /// <param name="innerException">An optional inner exception to include in the thrown exception.</param> private async Task CloseWithReceiveErrorAndThrowAsync( WebSocketCloseStatus closeStatus, WebSocketError error, Exception innerException = null) { // Close the connection if it hasn't already been closed if (!_sentCloseFrame) { await CloseOutputAsync(closeStatus, string.Empty, default).ConfigureAwait(false); } // Dump our receive buffer; we're in a bad state to do any further processing _receiveBufferCount = 0; // Let the caller know we've failed throw new WebSocketException(error, innerException); } /// <summary>Parses a message header from the buffer. This assumes the header is in the buffer.</summary> /// <param name="resultHeader">The read header.</param> /// <returns>true if a header was read; false if the header was invalid.</returns> private bool TryParseMessageHeaderFromReceiveBuffer(out MessageHeader resultHeader) { Debug.Assert(_receiveBufferCount >= 2, $"Expected to at least have the first two bytes of the header."); var header = new MessageHeader(); Span<byte> receiveBufferSpan = _receiveBuffer.Span; header.Fin = (receiveBufferSpan[_receiveBufferOffset] & 0x80) != 0; bool reservedSet = (receiveBufferSpan[_receiveBufferOffset] & 0x70) != 0; header.Opcode = (MessageOpcode)(receiveBufferSpan[_receiveBufferOffset] & 0xF); bool masked = (receiveBufferSpan[_receiveBufferOffset + 1] & 0x80) != 0; header.PayloadLength = receiveBufferSpan[_receiveBufferOffset + 1] & 0x7F; ConsumeFromBuffer(2); // Read the remainder of the payload length, if necessary if (header.PayloadLength == 126) { Debug.Assert(_receiveBufferCount >= 2, $"Expected to have two bytes for the payload length."); header.PayloadLength = (receiveBufferSpan[_receiveBufferOffset] << 8) | receiveBufferSpan[_receiveBufferOffset + 1]; ConsumeFromBuffer(2); } else if (header.PayloadLength == 127) { Debug.Assert(_receiveBufferCount >= 8, $"Expected to have eight bytes for the payload length."); header.PayloadLength = 0; for (int i = 0; i < 8; i++) { header.PayloadLength = (header.PayloadLength << 8) | receiveBufferSpan[_receiveBufferOffset + i]; } ConsumeFromBuffer(8); } bool shouldFail = reservedSet; if (masked) { if (!_isServer) { shouldFail = true; } header.Mask = CombineMaskBytes(receiveBufferSpan, _receiveBufferOffset); // Consume the mask bytes ConsumeFromBuffer(4); } // Do basic validation of the header switch (header.Opcode) { case MessageOpcode.Continuation: if (_lastReceiveHeader.Fin) { // Can't continue from a final message shouldFail = true; } break; case MessageOpcode.Binary: case MessageOpcode.Text: if (!_lastReceiveHeader.Fin) { // Must continue from a non-final message shouldFail = true; } break; case MessageOpcode.Close: case MessageOpcode.Ping: case MessageOpcode.Pong: if (header.PayloadLength > MaxControlPayloadLength || !header.Fin) { // Invalid control messgae shouldFail = true; } break; default: // Unknown opcode shouldFail = true; break; } // Return the read header resultHeader = header; return !shouldFail; } /// <summary>Send a close message, then receive until we get a close response message.</summary> /// <param name="closeStatus">The close status to send.</param> /// <param name="statusDescription">The close status description to send.</param> /// <param name="cancellationToken">The CancellationToken to use to cancel the websocket.</param> private async Task CloseAsyncPrivate(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken) { // Send the close message. Skip sending a close frame if we're currently in a CloseSent state, // for example having just done a CloseOutputAsync. if (!_sentCloseFrame) { await SendCloseFrameAsync(closeStatus, statusDescription, cancellationToken).ConfigureAwait(false); } // We should now either be in a CloseSent case (because we just sent one), or in a CloseReceived state, in case // there was a concurrent receive that ended up handling an immediate close frame response from the server. // Of course it could also be Aborted if something happened concurrently to cause things to blow up. Debug.Assert( State == WebSocketState.CloseSent || State == WebSocketState.CloseReceived || State == WebSocketState.Aborted, $"Unexpected state {State}."); // Wait until we've received a close response byte[] closeBuffer = ArrayPool<byte>.Shared.Rent(MaxMessageHeaderLength + MaxControlPayloadLength); try { while (!_receivedCloseFrame) { Debug.Assert(!Monitor.IsEntered(StateUpdateLock), $"{nameof(StateUpdateLock)} must never be held when acquiring {nameof(ReceiveAsyncLock)}"); Task receiveTask; lock (ReceiveAsyncLock) { // Now that we're holding the ReceiveAsyncLock, double-check that we've not yet received the close frame. // It could have been received between our check above and now due to a concurrent receive completing. if (_receivedCloseFrame) { break; } // We've not yet processed a received close frame, which means we need to wait for a received close to complete. // There may already be one in flight, in which case we want to just wait for that one rather than kicking off // another (we don't support concurrent receive operations). We need to kick off a new receive if either we've // never issued a receive or if the last issued receive completed for reasons other than a close frame. There is // a race condition here, e.g. if there's a in-flight receive that completes after we check, but that's fine: worst // case is we then await it, find that it's not what we need, and try again. receiveTask = _lastReceiveAsync; _lastReceiveAsync = receiveTask = ValidateAndReceiveAsync(receiveTask, closeBuffer, cancellationToken); } // Wait for whatever receive task we have. We'll then loop around again to re-check our state. Debug.Assert(receiveTask != null); await receiveTask.ConfigureAwait(false); } } finally { ArrayPool<byte>.Shared.Return(closeBuffer); } // We're closed. Close the connection and update the status. lock (StateUpdateLock) { DisposeCore(); if (_state < WebSocketState.Closed) { _state = WebSocketState.Closed; } } } /// <summary>Sends a close message to the server.</summary> /// <param name="closeStatus">The close status to send.</param> /// <param name="closeStatusDescription">The close status description to send.</param> /// <param name="cancellationToken">The CancellationToken to use to cancel the websocket.</param> private async Task SendCloseFrameAsync(WebSocketCloseStatus closeStatus, string closeStatusDescription, CancellationToken cancellationToken) { // Close payload is two bytes containing the close status followed by a UTF8-encoding of the status description, if it exists. byte[] buffer = null; try { int count = 2; if (string.IsNullOrEmpty(closeStatusDescription)) { buffer = ArrayPool<byte>.Shared.Rent(count); } else { count += s_textEncoding.GetByteCount(closeStatusDescription); buffer = ArrayPool<byte>.Shared.Rent(count); int encodedLength = s_textEncoding.GetBytes(closeStatusDescription, 0, closeStatusDescription.Length, buffer, 2); Debug.Assert(count - 2 == encodedLength, $"GetByteCount and GetBytes encoded count didn't match"); } ushort closeStatusValue = (ushort)closeStatus; buffer[0] = (byte)(closeStatusValue >> 8); buffer[1] = (byte)(closeStatusValue & 0xFF); await SendFrameAsync(MessageOpcode.Close, true, new Memory<byte>(buffer, 0, count), cancellationToken).ConfigureAwait(false); } finally { if (buffer != null) { ArrayPool<byte>.Shared.Return(buffer); } } lock (StateUpdateLock) { _sentCloseFrame = true; if (_state <= WebSocketState.CloseReceived) { _state = WebSocketState.CloseSent; } } if (!_isServer && _receivedCloseFrame) { await WaitForServerToCloseConnectionAsync().ConfigureAwait(false); } } private void ConsumeFromBuffer(int count) { Debug.Assert(count >= 0, $"Expected non-negative count, got {count}"); Debug.Assert(count <= _receiveBufferCount, $"Trying to consume {count}, which is more than exists {_receiveBufferCount}"); _receiveBufferCount -= count; _receiveBufferOffset += count; } private async Task EnsureBufferContainsAsync(int minimumRequiredBytes, bool throwOnPrematureClosure = true) { Debug.Assert(minimumRequiredBytes <= _receiveBuffer.Length, $"Requested number of bytes {minimumRequiredBytes} must not exceed {_receiveBuffer.Length}"); // If we don't have enough data in the buffer to satisfy the minimum required, read some more. if (_receiveBufferCount < minimumRequiredBytes) { // If there's any data in the buffer, shift it down. if (_receiveBufferCount > 0) { _receiveBuffer.Span.Slice(_receiveBufferOffset, _receiveBufferCount).CopyTo(_receiveBuffer.Span); } _receiveBufferOffset = 0; // While we don't have enough data, read more. while (_receiveBufferCount < minimumRequiredBytes) { int numRead = await _stream.ReadAsync(_receiveBuffer.Slice(_receiveBufferCount, _receiveBuffer.Length - _receiveBufferCount), default).ConfigureAwait(false); Debug.Assert(numRead >= 0, $"Expected non-negative bytes read, got {numRead}"); if (numRead <= 0) { ThrowIfEOFUnexpected(throwOnPrematureClosure); break; } _receiveBufferCount += numRead; } } } private void ThrowIfEOFUnexpected(bool throwOnPrematureClosure) { // The connection closed before we were able to read everything we needed. // If it was due to us being disposed, fail. If it was due to the connection // being closed and it wasn't expected, fail. If it was due to the connection // being closed and that was expected, exit gracefully. if (_disposed) { throw new ObjectDisposedException(nameof(WebSocket)); } if (throwOnPrematureClosure) { throw new WebSocketException(WebSocketError.ConnectionClosedPrematurely); } } /// <summary>Gets a send buffer from the pool.</summary> private void AllocateSendBuffer(int minLength) { Debug.Assert(_sendBuffer == null); // would only fail if had some catastrophic error previously that prevented cleaning up _sendBuffer = ArrayPool<byte>.Shared.Rent(minLength); } /// <summary>Releases the send buffer to the pool.</summary> private void ReleaseSendBuffer() { byte[] old = _sendBuffer; if (old != null) { _sendBuffer = null; ArrayPool<byte>.Shared.Return(old); } } private static unsafe int CombineMaskBytes(Span<byte> buffer, int maskOffset) => BitConverter.ToInt32(buffer.Slice(maskOffset)); /// <summary>Applies a mask to a portion of a byte array.</summary> /// <param name="toMask">The buffer to which the mask should be applied.</param> /// <param name="mask">The array containing the mask to apply.</param> /// <param name="maskOffset">The offset into <paramref name="mask"/> of the mask to apply of length <see cref="MaskLength"/>.</param> /// <param name="maskOffsetIndex">The next position offset from <paramref name="maskOffset"/> of which by to apply next from the mask.</param> /// <returns>The updated maskOffsetOffset value.</returns> private static int ApplyMask(Span<byte> toMask, byte[] mask, int maskOffset, int maskOffsetIndex) { Debug.Assert(maskOffsetIndex < MaskLength, $"Unexpected {nameof(maskOffsetIndex)}: {maskOffsetIndex}"); Debug.Assert(mask.Length >= MaskLength + maskOffset, $"Unexpected inputs: {mask.Length}, {maskOffset}"); return ApplyMask(toMask, CombineMaskBytes(mask, maskOffset), maskOffsetIndex); } /// <summary>Applies a mask to a portion of a byte array.</summary> /// <param name="toMask">The buffer to which the mask should be applied.</param> /// <param name="mask">The four-byte mask, stored as an Int32.</param> /// <param name="maskIndex">The index into the mask.</param> /// <returns>The next index into the mask to be used for future applications of the mask.</returns> private static unsafe int ApplyMask(Span<byte> toMask, int mask, int maskIndex) { Debug.Assert(maskIndex < sizeof(int)); int maskShift = maskIndex * 8; int shiftedMask = (int)(((uint)mask >> maskShift) | ((uint)mask << (32 - maskShift))); #if MONO_FEATURE_SIMD // Try to use SIMD. We can if the number of bytes we're trying to mask is at least as much // as the width of a vector and if the width is an even multiple of the mask. if (Vector.IsHardwareAccelerated && Vector<byte>.Count % sizeof(int) == 0 && toMask.Length >= Vector<byte>.Count) { Vector<byte> maskVector = Vector.AsVectorByte(new Vector<int>(shiftedMask)); Span<Vector<byte>> toMaskVector = MemoryMarshal.Cast<byte, Vector<byte>>(toMask); for (int i = 0; i < toMaskVector.Length; i++) { toMaskVector[i] ^= maskVector; } // Fall through to processing any remaining bytes that were less than a vector width. toMask = toMask.Slice(Vector<byte>.Count * toMaskVector.Length); } #endif // If there are any bytes remaining (either we couldn't use vectors, or the count wasn't // an even multiple of the vector width), process them without vectors. int count = toMask.Length; if (count > 0) { fixed (byte* toMaskPtr = &MemoryMarshal.GetReference(toMask)) { byte* p = toMaskPtr; // Try to go an int at a time if the remaining data is 4-byte aligned and there's enough remaining. if (((long)p % sizeof(int)) == 0) { while (count >= sizeof(int)) { count -= sizeof(int); *((int*)p) ^= shiftedMask; p += sizeof(int); } // We don't need to update the maskIndex, as its mod-4 value won't have changed. // `p` points to the remainder. } // Process any remaining data a byte at a time. if (count > 0) { byte* maskPtr = (byte*)&mask; byte* end = p + count; while (p < end) { *p++ ^= maskPtr[maskIndex]; maskIndex = (maskIndex + 1) & 3; } } } } // Return the updated index. return maskIndex; } /// <summary>Aborts the websocket and throws an exception if an existing operation is in progress.</summary> private void ThrowIfOperationInProgress(bool operationCompleted, [CallerMemberName] string methodName = null) { if (!operationCompleted) { Abort(); ThrowOperationInProgress(methodName); } } private void ThrowOperationInProgress(string methodName) => throw new InvalidOperationException(SR.Format(SR.net_Websockets_AlreadyOneOutstandingOperation, methodName)); /// <summary>Creates an OperationCanceledException instance, using a default message and the specified inner exception and token.</summary> private static Exception CreateOperationCanceledException(Exception innerException, CancellationToken cancellationToken = default(CancellationToken)) { return new OperationCanceledException( new OperationCanceledException().Message, innerException, cancellationToken); } // From https://raw.githubusercontent.com/aspnet/WebSockets/dev/src/Microsoft.AspNetCore.WebSockets.Protocol/Utilities.cs // Performs a stateful validation of UTF-8 bytes. // It checks for valid formatting, overlong encodings, surrogates, and value ranges. private static bool TryValidateUtf8(Span<byte> span, bool endOfMessage, Utf8MessageState state) { for (int i = 0; i < span.Length;) { // Have we started a character sequence yet? if (!state.SequenceInProgress) { // The first byte tells us how many bytes are in the sequence. state.SequenceInProgress = true; byte b = span[i]; i++; if ((b & 0x80) == 0) // 0bbbbbbb, single byte { state.AdditionalBytesExpected = 0; state.CurrentDecodeBits = b & 0x7F; state.ExpectedValueMin = 0; } else if ((b & 0xC0) == 0x80) { // Misplaced 10bbbbbb continuation byte. This cannot be the first byte. return false; } else if ((b & 0xE0) == 0xC0) // 110bbbbb 10bbbbbb { state.AdditionalBytesExpected = 1; state.CurrentDecodeBits = b & 0x1F; state.ExpectedValueMin = 0x80; } else if ((b & 0xF0) == 0xE0) // 1110bbbb 10bbbbbb 10bbbbbb { state.AdditionalBytesExpected = 2; state.CurrentDecodeBits = b & 0xF; state.ExpectedValueMin = 0x800; } else if ((b & 0xF8) == 0xF0) // 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb { state.AdditionalBytesExpected = 3; state.CurrentDecodeBits = b & 0x7; state.ExpectedValueMin = 0x10000; } else // 111110bb & 1111110b & 11111110 && 11111111 are not valid { return false; } } while (state.AdditionalBytesExpected > 0 && i < span.Length) { byte b = span[i]; if ((b & 0xC0) != 0x80) { return false; } i++; state.AdditionalBytesExpected--; // Each continuation byte carries 6 bits of data 0x10bbbbbb. state.CurrentDecodeBits = (state.CurrentDecodeBits << 6) | (b & 0x3F); if (state.AdditionalBytesExpected == 1 && state.CurrentDecodeBits >= 0x360 && state.CurrentDecodeBits <= 0x37F) { // This is going to end up in the range of 0xD800-0xDFFF UTF-16 surrogates that are not allowed in UTF-8; return false; } if (state.AdditionalBytesExpected == 2 && state.CurrentDecodeBits >= 0x110) { // This is going to be out of the upper Unicode bound 0x10FFFF. return false; } } if (state.AdditionalBytesExpected == 0) { state.SequenceInProgress = false; if (state.CurrentDecodeBits < state.ExpectedValueMin) { // Overlong encoding (e.g. using 2 bytes to encode something that only needed 1). return false; } } } if (endOfMessage && state.SequenceInProgress) { return false; } return true; } private sealed class Utf8MessageState { internal bool SequenceInProgress; internal int AdditionalBytesExpected; internal int ExpectedValueMin; internal int CurrentDecodeBits; } private enum MessageOpcode : byte { Continuation = 0x0, Text = 0x1, Binary = 0x2, Close = 0x8, Ping = 0x9, Pong = 0xA } [StructLayout(LayoutKind.Auto)] private struct MessageHeader { internal MessageOpcode Opcode; internal bool Fin; internal long PayloadLength; internal int Mask; } /// <summary> /// Interface used by <see cref="ReceiveAsyncPrivate"/> to enable it to return /// different result types in an efficient manner. /// </summary> /// <typeparam name="TResult">The type of the result</typeparam> private interface IWebSocketReceiveResultGetter<TResult> { TResult GetResult(int count, WebSocketMessageType messageType, bool endOfMessage, WebSocketCloseStatus? closeStatus, string closeDescription); } /// <summary><see cref="IWebSocketReceiveResultGetter{TResult}"/> implementation for <see cref="WebSocketReceiveResult"/>.</summary> private readonly struct WebSocketReceiveResultGetter : IWebSocketReceiveResultGetter<WebSocketReceiveResult> { public WebSocketReceiveResult GetResult(int count, WebSocketMessageType messageType, bool endOfMessage, WebSocketCloseStatus? closeStatus, string closeDescription) => new WebSocketReceiveResult(count, messageType, endOfMessage, closeStatus, closeDescription); } } }
50.810204
199
0.582828
[ "MIT" ]
baulig/corefx
src/Common/src/System/Net/WebSockets/ManagedWebSocket.cs
74,691
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; namespace Aliyun.Acs.Edas.Model.V20170801 { public class QueryServiceTimeConfigResponse : AcsResponse { private int? code; private string message; private bool? success; private QueryServiceTimeConfig_Data data; public int? Code { get { return code; } set { code = value; } } public string Message { get { return message; } set { message = value; } } public bool? Success { get { return success; } set { success = value; } } public QueryServiceTimeConfig_Data Data { get { return data; } set { data = value; } } public class QueryServiceTimeConfig_Data { private int? pageNumber; private int? totalSize; private int? pageSize; private int? currentPage; private List<QueryServiceTimeConfig_MseServiceTime> result; public int? PageNumber { get { return pageNumber; } set { pageNumber = value; } } public int? TotalSize { get { return totalSize; } set { totalSize = value; } } public int? PageSize { get { return pageSize; } set { pageSize = value; } } public int? CurrentPage { get { return currentPage; } set { currentPage = value; } } public List<QueryServiceTimeConfig_MseServiceTime> Result { get { return result; } set { result = value; } } public class QueryServiceTimeConfig_MseServiceTime { private long? id; private string path; private string consumerAppName; private string timeout; private string consumerAppId; public long? Id { get { return id; } set { id = value; } } public string Path { get { return path; } set { path = value; } } public string ConsumerAppName { get { return consumerAppName; } set { consumerAppName = value; } } public string Timeout { get { return timeout; } set { timeout = value; } } public string ConsumerAppId { get { return consumerAppId; } set { consumerAppId = value; } } } } } }
15.085837
63
0.545661
[ "Apache-2.0" ]
aliyun/aliyun-openapi-net-sdk
aliyun-net-sdk-edas/Edas/Model/V20170801/QueryServiceTimeConfigResponse.cs
3,515
C#
using System; using DataStructures.Stack; namespace DataStructures { public class BracketValidation { public bool MultiBracketValidation(string BracketString) { bool error = false; Stack<char> stack = new Stack<char>(); foreach (var item in BracketString.ToCharArray()) { if (item == '(' || item == '{' || item == '[') { stack.Push(item); } else if (item == ')' || item == '}' || item == ']') { if (stack.Peek() != GetComplementBracket(item)) { error = true; break; } else { stack.Pop(); } } } if (error || !stack.IsEmpty()) return false; else return true; } private static char GetComplementBracket(char item) { return item switch { ')' => '(', '}' => '{', ']' => '[', _ => ' ', }; } } }
25.54
67
0.335944
[ "MIT" ]
selmaT273/DSA
DataStructures/BracketValidation.cs
1,279
C#
using J2N.Text; using Lucene.Net.Support; using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; namespace Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using ArrayUtil = Lucene.Net.Util.ArrayUtil; using BytesRef = Lucene.Net.Util.BytesRef; using FlushInfo = Lucene.Net.Store.FlushInfo; using IOContext = Lucene.Net.Store.IOContext; using IOUtils = Lucene.Net.Util.IOUtils; using RamUsageEstimator = Lucene.Net.Util.RamUsageEstimator; using TermVectorsWriter = Lucene.Net.Codecs.TermVectorsWriter; internal sealed class TermVectorsConsumer : TermsHashConsumer { internal TermVectorsWriter writer; internal readonly DocumentsWriterPerThread docWriter; internal readonly DocumentsWriterPerThread.DocState docState; internal readonly BytesRef flushTerm = new BytesRef(); // Used by perField when serializing the term vectors internal readonly ByteSliceReader vectorSliceReaderPos = new ByteSliceReader(); internal readonly ByteSliceReader vectorSliceReaderOff = new ByteSliceReader(); internal bool hasVectors; internal int numVectorFields; internal int lastDocID; private TermVectorsConsumerPerField[] perFields = new TermVectorsConsumerPerField[1]; public TermVectorsConsumer(DocumentsWriterPerThread docWriter) { this.docWriter = docWriter; docState = docWriter.docState; } // LUCENENE specific - original was internal, but FreqProxTermsWriter requires public (little point, since both are internal classes) [MethodImpl(MethodImplOptions.NoInlining)] public override void Flush(IDictionary<string, TermsHashConsumerPerField> fieldsToFlush, SegmentWriteState state) { if (writer != null) { int numDocs = state.SegmentInfo.DocCount; Debug.Assert(numDocs > 0); // At least one doc in this run had term vectors enabled try { Fill(numDocs); Debug.Assert(state.SegmentInfo != null); writer.Finish(state.FieldInfos, numDocs); } finally { IOUtils.Dispose(writer); writer = null; lastDocID = 0; hasVectors = false; } } foreach (TermsHashConsumerPerField field in fieldsToFlush.Values) { TermVectorsConsumerPerField perField = (TermVectorsConsumerPerField)field; perField.termsHashPerField.Reset(); perField.ShrinkHash(); } } /// <summary> /// Fills in no-term-vectors for all docs we haven't seen /// since the last doc that had term vectors. /// </summary> internal void Fill(int docID) { while (lastDocID < docID) { writer.StartDocument(0); writer.FinishDocument(); lastDocID++; } } [MethodImpl(MethodImplOptions.NoInlining)] private void InitTermVectorsWriter() { if (writer == null) { IOContext context = new IOContext(new FlushInfo(docWriter.NumDocsInRAM, docWriter.BytesUsed)); writer = docWriter.codec.TermVectorsFormat.VectorsWriter(docWriter.directory, docWriter.SegmentInfo, context); lastDocID = 0; } } [MethodImpl(MethodImplOptions.NoInlining)] internal override void FinishDocument(TermsHash termsHash) { // LUCENENET: .NET doesn't support asserts in release mode if (Lucene.Net.Diagnostics.Debugging.AssertsEnabled) docWriter.TestPoint("TermVectorsTermsWriter.finishDocument start"); if (!hasVectors) { return; } InitTermVectorsWriter(); Fill(docState.docID); // Append term vectors to the real outputs: writer.StartDocument(numVectorFields); for (int i = 0; i < numVectorFields; i++) { perFields[i].FinishDocument(); } writer.FinishDocument(); Debug.Assert(lastDocID == docState.docID, "lastDocID=" + lastDocID + " docState.docID=" + docState.docID); lastDocID++; termsHash.Reset(); Reset(); // LUCENENET: .NET doesn't support asserts in release mode if (Lucene.Net.Diagnostics.Debugging.AssertsEnabled) docWriter.TestPoint("TermVectorsTermsWriter.finishDocument end"); } [MethodImpl(MethodImplOptions.NoInlining)] public override void Abort() { hasVectors = false; if (writer != null) { writer.Abort(); writer = null; } lastDocID = 0; Reset(); } internal void Reset() { Arrays.Fill(perFields, null); // don't hang onto stuff from previous doc numVectorFields = 0; } public override TermsHashConsumerPerField AddField(TermsHashPerField termsHashPerField, FieldInfo fieldInfo) { return new TermVectorsConsumerPerField(termsHashPerField, this, fieldInfo); } [MethodImpl(MethodImplOptions.NoInlining)] internal void AddFieldToFlush(TermVectorsConsumerPerField fieldToFlush) { if (numVectorFields == perFields.Length) { int newSize = ArrayUtil.Oversize(numVectorFields + 1, RamUsageEstimator.NUM_BYTES_OBJECT_REF); TermVectorsConsumerPerField[] newArray = new TermVectorsConsumerPerField[newSize]; Array.Copy(perFields, 0, newArray, 0, numVectorFields); perFields = newArray; } perFields[numVectorFields++] = fieldToFlush; } internal override void StartDocument() { Debug.Assert(ClearLastVectorFieldName()); Reset(); } // Called only by assert internal bool ClearLastVectorFieldName() { lastVectorFieldName = null; return true; } // Called only by assert internal string lastVectorFieldName; internal bool VectorFieldsInOrder(FieldInfo fi) { try { return lastVectorFieldName != null ? lastVectorFieldName.CompareToOrdinal(fi.Name) < 0 : true; } finally { lastVectorFieldName = fi.Name; } } } }
35.818605
141
0.600182
[ "Apache-2.0" ]
Ref12/lucenenet
src/Lucene.Net/Index/TermVectorsConsumer.cs
7,701
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MapService.Models { public struct Colors { public string primaryColor { get; set; } public string secondaryColor { get; set; } public string preferredColorScheme { get; set; } } public class MapSetting { public string target { get; set; } public int[] center { get; set; } public string title { get; set; } public string projection { get; set; } public int zoom { get; set; } public int maxZoom { get; set; } public int minZoom { get; set; } public double[] resolutions { get; set; } public double[] origin { get; set; } public double[] extent { get; set; } public bool constrainOnlyCenter { get; set; } public bool constrainResolution { get; set; } public bool enableDownloadLink { get; set; } public string logo { get; set; } public string logoLight { get; set; } public string logoDark { get; set; } public string geoserverLegendOptions { get; set; } public bool mapselector { get; set; } public bool mapcleaner { get; set; } public bool drawerVisible { get; set; } public bool drawerVisibleMobile {get; set; } public bool drawerPermanent { get; set; } public string activeDrawerOnStart { get; set; } public Colors colors { get; set; } public string defaultCookieNoticeMessage { get; set; } public string defaultCookieNoticeUrl { get; set; } public string crossOrigin { get; set; } public bool showCookieNotice { get; set; } public bool showThemeToggler { get; set; } } }
23.922078
62
0.597177
[ "MIT" ]
hajkmap/Hajk
backend/mapservice/Models/MapSetting.cs
1,844
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization; using Azure.Messaging.EventHubs.Amqp; using Azure.Messaging.EventHubs.Metadata; using Microsoft.Azure.Amqp; using Microsoft.Azure.Amqp.Encoding; using Microsoft.Azure.Amqp.Framing; using NUnit.Framework; using NUnit.Framework.Constraints; namespace Azure.Messaging.EventHubs.Tests { /// <summary> /// The suite of tests for the <see cref="AmqpMessageConverter" /> /// class. /// </summary> /// [TestFixture] public class AmqpMessageConverterTests { /// <summary> /// The set of test cases for known described type properties. /// </summary> public static IEnumerable<object[]> DescribedTypePropertyTestCases() { Func<object, object> TranslateValue = value => { return value switch { DateTimeOffset offset => offset.Ticks, TimeSpan timespan => timespan.Ticks, Uri uri => uri.AbsoluteUri, _ => value, }; }; yield return new object[] { AmqpProperty.Descriptor.Uri, new Uri("https://www.cheetoes.zomg"), TranslateValue }; yield return new object[] { AmqpProperty.Descriptor.DateTimeOffset, DateTimeOffset.Parse("2015-10-27T12:00:00Z"), TranslateValue }; yield return new object[] { AmqpProperty.Descriptor.TimeSpan, TimeSpan.FromHours(6), TranslateValue }; } /// <summary> /// The set of test cases for known described type properties. /// </summary> /// public static IEnumerable<object[]> StreamPropertyTestCases() { var contents = new byte[] { 0x55, 0x66, 0x99, 0xAA }; yield return new object[] { new MemoryStream(contents, false), contents }; yield return new object[] { new BufferedStream(new MemoryStream(contents, false), 512), contents }; } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateMessageFromEvent" /> /// method. /// </summary> /// [Test] public void CreateMessageFromEventValidatesTheSource() { var converter = new AmqpMessageConverter(); Assert.That(() => converter.CreateMessageFromEvent(null), Throws.ArgumentNullException); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateMessageFromEvent" /> /// method. /// </summary> /// [Test] [TestCase(null)] [TestCase("")] public void CreateMessageFromEventAllowsNoPartitionKey(string partitionKey) { var converter = new AmqpMessageConverter(); Assert.That(() => converter.CreateMessageFromEvent(new EventData(new byte[] { 0x11 }), partitionKey), Throws.Nothing); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateMessageFromEvent" /> /// method. /// </summary> /// [Test] public void CreateMessageFromEventPopulatesTheBody() { var body = new byte[] { 0x11, 0x22, 0x33 }; var eventData = new EventData(body); var converter = new AmqpMessageConverter(); using AmqpMessage message = converter.CreateMessageFromEvent(eventData); Assert.That(message, Is.Not.Null, "The AMQP message should have been created."); Assert.That(message.DataBody, Is.Not.Null, "The AMQP message should a body."); var messageData = message.DataBody.ToList(); Assert.That(messageData.Count, Is.EqualTo(1), "The AMQP message should a single data body."); Assert.That(messageData[0].Value, Is.EqualTo(eventData.Body.ToArray()), "The AMQP message data should match the event body."); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateMessageFromEvent" /> /// method. /// </summary> /// [Test] [TestCase(null)] [TestCase("")] [TestCase("a-key-that-is-for-partitions")] public void CreateMessageFromEventProperlySetsThePartitionKeyAnnotation(string partitionKey) { var body = new byte[] { 0x11, 0x22, 0x33 }; var eventData = new EventData(body); var converter = new AmqpMessageConverter(); using AmqpMessage message = converter.CreateMessageFromEvent(eventData, partitionKey); Assert.That(message, Is.Not.Null, "The AMQP message should have been created."); Assert.That(message.MessageAnnotations.Map.TryGetValue(AmqpProperty.PartitionKey, out object annotationPartionKey), Is.EqualTo(!string.IsNullOrEmpty(partitionKey)), "The partition key annotation was not correctly set."); if (!string.IsNullOrEmpty(partitionKey)) { Assert.That(annotationPartionKey, Is.EqualTo(partitionKey), "The partition key annotation should match."); } } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateMessageFromEvent" /> /// method. /// </summary> /// [Test] public void CreateMessageFromEventPopulatesSimpleApplicationProperties() { var propertyValues = new object[] { (byte)0x22, (sbyte)0x11, (short)5, (int)27, (long)1122334, (ushort)12, (uint)24, (ulong)9955, (float)4.3, (double)3.4, (decimal)7.893, Guid.NewGuid(), DateTime.Parse("2015-10-27T12:00:00Z"), true, 'x', "hello" }; var eventData = new EventData( eventBody: new byte[] { 0x11, 0x22, 0x33 }, properties: propertyValues.ToDictionary(value => $"{ value.GetType().Name }Property", value => value)); using AmqpMessage message = new AmqpMessageConverter().CreateMessageFromEvent(eventData); Assert.That(message, Is.Not.Null, "The AMQP message should have been created."); Assert.That(message.DataBody, Is.Not.Null, "The AMQP message should a body."); Assert.That(message.ApplicationProperties, Is.Not.Null, "The AMQP message should have a set of application properties."); // The collection comparisons built into the test assertions do not recognize // the property sets as equivalent, but a manual inspection proves the properties exist // in both. foreach (var property in eventData.Properties.Keys) { var containsValue = message.ApplicationProperties.Map.TryGetValue(property, out object value); Assert.That(containsValue, Is.True, $"The message properties did not contain: [{ property }]"); Assert.That(value, Is.EqualTo(eventData.Properties[property]), $"The property value did not match for: [{ property }]"); } } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateMessageFromEvent" /> /// method. /// </summary> /// [Test] [TestCaseSource(nameof(DescribedTypePropertyTestCases))] public void CreateMessageFromEventTranslatesDescribedApplicationProperties(object typeDescriptor, object propertyValueRaw, Func<object, object> propertyValueAccessor) { var eventData = new EventData( eventBody: new byte[] { 0x11, 0x22, 0x33 }, properties: new Dictionary<string, object> { { "TestProp", propertyValueRaw } }); using AmqpMessage message = new AmqpMessageConverter().CreateMessageFromEvent(eventData); Assert.That(message, Is.Not.Null, "The AMQP message should have been created."); Assert.That(message.DataBody, Is.Not.Null, "The AMQP message should a body."); Assert.That(message.ApplicationProperties, Is.Not.Null, "The AMQP message should have a set of application properties."); var propertyKey = eventData.Properties.Keys.First(); var propertyValue = propertyValueAccessor(eventData.Properties[propertyKey]); var containsValue = message.ApplicationProperties.Map.TryGetValue(propertyKey, out DescribedType describedValue); Assert.That(containsValue, Is.True, "The message properties did not contain the property."); Assert.That(describedValue.Value, Is.EqualTo(propertyValue), "The property value did not match."); Assert.That(describedValue.Descriptor, Is.EqualTo(typeDescriptor), "The message property descriptor was incorrect."); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateMessageFromEvent" /> /// method. /// </summary> /// [Test] [TestCaseSource(nameof(StreamPropertyTestCases))] public void CreateMessageFromEventTranslatesStreamApplicationProperties(object propertyStream, byte[] contents) { var eventData = new EventData( eventBody: new byte[] { 0x11, 0x22, 0x33 }, properties: new Dictionary<string, object> { { "TestProp", propertyStream } }); using AmqpMessage message = new AmqpMessageConverter().CreateMessageFromEvent(eventData); Assert.That(message, Is.Not.Null, "The AMQP message should have been created."); Assert.That(message.DataBody, Is.Not.Null, "The AMQP message should a body."); Assert.That(message.ApplicationProperties, Is.Not.Null, "The AMQP message should have a set of application properties."); var propertyKey = eventData.Properties.Keys.First(); var containsValue = message.ApplicationProperties.Map.TryGetValue(propertyKey, out object streamValue); Assert.That(containsValue, Is.True, "The message properties did not contain the property."); Assert.That(streamValue, Is.InstanceOf<ArraySegment<byte>>(), "The message property stream was not read correctly."); Assert.That(((ArraySegment<byte>)streamValue).ToArray(), Is.EqualTo(contents), "The property value did not match."); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateMessageFromEvent" /> /// method. /// </summary> /// [Test] public void CreateMessageFromEventFailsForUnknownApplicationPropertyType() { var eventData = new EventData( eventBody: new byte[] { 0x11, 0x22, 0x33 }, properties: new Dictionary<string, object> { { "TestProperty", new RankException() } }); Assert.That(() => new AmqpMessageConverter().CreateMessageFromEvent(eventData), Throws.InstanceOf<SerializationException>()); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateMessageFromEvent" /> /// method. /// </summary> /// [Test] public void CreateMessageFromEventAllowsAnEmptyEvent() { var eventData = new EventData(ReadOnlyMemory<byte>.Empty); Assert.That(() => new AmqpMessageConverter().CreateMessageFromEvent(eventData), Throws.Nothing); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateMessageFromEvent" /> /// method. /// </summary> /// [Test] public void CreateMessageFromEventAllowsEmptyEventWithAProperty() { var eventData = new EventData(new byte[0]); eventData.Properties["Test"] = 1; Assert.That(() => new AmqpMessageConverter().CreateMessageFromEvent(eventData), Throws.Nothing); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateMessageFromEvent" /> /// method. /// </summary> /// [Test] public void CreateMessageFromEventAllowsEmptyEventWithAPartitionKey() { var eventData = new EventData(new byte[0]); Assert.That(() => new AmqpMessageConverter().CreateMessageFromEvent(eventData, "annotation"), Throws.Nothing); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateBatchFromEvents" /> /// method. /// </summary> /// [Test] public void CreateBatchFromEventsValidatesTheSource() { var converter = new AmqpMessageConverter(); Assert.That(() => converter.CreateBatchFromEvents(null, "anything"), Throws.ArgumentNullException); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateBatchFromEvents" /> /// method. /// </summary> /// [Test] [TestCase(null)] [TestCase("")] public void CreateBatchFromEventsAllowsNoPartitionKey(string partitionKey) { EventData[] events = new[] { new EventData(new byte[] { 0x11, 0x22, 0x33 }) }; Assert.That(() => new AmqpMessageConverter().CreateBatchFromEvents(events, partitionKey), Throws.Nothing); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateBatchFromEvents" /> /// method. /// </summary> /// [Test] [TestCase(null)] [TestCase("")] [TestCase("a-key-that-is-for-partitions")] public void CreateBatchFromEventsWithOneMessagePopulatesEnvelopeProperties(string partitionKey) { var eventData = new EventData(new byte[] { 0x11, 0x22, 0x33 }); var converter = new AmqpMessageConverter(); using AmqpMessage message = converter.CreateBatchFromEvents(new[] { eventData }, partitionKey); Assert.That(message, Is.Not.Null, "The batch envelope should have been created."); Assert.That(message.Batchable, Is.True, "The batch envelope should be set to batchable."); Assert.That(message.MessageFormat, Is.Null, "The batch envelope should be not be marked with a batchable format when created from one event."); Assert.That(message.DataBody, Is.Not.Null, "The batch envelope should a body."); Assert.That(message.DataBody.ToList().Count, Is.EqualTo(1), "The batch envelope should contain a single event in the body."); Assert.That(message.MessageAnnotations.Map.TryGetValue(AmqpProperty.PartitionKey, out string partitionKeyAnnotation), Is.EqualTo(!string.IsNullOrEmpty(partitionKey)), "There should be an annotation if a partition key was present."); if (!string.IsNullOrEmpty(partitionKey)) { Assert.That(partitionKeyAnnotation, Is.EqualTo(partitionKey), "The partition key annotation should match."); } } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateBatchFromEvents" /> /// method. /// </summary> /// [Test] [TestCase(null)] [TestCase("")] [TestCase("a-key-that-is-for-partitions")] public void CreateBatchFromEventsWithMultipleEventsMessagePopulatesEnvelopeProperties(string partitionKey) { EventData[] events = new[] { new EventData(new byte[] { 0x11, 0x22, 0x33 }), new EventData(new byte[] { 0x44, 0x55, 0x66 }) }; using AmqpMessage message = new AmqpMessageConverter().CreateBatchFromEvents(events, partitionKey); Assert.That(message, Is.Not.Null, "The batch envelope should have been created."); Assert.That(message.Batchable, Is.True, "The batch envelope should be marked as batchable."); Assert.That(message.MessageFormat, Is.EqualTo(AmqpConstants.AmqpBatchedMessageFormat), "The batch envelope should be marked with a batchable format."); Assert.That(message.DataBody, Is.Not.Null, "The batch envelope should a body."); Assert.That(message.DataBody.ToList().Count, Is.EqualTo(events.Length), "The batch envelope should contain each batch event in the body."); Assert.That(message.MessageAnnotations.Map.TryGetValue(AmqpProperty.PartitionKey, out string partitionKeyAnnotation), Is.EqualTo(!string.IsNullOrEmpty(partitionKey)), "There should be an annotation if a partition key was present."); if (!string.IsNullOrEmpty(partitionKey)) { Assert.That(partitionKeyAnnotation, Is.EqualTo(partitionKey), "The partition key annotation should match."); } } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateBatchFromEvents" /> /// method. /// </summary> /// [Test] public void CreateBatchFromEventWithOneEventUsesItForTheEnvelope() { var body = new byte[] { 0x11, 0x22, 0x33 }; var property = 65; var eventData = new EventData( eventBody: body, properties: new Dictionary<string, object> { { nameof(property), property } }); using AmqpMessage message = new AmqpMessageConverter().CreateBatchFromEvents(new[] { eventData }, "Something"); Assert.That(message, Is.Not.Null, "The batch envelope should have been created."); Assert.That(message.DataBody, Is.Not.Null, "The batch envelope should a body."); var messageData = message.DataBody.ToList(); Assert.That(messageData.Count, Is.EqualTo(1), "The batch envelope should a single data body."); Assert.That(messageData[0].Value, Is.EqualTo(eventData.Body.ToArray()), "The batch envelope data should match the event body."); Assert.That(message.ApplicationProperties.Map.TryGetValue(nameof(property), out object propertyValue), Is.True, "The application property should exist in the batch."); Assert.That(propertyValue, Is.EqualTo(property), "The application property value should match."); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateBatchFromEvents" /> /// method. /// </summary> /// [Test] public void CreateBatchFromEventsWithMultipleEventsPopulatesTheEnvelopeBody() { using var firstEventStream = new MemoryStream(new byte[] { 0x37, 0x39 }); using var secondEventStream = new MemoryStream(new byte[] { 0x73, 0x93 }); var firstEvent = new EventData( eventBody: new byte[] { 0x11, 0x22, 0x33 }, properties: new Dictionary<string, object> { { nameof(MemoryStream), firstEventStream } }); var secondEvent = new EventData( eventBody: new byte[] { 0x44, 0x55, 0x66 }, properties: new Dictionary<string, object> { { nameof(MemoryStream), secondEventStream } }); EventData[] events = new[] { firstEvent, secondEvent }; var converter = new AmqpMessageConverter(); using AmqpMessage message = converter.CreateBatchFromEvents(events, null); Assert.That(message, Is.Not.Null, "The batch envelope should have been created."); Assert.That(message.DataBody, Is.Not.Null, "The batch envelope should a body."); var messageData = message.DataBody.ToList(); Assert.That(messageData.Count, Is.EqualTo(events.Length), "The batch envelope should contain each batch event in the body."); // Reset the position for the stream properties, so that they // can be read for translation again. firstEventStream.Position = 0; secondEventStream.Position = 0; for (var index = 0; index < events.Length; ++index) { AmqpMessage eventMessage = converter.CreateMessageFromEvent(events[index]); eventMessage.Batchable = true; using var memoryStream = new MemoryStream(); using var eventStream = eventMessage.ToStream(); eventStream.CopyTo(memoryStream); var expected = memoryStream.ToArray(); var actual = ((ArraySegment<byte>)messageData[index].Value).ToArray(); Assert.That(actual, Is.EqualTo(expected), $"The batch body for message { index } should match the serialized event."); } } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateBatchFromEvents" /> /// method. /// </summary> [Test] public void CreateBatchFromEventsWithMultipleEventsAssignsThePartitionKeyToBodyMessages() { var partitionKey = "sOmE-kEY"; var firstEvent = new EventData(new byte[] { 0x11, 0x22, 0x33 }); var secondEvent = new EventData(new byte[] { 0x44, 0x55, 0x66 }); EventData[] events = new[] { firstEvent, secondEvent }; var converter = new AmqpMessageConverter(); using AmqpMessage message = converter.CreateBatchFromEvents(events, partitionKey); Assert.That(message, Is.Not.Null, "The batch envelope should have been created."); Assert.That(message.DataBody, Is.Not.Null, "The batch envelope should a body."); var messageData = message.DataBody.ToList(); Assert.That(messageData.Count, Is.EqualTo(events.Length), "The batch envelope should contain each batch event in the body."); for (var index = 0; index < events.Length; ++index) { AmqpMessage eventMessage = converter.CreateMessageFromEvent(events[index]); eventMessage.Batchable = true; eventMessage.MessageAnnotations.Map[AmqpProperty.PartitionKey] = partitionKey; using var memoryStream = new MemoryStream(); using var eventStream = eventMessage.ToStream(); eventStream.CopyTo(memoryStream); var expected = memoryStream.ToArray(); var actual = ((ArraySegment<byte>)messageData[index].Value).ToArray(); Assert.That(actual, Is.EqualTo(expected), $"The batch body for message { index } should match the serialized event."); } } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateBatchFromMessages" /> /// method. /// </summary> /// [Test] public void CreateBatchFromMessagesValidatesTheSource() { var converter = new AmqpMessageConverter(); Assert.That(() => converter.CreateBatchFromMessages(null, "anything"), Throws.ArgumentNullException); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateBatchFromMessages" /> /// method. /// </summary> /// [Test] [TestCase(null)] [TestCase("")] public void CreateBatchFromMessagesAllowNoPartitionKey(string partitionKey) { var converter = new AmqpMessageConverter(); Assert.That(() => converter.CreateBatchFromMessages(new[] { AmqpMessage.Create() }, partitionKey), Throws.Nothing); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateBatchFromMessages" /> /// method. /// </summary> /// [Test] [TestCase(null)] [TestCase("")] [TestCase("a-key-that-is-for-partitions")] public void CreateBatchFromMessagesWithOneMessagePopulatesEnvelopeProperties(string partitionKey) { var eventData = new EventData(new byte[] { 0x11, 0x22, 0x33 }); var converter = new AmqpMessageConverter(); using AmqpMessage source = converter.CreateMessageFromEvent(eventData); using AmqpMessage batchEnvelope = converter.CreateBatchFromMessages(new[] { source }, partitionKey); Assert.That(batchEnvelope, Is.Not.Null, "The batch envelope should have been created."); Assert.That(batchEnvelope.Batchable, Is.True, "The batch envelope should be set to batchable."); Assert.That(batchEnvelope.MessageFormat, Is.Null, "The batch envelope should be not be marked with a batchable format when created from one event."); Assert.That(batchEnvelope.DataBody, Is.Not.Null, "The batch envelope should a body."); Assert.That(batchEnvelope.DataBody.ToList().Count, Is.EqualTo(1), "The batch envelope should contain a single event in the body."); Assert.That(batchEnvelope.MessageAnnotations.Map.TryGetValue(AmqpProperty.PartitionKey, out string partitionKeyAnnotation), Is.EqualTo(!string.IsNullOrEmpty(partitionKey)), "There should be an annotation if a partition key was present."); if (!string.IsNullOrEmpty(partitionKey)) { Assert.That(partitionKeyAnnotation, Is.EqualTo(partitionKey), "The partition key annotation should match."); } } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateBatchFromMessages" /> /// method. /// </summary> /// [Test] [TestCase(null)] [TestCase("")] [TestCase("a-key-that-is-for-partitions")] public void CreateBatchFromMessagesWithMultipleEventsMessagePopulatesEnvelopeProperties(string partitionKey) { var converter = new AmqpMessageConverter(); using AmqpMessage first = converter.CreateMessageFromEvent(new EventData(new byte[] { 0x11, 0x22, 0x33 })); using AmqpMessage second = converter.CreateMessageFromEvent(new EventData(new byte[] { 0x44, 0x55, 0x66 })); AmqpMessage[] source = new[] { first, second }; using AmqpMessage batchEnvelope = converter.CreateBatchFromMessages(source, partitionKey); Assert.That(batchEnvelope, Is.Not.Null, "The batch envelope should have been created."); Assert.That(batchEnvelope.Batchable, Is.True, "The batch envelope should be marked as batchable."); Assert.That(batchEnvelope.MessageFormat, Is.EqualTo(AmqpConstants.AmqpBatchedMessageFormat), "The batch envelope should be marked with a batchable format."); Assert.That(batchEnvelope.DataBody, Is.Not.Null, "The batch envelope should a body."); Assert.That(batchEnvelope.DataBody.ToList().Count, Is.EqualTo(source.Length), "The batch envelope should contain each batch event in the body."); Assert.That(batchEnvelope.MessageAnnotations.Map.TryGetValue(AmqpProperty.PartitionKey, out string partitionKeyAnnotation), Is.EqualTo(!string.IsNullOrEmpty(partitionKey)), "There should be an annotation if a partition key was present."); if (!string.IsNullOrEmpty(partitionKey)) { Assert.That(partitionKeyAnnotation, Is.EqualTo(partitionKey), "The partition key annotation should match."); } } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateBatchFromMessages" /> /// method. /// </summary> /// [Test] public void CreateBatchFromMessagesWithOneEventUsesItForTheEnvelope() { var converter = new AmqpMessageConverter(); var body = new byte[] { 0x11, 0x22, 0x33 }; var property = 65; var eventData = new EventData( eventBody: body, properties: new Dictionary<string, object> { { nameof(property), property } }); using AmqpMessage source = converter.CreateMessageFromEvent(eventData); using AmqpMessage batchEnvelope = converter.CreateBatchFromMessages(new[] { source }, "Something"); Assert.That(batchEnvelope, Is.Not.Null, "The batch envelope should have been created."); Assert.That(batchEnvelope.DataBody, Is.Not.Null, "The batch envelope should a body."); var messageData = batchEnvelope.DataBody.ToList(); Assert.That(messageData.Count, Is.EqualTo(1), "The batch envelope should a single data body."); Assert.That(messageData[0].Value, Is.EqualTo(eventData.Body.ToArray()), "The batch envelope data should match the event body."); Assert.That(batchEnvelope.ApplicationProperties.Map.TryGetValue(nameof(property), out object propertyValue), Is.True, "The application property should exist in the batch."); Assert.That(propertyValue, Is.EqualTo(property), "The application property value should match."); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateBatchFromMessages" /> /// method. /// </summary> /// [Test] public void CreateBatchFromMessagesWithMultipleEventsPopulatesTheEnvelopeBody() { using var firstEventStream = new MemoryStream(new byte[] { 0x37, 0x39 }); using var secondEventStream = new MemoryStream(new byte[] { 0x73, 0x93 }); var converter = new AmqpMessageConverter(); var firstEvent = new EventData( eventBody: new byte[] { 0x11, 0x22, 0x33 }, properties: new Dictionary<string, object> { { nameof(MemoryStream), firstEventStream } }); var secondEvent = new EventData( eventBody: new byte[] { 0x44, 0x55, 0x66 }, properties: new Dictionary<string, object> { { nameof(MemoryStream), secondEventStream } }); using AmqpMessage firstMessage = converter.CreateMessageFromEvent(firstEvent); using AmqpMessage secondMessage = converter.CreateMessageFromEvent(secondEvent); AmqpMessage[] source = new[] { firstMessage, secondMessage }; using AmqpMessage batchEnvelope = converter.CreateBatchFromMessages(source, null); Assert.That(batchEnvelope, Is.Not.Null, "The batch envelope should have been created."); Assert.That(batchEnvelope.DataBody, Is.Not.Null, "The batch envelope should a body."); var messageData = batchEnvelope.DataBody.ToList(); Assert.That(messageData.Count, Is.EqualTo(source.Length), "The batch envelope should contain each batch event in the body."); // Reset the position for the stream properties, so that they // can be read for translation again. firstEventStream.Position = 0; secondEventStream.Position = 0; for (var index = 0; index < source.Length; ++index) { AmqpMessage eventMessage = source[index]; eventMessage.Batchable = true; using var memoryStream = new MemoryStream(); using var eventStream = eventMessage.ToStream(); eventStream.CopyTo(memoryStream); var expected = memoryStream.ToArray(); var actual = ((ArraySegment<byte>)messageData[index].Value).ToArray(); Assert.That(actual, Is.EqualTo(expected), $"The batch body for message { index } should match the serialized event."); } } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateBatchFromMessages" /> /// method. /// </summary> [Test] public void CreateBatchFromMessagesWithMultipleEventsAssignsThePartitionKeyToBodyMessages() { var partitionKey = "sOmE-kEY"; var firstEvent = new EventData(new byte[] { 0x11, 0x22, 0x33 }); var secondEvent = new EventData(new byte[] { 0x44, 0x55, 0x66 }); var converter = new AmqpMessageConverter(); using AmqpMessage firstMessage = converter.CreateMessageFromEvent(firstEvent, partitionKey); using AmqpMessage secondMessage = converter.CreateMessageFromEvent(secondEvent, partitionKey); AmqpMessage[] source = new[] { firstMessage, secondMessage }; using AmqpMessage batchEnvelope = converter.CreateBatchFromMessages(source, partitionKey); Assert.That(batchEnvelope, Is.Not.Null, "The batch envelope should have been created."); Assert.That(batchEnvelope.DataBody, Is.Not.Null, "The batch envelope should a body."); var messageData = batchEnvelope.DataBody.ToList(); Assert.That(messageData.Count, Is.EqualTo(source.Length), "The batch envelope should contain each batch event in the body."); for (var index = 0; index < source.Length; ++index) { AmqpMessage eventMessage = source[index]; eventMessage.Batchable = true; using var memoryStream = new MemoryStream(); using var eventStream = eventMessage.ToStream(); eventStream.CopyTo(memoryStream); var expected = memoryStream.ToArray(); var actual = ((ArraySegment<byte>)messageData[index].Value).ToArray(); Assert.That(actual, Is.EqualTo(expected), $"The batch body for message { index } should match the serialized event."); } } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateEventFromMessage" /> /// method. /// </summary> /// [Test] public void CreateEventFromMessageValidatesTheSource() { var converter = new AmqpMessageConverter(); Assert.That(() => converter.CreateEventFromMessage(null), Throws.ArgumentNullException); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateEventFromMessage" /> /// method. /// </summary> /// [Test] public void CreateEventFromMessagePopulatesTheBody() { var body = new byte[] { 0x11, 0x22, 0x33 }; using var bodyStream = new MemoryStream(body, false); using var message = AmqpMessage.Create(bodyStream, true); var converter = new AmqpMessageConverter(); EventData eventData = converter.CreateEventFromMessage(message); Assert.That(eventData, Is.Not.Null, "The event should have been created."); Assert.That(eventData.Body, Is.Not.Null, "The event should have a body."); Assert.That(eventData.Body.ToArray(), Is.EqualTo(body), "The body contents should match."); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateEventFromMessage" /> /// method. /// </summary> /// [Test] public void CreateEventFromMessagePopulatesSimpleApplicationProperties() { var propertyValues = new object[] { (byte)0x22, (sbyte)0x11, (short)5, (int)27, (long)1122334, (ushort)12, (uint)24, (ulong)9955, (float)4.3, (double)3.4, (decimal)7.893, Guid.NewGuid(), DateTime.Parse("2015-10-27T12:00:00Z"), true, 'x', "hello" }; var applicationProperties = propertyValues.ToDictionary(value => $"{ value.GetType().Name }Property", value => value); using var bodyStream = new MemoryStream(new byte[] { 0x11, 0x22, 0x33 }, false); using var message = AmqpMessage.Create(bodyStream, true); foreach (KeyValuePair<string, object> pair in applicationProperties) { message.ApplicationProperties.Map.Add(pair.Key, pair.Value); } var converter = new AmqpMessageConverter(); EventData eventData = converter.CreateEventFromMessage(message); Assert.That(eventData, Is.Not.Null, "The event should have been created."); Assert.That(eventData.Body, Is.Not.Null, "The event should have a body."); Assert.That(eventData.Properties.Any(), Is.True, "The event should have a set of application properties."); // The collection comparisons built into the test assertions do not recognize // the property sets as equivalent, but a manual inspection proves the properties exist // in both. foreach (var property in applicationProperties.Keys) { var containsValue = eventData.Properties.TryGetValue(property, out object value); Assert.That(containsValue, Is.True, $"The event properties did not contain: [{ property }]"); Assert.That(value, Is.EqualTo(applicationProperties[property]), $"The property value did not match for: [{ property }]"); } } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateEventFromMessage" /> /// method. /// </summary> /// [Test] [TestCaseSource(nameof(DescribedTypePropertyTestCases))] public void CreateEventFromMessagePopulateDescribedApplicationProperties(object typeDescriptor, object propertyValueRaw, Func<object, object> propertyValueAccessor) { using var bodyStream = new MemoryStream(new byte[] { 0x11, 0x22, 0x33 }, false); using var message = AmqpMessage.Create(bodyStream, true); var describedProperty = new DescribedType(typeDescriptor, propertyValueAccessor(propertyValueRaw)); message.ApplicationProperties.Map.Add(typeDescriptor.ToString(), describedProperty); var converter = new AmqpMessageConverter(); EventData eventData = converter.CreateEventFromMessage(message); Assert.That(eventData, Is.Not.Null, "The event should have been created."); Assert.That(eventData.Body, Is.Not.Null, "The event should have a body."); Assert.That(eventData.Properties.Any(), Is.True, "The event should have a set of application properties."); var containsValue = eventData.Properties.TryGetValue(typeDescriptor.ToString(), out object value); Assert.That(containsValue, Is.True, $"The event properties did not contain the described property."); Assert.That(value, Is.EqualTo(propertyValueRaw), $"The property value did not match."); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateEventFromMessage" /> /// method. /// </summary> /// [Test] public void CreateEventFromMessagePopulatesAnArrayApplicationPropertyType() { using var bodyStream = new MemoryStream(new byte[] { 0x11, 0x22, 0x33 }, false); using var message = AmqpMessage.Create(bodyStream, true); var propertyKey = "Test"; var propertyValue = new byte[] { 0x11, 0x15, 0xF8, 0x20 }; message.ApplicationProperties.Map.Add(propertyKey, propertyValue); var converter = new AmqpMessageConverter(); EventData eventData = converter.CreateEventFromMessage(message); Assert.That(eventData, Is.Not.Null, "The event should have been created."); Assert.That(eventData.Body, Is.Not.Null, "The event should have a body."); Assert.That(eventData.Properties.Any(), Is.True, "The event should have a set of application properties."); var containsValue = eventData.Properties.TryGetValue(propertyKey, out var eventValue); Assert.That(containsValue, Is.True, $"The event properties should contain the property."); Assert.That(eventValue, Is.EquivalentTo(propertyValue)); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateEventFromMessage" /> /// method. /// </summary> /// [Test] public void CreateEventFromMessagePopulatesAFullArraySegmentApplicationPropertyType() { using var bodyStream = new MemoryStream(new byte[] { 0x11, 0x22, 0x33 }, false); using var message = AmqpMessage.Create(bodyStream, true); var propertyKey = "Test"; var propertyValue = new byte[] { 0x11, 0x15, 0xF8, 0x20 }; message.ApplicationProperties.Map.Add(propertyKey, new ArraySegment<byte>(propertyValue)); var converter = new AmqpMessageConverter(); EventData eventData = converter.CreateEventFromMessage(message); Assert.That(eventData, Is.Not.Null, "The event should have been created."); Assert.That(eventData.Body, Is.Not.Null, "The event should have a body."); Assert.That(eventData.Properties.Any(), Is.True, "The event should have a set of application properties."); var containsValue = eventData.Properties.TryGetValue(propertyKey, out var eventValue); Assert.That(containsValue, Is.True, $"The event properties should contain the property."); Assert.That(eventValue, Is.EquivalentTo(propertyValue)); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateEventFromMessage" /> /// method. /// </summary> /// [Test] public void CreateEventFromMessagePopulatesAnArraySegmentApplicationPropertyType() { using var bodyStream = new MemoryStream(new byte[] { 0x11, 0x22, 0x33 }, false); using var message = AmqpMessage.Create(bodyStream, true); var propertyKey = "Test"; var propertyValue = new byte[] { 0x11, 0x15, 0xF8, 0x20 }; message.ApplicationProperties.Map.Add(propertyKey, new ArraySegment<byte>(propertyValue, 1, 2)); var converter = new AmqpMessageConverter(); EventData eventData = converter.CreateEventFromMessage(message); Assert.That(eventData, Is.Not.Null, "The event should have been created."); Assert.That(eventData.Body, Is.Not.Null, "The event should have a body."); Assert.That(eventData.Properties.Any(), Is.True, "The event should have a set of application properties."); var containsValue = eventData.Properties.TryGetValue(propertyKey, out var eventValue); Assert.That(containsValue, Is.True, $"The event properties should contain the property."); Assert.That(eventValue, Is.EquivalentTo(propertyValue.Skip(1).Take(2))); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateEventFromMessage" /> /// method. /// </summary> /// [Test] public void CreateEventFromMessageDoesNotIncludeUnknownApplicationPropertyType() { using var bodyStream = new MemoryStream(new byte[] { 0x11, 0x22, 0x33 }, false); using var message = AmqpMessage.Create(bodyStream, true); var typeDescriptor = (AmqpSymbol)"INVALID"; var describedProperty = new DescribedType(typeDescriptor, 1234); message.ApplicationProperties.Map.Add(typeDescriptor.ToString(), describedProperty); var converter = new AmqpMessageConverter(); EventData eventData = converter.CreateEventFromMessage(message); Assert.That(eventData, Is.Not.Null, "The event should have been created."); Assert.That(eventData.Body, Is.Not.Null, "The event should have a body."); Assert.That(eventData.Properties.Any(), Is.False, "The event should not have a set of application properties."); var containsValue = eventData.Properties.TryGetValue(typeDescriptor.ToString(), out var _); Assert.That(containsValue, Is.False, $"The event properties should not contain the described property."); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateEventFromMessage" /> /// method. /// </summary> /// [Test] public void CreateEventFromMessagePopulatesTypedSystemProperties() { var offset = 123; var sequenceNumber = (long.MaxValue - 10); var enqueuedTime = DateTimeOffset.Parse("2015-10-27T12:00:00Z"); var partitionKey = "OMG! partition!"; using var bodyStream = new MemoryStream(new byte[] { 0x11, 0x22, 0x33 }, false); using var message = AmqpMessage.Create(bodyStream, true); message.ApplicationProperties.Map.Add("First", 1); message.ApplicationProperties.Map.Add("Second", "2"); message.MessageAnnotations.Map.Add(AmqpProperty.Offset, offset.ToString()); message.MessageAnnotations.Map.Add(AmqpProperty.SequenceNumber, sequenceNumber); message.MessageAnnotations.Map.Add(AmqpProperty.EnqueuedTime, enqueuedTime.Ticks); message.MessageAnnotations.Map.Add(AmqpProperty.PartitionKey, partitionKey); var converter = new AmqpMessageConverter(); EventData eventData = converter.CreateEventFromMessage(message); Assert.That(eventData, Is.Not.Null, "The event should have been created."); Assert.That(eventData.Body, Is.Not.Null, "The event should have a body."); Assert.That(eventData.Properties.Count, Is.EqualTo(message.ApplicationProperties.Map.Count()), "The event should have a set of properties."); Assert.That(eventData.Offset, Is.EqualTo(offset), "The offset should match."); Assert.That(eventData.SequenceNumber, Is.EqualTo(sequenceNumber), "The sequence number should match."); Assert.That(eventData.EnqueuedTime, Is.EqualTo(enqueuedTime), "The enqueue time should match."); Assert.That(eventData.PartitionKey, Is.EqualTo(partitionKey), "The partition key should match."); Assert.That(eventData.LastPartitionOffset.HasValue, Is.False, "The last offset should not be set."); Assert.That(eventData.LastPartitionSequenceNumber.HasValue, Is.False, "The last sequence number should not be set."); Assert.That(eventData.LastPartitionEnqueuedTime.HasValue, Is.False, "The last enqueued time should not be set."); Assert.That(eventData.LastPartitionInformationRetrievalTime.HasValue, Is.False, "The last retrieval time should not be set."); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateEventFromMessage" /> /// method. /// </summary> /// [Test] public void CreateEventFromMessagePopulatesMappedSystemProperties() { var firstMessageAnnotation = 456; var secondMessageAnnotation = "hello"; var subjectValue = "Test"; using var bodyStream = new MemoryStream(new byte[] { 0x11, 0x22, 0x33 }, false); using var message = AmqpMessage.Create(bodyStream, true); message.ApplicationProperties.Map.Add("First", 1); message.ApplicationProperties.Map.Add("Second", "2"); message.MessageAnnotations.Map.Add(nameof(firstMessageAnnotation), firstMessageAnnotation); message.MessageAnnotations.Map.Add(nameof(secondMessageAnnotation), secondMessageAnnotation); message.Properties.Subject = subjectValue; var converter = new AmqpMessageConverter(); EventData eventData = converter.CreateEventFromMessage(message); Assert.That(eventData, Is.Not.Null, "The event should have been created."); Assert.That(eventData.Body, Is.Not.Null, "The event should have a body."); Assert.That(eventData.Properties.Count, Is.EqualTo(message.ApplicationProperties.Map.Count()), "The event should have a set of properties."); Assert.That(eventData.SystemProperties.ContainsKey(nameof(firstMessageAnnotation)), Is.True, "The first annotation should be in the system properties."); Assert.That(eventData.SystemProperties.ContainsKey(nameof(secondMessageAnnotation)), Is.True, "The second annotation should be in the system properties."); Assert.That(eventData.SystemProperties.ContainsKey(Properties.SubjectName), Is.True, "The message subject should be in the system properties."); Assert.That(eventData.SystemProperties[nameof(firstMessageAnnotation)], Is.EqualTo(firstMessageAnnotation), "The first annotation should match."); Assert.That(eventData.SystemProperties[nameof(secondMessageAnnotation)], Is.EqualTo(secondMessageAnnotation), "The second annotation should match."); Assert.That(eventData.SystemProperties[Properties.SubjectName], Is.EqualTo(subjectValue), "The message subject should match."); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateEventFromMessage" /> /// method. /// </summary> /// [Test] public void CreateEventFromMessagePopulatesTypedSystemPropertiesAndMetrics() { var offset = 123; var lastOffset = 987; var sequenceNumber = (long.MaxValue - 10); var lastSequenceNumber = (long.MaxValue - 100); var enqueuedTime = DateTimeOffset.Parse("2015-10-27T12:00:00Z"); var lastEnqueuedTime = DateTimeOffset.Parse("2012-03-04T08:42:00Z"); var lastRetrievalTime = DateTimeOffset.Parse("203-09-27T04:32:00Z"); var partitionKey = "OMG! partition!"; using var bodyStream = new MemoryStream(new byte[] { 0x11, 0x22, 0x33 }, false); using var message = AmqpMessage.Create(bodyStream, true); message.ApplicationProperties.Map.Add("First", 1); message.ApplicationProperties.Map.Add("Second", "2"); message.MessageAnnotations.Map.Add(AmqpProperty.Offset, offset.ToString()); message.MessageAnnotations.Map.Add(AmqpProperty.SequenceNumber, sequenceNumber); message.MessageAnnotations.Map.Add(AmqpProperty.EnqueuedTime, enqueuedTime.Ticks); message.MessageAnnotations.Map.Add(AmqpProperty.PartitionKey, partitionKey); message.DeliveryAnnotations.Map.Add(AmqpProperty.PartitionLastEnqueuedSequenceNumber, lastSequenceNumber); message.DeliveryAnnotations.Map.Add(AmqpProperty.PartitionLastEnqueuedOffset, lastOffset.ToString()); message.DeliveryAnnotations.Map.Add(AmqpProperty.PartitionLastEnqueuedTimeUtc, lastEnqueuedTime.Ticks); message.DeliveryAnnotations.Map.Add(AmqpProperty.LastPartitionInformationRetrievalTimeUtc, lastRetrievalTime.Ticks); var converter = new AmqpMessageConverter(); EventData eventData = converter.CreateEventFromMessage(message); Assert.That(eventData, Is.Not.Null, "The event should have been created."); Assert.That(eventData.Body, Is.Not.Null, "The event should have a body."); Assert.That(eventData.Properties.Count, Is.EqualTo(message.ApplicationProperties.Map.Count()), "The event should have a set of properties."); Assert.That(eventData.Offset, Is.EqualTo(offset), "The offset should match."); Assert.That(eventData.SequenceNumber, Is.EqualTo(sequenceNumber), "The sequence number should match."); Assert.That(eventData.EnqueuedTime, Is.EqualTo(enqueuedTime), "The enqueue time should match."); Assert.That(eventData.PartitionKey, Is.EqualTo(partitionKey), "The partition key should match."); Assert.That(eventData.LastPartitionOffset, Is.EqualTo(lastOffset), "The last offset should match."); Assert.That(eventData.LastPartitionSequenceNumber, Is.EqualTo(lastSequenceNumber), "The last sequence number should match."); Assert.That(eventData.LastPartitionEnqueuedTime, Is.EqualTo(lastEnqueuedTime), "The last enqueued time should match."); Assert.That(eventData.LastPartitionInformationRetrievalTime, Is.EqualTo(lastRetrievalTime), "The last retrieval time should match."); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateEventFromMessage" /> /// method. /// </summary> /// [Test] public void CreateEventFromMessagePopulatesEnqueueTimeFromDateTime() { var enqueuedTime = DateTimeOffset.Parse("2015-10-27T12:00:00Z"); var lastEnqueuedTime = DateTimeOffset.Parse("2012-03-04T08:42:00Z"); using var bodyStream = new MemoryStream(new byte[] { 0x11, 0x22, 0x33 }, false); using var message = AmqpMessage.Create(bodyStream, true); message.MessageAnnotations.Map.Add(AmqpProperty.EnqueuedTime, enqueuedTime.UtcDateTime); message.DeliveryAnnotations.Map.Add(AmqpProperty.PartitionLastEnqueuedTimeUtc, lastEnqueuedTime.UtcDateTime); var converter = new AmqpMessageConverter(); EventData eventData = converter.CreateEventFromMessage(message); Assert.That(eventData, Is.Not.Null, "The event should have been created."); Assert.That(eventData.EnqueuedTime, Is.EqualTo(enqueuedTime), "The enqueue time should match."); Assert.That(eventData.LastPartitionEnqueuedTime, Is.EqualTo(lastEnqueuedTime), "The last enqueued time should match."); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateEventFromMessage" /> /// method. /// </summary> /// [Test] public void CreateEventFromMessagePopulatesEnqueueTimeFromTicks() { var enqueuedTime = DateTimeOffset.Parse("2015-10-27T12:00:00Z"); var lastEnqueuedTime = DateTimeOffset.Parse("2012-03-04T08:42:00Z"); using var bodyStream = new MemoryStream(new byte[] { 0x11, 0x22, 0x33 }, false); using var message = AmqpMessage.Create(bodyStream, true); message.MessageAnnotations.Map.Add(AmqpProperty.EnqueuedTime, enqueuedTime.UtcTicks); message.DeliveryAnnotations.Map.Add(AmqpProperty.PartitionLastEnqueuedTimeUtc, lastEnqueuedTime.UtcTicks); var converter = new AmqpMessageConverter(); EventData eventData = converter.CreateEventFromMessage(message); Assert.That(eventData, Is.Not.Null, "The event should have been created."); Assert.That(eventData.EnqueuedTime, Is.EqualTo(enqueuedTime), "The enqueue time should match."); Assert.That(eventData.LastPartitionEnqueuedTime, Is.EqualTo(lastEnqueuedTime), "The last enqueued time should match."); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateEventFromMessage" /> /// method. /// </summary> /// [Test] public void CreateEventFromMessagePopulatesLastRetrievalTimeFromDateTime() { var lastRetrieval = DateTimeOffset.Parse("2012-03-04T08:42:00Z"); using var bodyStream = new MemoryStream(new byte[] { 0x11, 0x22, 0x33 }, false); using var message = AmqpMessage.Create(bodyStream, true); message.DeliveryAnnotations.Map.Add(AmqpProperty.LastPartitionInformationRetrievalTimeUtc, lastRetrieval.UtcDateTime); var converter = new AmqpMessageConverter(); EventData eventData = converter.CreateEventFromMessage(message); Assert.That(eventData, Is.Not.Null, "The event should have been created."); Assert.That(eventData.LastPartitionInformationRetrievalTime, Is.EqualTo(lastRetrieval), "The last retrieval time should match."); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateEventFromMessage" /> /// method. /// </summary> /// [Test] public void CreateEventFromMessagePopulatesLastRetrievalTimeFromTicks() { var lastRetrieval = DateTimeOffset.Parse("2012-03-04T08:42:00Z"); using var bodyStream = new MemoryStream(new byte[] { 0x11, 0x22, 0x33 }, false); using var message = AmqpMessage.Create(bodyStream, true); message.DeliveryAnnotations.Map.Add(AmqpProperty.LastPartitionInformationRetrievalTimeUtc, lastRetrieval.UtcTicks); var converter = new AmqpMessageConverter(); EventData eventData = converter.CreateEventFromMessage(message); Assert.That(eventData, Is.Not.Null, "The event should have been created."); Assert.That(eventData.LastPartitionInformationRetrievalTime, Is.EqualTo(lastRetrieval), "The last retrieval time should match."); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateEventFromMessage" /> /// method. /// </summary> /// [Test] public void CreateEventFromMessageAllowsAnEmptyMessage() { var message = AmqpMessage.Create(); Assert.That(() => new AmqpMessageConverter().CreateEventFromMessage(message), Throws.Nothing); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateEventFromMessage" /> /// method. /// </summary> /// [Test] public void CreateEventFromMessageAllowsAnEmptyMessageWithProperties() { var propertyValue = 1; var message = AmqpMessage.Create(); message.ApplicationProperties.Map.Add("Test", propertyValue); message.MessageAnnotations.Map.Add(AmqpProperty.Offset, propertyValue.ToString()); EventData eventData = new AmqpMessageConverter().CreateEventFromMessage(message); Assert.That(eventData, Is.Not.Null, "The event should have been created."); Assert.That(eventData.Properties.Count, Is.EqualTo(message.ApplicationProperties.Map.Count()), "There should have been properties present."); Assert.That(eventData.Properties.First().Value, Is.EqualTo(propertyValue), "The application property should have been populated."); Assert.That(eventData.Offset, Is.EqualTo(propertyValue), "The offset should have been populated."); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateMessageFromEvent" /> /// method. /// </summary> /// [Test] public void AnEventCanBeTranslatedToItself() { var sourceEvent = new EventData( eventBody: new byte[] { 0x11, 0x22, 0x33 }, properties: new Dictionary<string, object> { { "Test", 1234 } }); var converter = new AmqpMessageConverter(); using AmqpMessage message = converter.CreateMessageFromEvent(sourceEvent); EventData eventData = converter.CreateEventFromMessage(message); Assert.That(message, Is.Not.Null, "The AMQP message should have been created."); Assert.That(eventData, Is.Not.Null, "The translated event should have been created."); Assert.That(eventData.IsEquivalentTo(sourceEvent), "The translated event should match the source event."); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateEventHubPropertiesRequest" /> /// method. /// </summary> /// [Test] [TestCase(null)] [TestCase("")] public void CreateEventHubPropertiesRequestValidatesTheEventHub(string eventHubName) { ExactTypeConstraint typeConstraint = eventHubName is null ? Throws.ArgumentNullException : Throws.ArgumentException; var converter = new AmqpMessageConverter(); Assert.That(() => converter.CreateEventHubPropertiesRequest(eventHubName, "dummy"), typeConstraint); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateEventHubPropertiesRequest" /> /// method. /// </summary> /// [Test] [TestCase(null)] [TestCase("")] public void CreateEventHubPropertiesRequestValidatesTheToken(string token) { ExactTypeConstraint typeConstraint = token is null ? Throws.ArgumentNullException : Throws.ArgumentException; var converter = new AmqpMessageConverter(); Assert.That(() => converter.CreateEventHubPropertiesRequest("dummy", token), typeConstraint); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateEventHubPropertiesRequest" /> /// method. /// </summary> /// [Test] public void CreateEventHubPropertiesRequestCreatesTheRequest() { var eventHubName = "dummyName"; var token = "dummyToken"; var converter = new AmqpMessageConverter(); using AmqpMessage request = converter.CreateEventHubPropertiesRequest(eventHubName, token); Assert.That(request, Is.Not.Null, "The request should have been created"); Assert.That(request.ApplicationProperties, Is.Not.Null, "The request should have properties"); Assert.That(request.ApplicationProperties.Map.TryGetValue<string>(AmqpManagement.ResourceNameKey, out var resourceName), Is.True, "The resource name should be specified"); Assert.That(resourceName, Is.EqualTo(eventHubName), "The resource name should match"); Assert.That(request.ApplicationProperties.Map.TryGetValue<string>(AmqpManagement.SecurityTokenKey, out var securityToken), Is.True, "The security token should be specified"); Assert.That(securityToken, Is.EqualTo(token), "The security token should match"); Assert.That(request.ApplicationProperties.Map.TryGetValue<string>(AmqpManagement.OperationKey, out var operation), Is.True, "The operation should be specified"); Assert.That(operation, Is.EqualTo(AmqpManagement.ReadOperationValue), "The operation should match"); Assert.That(request.ApplicationProperties.Map.TryGetValue<string>(AmqpManagement.ResourceTypeKey, out var resourceScope), Is.True, "The resource scope be specified"); Assert.That(resourceScope, Is.EqualTo(AmqpManagement.EventHubResourceTypeValue), "The resource scope should match"); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateEventHubPropertiesFromResponse" /> /// method. /// </summary> /// [Test] public void CreateEventHubPropertiesFromResponseValidatesTheResponse() { var converter = new AmqpMessageConverter(); Assert.That(() => converter.CreateEventHubPropertiesFromResponse(null), Throws.ArgumentNullException); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateEventHubPropertiesFromResponse" /> /// method. /// </summary> /// [Test] public void CreateEventHubPropertiesFromResponseValidatesTheResponseDataIsPresent() { var converter = new AmqpMessageConverter(); using var response = AmqpMessage.Create(); Assert.That(() => converter.CreateEventHubPropertiesFromResponse(response), Throws.InstanceOf<InvalidOperationException>()); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateEventHubPropertiesFromResponse" /> /// method. /// </summary> /// [Test] public void CreateEventHubPropertiesFromResponseValidatesTheResponseDataType() { var converter = new AmqpMessageConverter(); using var response = AmqpMessage.Create(new Data { Value = new ArraySegment<byte>(new byte[] { 0x11, 0x22 }) }); Assert.That(() => converter.CreateEventHubPropertiesFromResponse(response), Throws.InstanceOf<InvalidOperationException>()); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreateEventHubPropertiesFromResponse" /> /// method. /// </summary> /// [Test] public void CreateEventHubPropertiesFromResponseCreatesTheProperties() { var name = "SomeName"; var created = DateTimeOffset.Parse("2015-10-27T00:00:00z"); var identifiers = new[] { "0", "1", "2" }; var converter = new AmqpMessageConverter(); var body = new AmqpMap { { AmqpManagement.ResponseMap.Name, name }, { AmqpManagement.ResponseMap.CreatedAt, created.UtcDateTime }, { AmqpManagement.ResponseMap.PartitionIdentifiers, identifiers } }; using var response = AmqpMessage.Create(new AmqpValue { Value = body }); Metadata.EventHubProperties properties = converter.CreateEventHubPropertiesFromResponse(response); Assert.That(properties, Is.Not.Null, "The properties should have been created"); Assert.That(properties.Name, Is.EqualTo(name), "The name should match"); Assert.That(properties.CreatedAt, Is.EqualTo(created), "The created date should match"); Assert.That(properties.PartitionIds, Is.EquivalentTo(identifiers), "The set of partition identifiers should match"); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreatePartitionPropertiesRequest" /> /// method. /// </summary> /// [Test] [TestCase(null)] [TestCase("")] public void CreatePartitionPropertiesRequestValidatesTheEventHub(string eventHubName) { ExactTypeConstraint typeConstraint = eventHubName is null ? Throws.ArgumentNullException : Throws.ArgumentException; var converter = new AmqpMessageConverter(); Assert.That(() => converter.CreatePartitionPropertiesRequest(eventHubName, "0", "dummy"), typeConstraint); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreatePartitionPropertiesRequest" /> /// method. /// </summary> /// [Test] [TestCase(null)] [TestCase("")] public void CreatePartitionPropertiesRequestValidatesThePartition(string partition) { ExactTypeConstraint typeConstraint = partition is null ? Throws.ArgumentNullException : Throws.ArgumentException; var converter = new AmqpMessageConverter(); Assert.That(() => converter.CreatePartitionPropertiesRequest("someHub", partition, "dummy"), typeConstraint); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreatePartitionPropertiesRequest" /> /// method. /// </summary> /// [Test] [TestCase(null)] [TestCase("")] public void CreatePartitionPropertiesRequestValidatesTheToken(string token) { ExactTypeConstraint typeConstraint = token is null ? Throws.ArgumentNullException : Throws.ArgumentException; var converter = new AmqpMessageConverter(); Assert.That(() => converter.CreatePartitionPropertiesRequest("someHub", "0", token), typeConstraint); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreatePartitionPropertiesRequest" /> /// method. /// </summary> /// [Test] public void CreatePartitionPropertiesRequestRequestCreatesTheRequest() { var eventHubName = "dummyName"; var partition = "2"; var token = "dummyToken"; var converter = new AmqpMessageConverter(); using AmqpMessage request = converter.CreatePartitionPropertiesRequest(eventHubName, partition, token); Assert.That(request, Is.Not.Null, "The request should have been created"); Assert.That(request.ApplicationProperties, Is.Not.Null, "The request should have properties"); Assert.That(request.ApplicationProperties.Map.TryGetValue<string>(AmqpManagement.ResourceNameKey, out var resourceName), Is.True, "The resource name should be specified"); Assert.That(resourceName, Is.EqualTo(eventHubName), "The resource name should match"); Assert.That(request.ApplicationProperties.Map.TryGetValue<string>(AmqpManagement.PartitionNameKey, out var partitionId), Is.True, "The resource name should be specified"); Assert.That(partitionId, Is.EqualTo(partition), "The partition should match"); Assert.That(request.ApplicationProperties.Map.TryGetValue<string>(AmqpManagement.SecurityTokenKey, out var securityToken), Is.True, "The security token should be specified"); Assert.That(securityToken, Is.EqualTo(token), "The security token should match"); Assert.That(request.ApplicationProperties.Map.TryGetValue<string>(AmqpManagement.OperationKey, out var operation), Is.True, "The operation should be specified"); Assert.That(operation, Is.EqualTo(AmqpManagement.ReadOperationValue), "The operation should match"); Assert.That(request.ApplicationProperties.Map.TryGetValue<string>(AmqpManagement.ResourceTypeKey, out var resourceScope), Is.True, "The resource scope be specified"); Assert.That(resourceScope, Is.EqualTo(AmqpManagement.PartitionResourceTypeValue), "The resource scope should match"); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreatePartitionPropertiesFromResponse" /> /// method. /// </summary> /// [Test] public void CreatePartitionPropertiesFromResponseValidatesTheResponse() { var converter = new AmqpMessageConverter(); Assert.That(() => converter.CreatePartitionPropertiesFromResponse(null), Throws.ArgumentNullException); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreatePartitionPropertiesFromResponse" /> /// method. /// </summary> /// [Test] public void CreatePartitionPropertiesFromResponseValidatesTheResponseDataIsPresent() { var converter = new AmqpMessageConverter(); using var response = AmqpMessage.Create(); Assert.That(() => converter.CreatePartitionPropertiesFromResponse(response), Throws.InstanceOf<InvalidOperationException>()); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreatePartitionPropertiesFromResponse" /> /// method. /// </summary> /// [Test] public void CreatePartitionPropertiesFromResponseValidatesTheResponseDataType() { var converter = new AmqpMessageConverter(); using var response = AmqpMessage.Create(new Data { Value = new ArraySegment<byte>(new byte[] { 0x11, 0x22 }) }); Assert.That(() => converter.CreatePartitionPropertiesFromResponse(response), Throws.InstanceOf<InvalidOperationException>()); } /// <summary> /// Verifies functionality of the <see cref="AmqpMessageConverter.CreatePartitionPropertiesFromResponse" /> /// method. /// </summary> /// [Test] public void CreatePartitionPropertiesFromResponseCreatesTheProperties() { var name = "SomeName"; var partition = "55"; var beginSequenceNumber = 555L; var lastSequenceNumber = 666L; var lastOffset = 777L; var lastEnqueueTime = DateTimeOffset.Parse("2015-10-27T00:00:00z"); var isEmpty = false; var converter = new AmqpMessageConverter(); var body = new AmqpMap { { AmqpManagement.ResponseMap.Name, name }, { AmqpManagement.ResponseMap.PartitionIdentifier, partition }, { AmqpManagement.ResponseMap.PartitionBeginSequenceNumber, beginSequenceNumber }, { AmqpManagement.ResponseMap.PartitionLastEnqueuedSequenceNumber, lastSequenceNumber }, { AmqpManagement.ResponseMap.PartitionLastEnqueuedOffset, lastOffset.ToString() }, { AmqpManagement.ResponseMap.PartitionLastEnqueuedTimeUtc, lastEnqueueTime.UtcDateTime }, { AmqpManagement.ResponseMap.PartitionRuntimeInfoPartitionIsEmpty, isEmpty } }; using var response = AmqpMessage.Create(new AmqpValue { Value = body }); PartitionProperties properties = converter.CreatePartitionPropertiesFromResponse(response); Assert.That(properties, Is.Not.Null, "The properties should have been created"); Assert.That(properties.EventHubName, Is.EqualTo(name), "The name should match"); Assert.That(properties.Id, Is.EqualTo(partition), "The partition should match"); Assert.That(properties.BeginningSequenceNumber, Is.EqualTo(beginSequenceNumber), "The beginning sequence number should match"); Assert.That(properties.LastEnqueuedSequenceNumber, Is.EqualTo(lastSequenceNumber), "The last sequence number should match"); Assert.That(properties.LastEnqueuedOffset, Is.EqualTo(lastOffset), "The offset should match"); Assert.That(properties.LastEnqueuedTime, Is.EqualTo(lastEnqueueTime), "The last enqueued time should match"); Assert.That(properties.IsEmpty, Is.EqualTo(isEmpty), "The empty flag should match"); } } }
50.495327
250
0.636538
[ "MIT" ]
LingyunSu/azure-sdk-for-net
sdk/eventhub/Azure.Messaging.EventHubs/tests/Amqp/AmqpMessageConverterTests.cs
75,644
C#
using chapter_11.Engine.Objects; using chapter_11.Engine.States; using chapter_11.States.Gameplay; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System.Collections.Generic; namespace chapter_11.Objects { public class ChopperSprite : BaseGameObject { private const float Speed = 4.0f; private const float BladeSpeed = 0.2f; // which chopper do we want from the texture private const int ChopperStartX = 0; private const int ChopperStartY = 0; private const int ChopperWidth = 44; private const int ChopperHeight = 98; // where are the blades on the texture private const int BladesStartX = 133; private const int BladesStartY = 98; private const int BladesWidth = 94; private const int BladesHeight = 94; // rotation center of the blades private const float BladesCenterX = 47.5f; private const float BladesCenterY = 47.5f; // positioning of the blades on the chopper private const int ChopperBladePosX = ChopperWidth / 2; private const int ChopperBladePosY = 34; // initial direction and speed of chopper private float _angle = 0.0f; private Vector2 _direction = new Vector2(0, 0); // track life total and age of chopper private int _age = 0; private int _life = 40; // chopper will flash red when hit private int _hitAt = 0; // bounding box. Note that since this chopper is rotated 180 degrees around its 0,0 origin, // this causes the bounding box to be further to the left and higher than the original texture coordinates private int BBPosX = -16; private int BBPosY = -63; private int BBWidth = 34; private int BBHeight = 98; private List<(int, Vector2)> _path; public ChopperSprite(Texture2D texture, List<(int, Vector2)> path) { _texture = texture; _path = path; AddBoundingBox(new Engine.Objects.BoundingBox(new Vector2(BBPosX, BBPosY), BBWidth, BBHeight)); } public void Update() { // Choppers follow a path where the direction changes at a certain frame, which is tracked by the chopper's age foreach(var p in _path) { int pAge = p.Item1; Vector2 pDirection = p.Item2; if (_age > pAge) { _direction = pDirection; } } Position = Position + (_direction * Speed); _age++; } public override void Render(SpriteBatch spriteBatch) { var chopperRect = new Rectangle(ChopperStartX, ChopperStartY, ChopperWidth, ChopperHeight); var chopperDestRect = new Rectangle(_position.ToPoint(), new Point(ChopperWidth, ChopperHeight)); var bladesRect = new Rectangle(BladesStartX, BladesStartY, BladesWidth, BladesHeight); var bladesDestRect = new Rectangle(_position.ToPoint(), new Point(BladesWidth, BladesHeight)); // if the chopper was just hit and is flashing, Color should alternate between OrangeRed and White var color = GetColor(); spriteBatch.Draw(_texture, chopperDestRect, chopperRect, color, MathHelper.Pi, new Vector2(ChopperBladePosX, ChopperBladePosY), SpriteEffects.None, 0f); spriteBatch.Draw(_texture, bladesDestRect, bladesRect, Color.White, _angle, new Vector2(BladesCenterX, BladesCenterY), SpriteEffects.None, 0f); _angle += BladeSpeed; } public override void OnNotify(BaseGameStateEvent gameEvent) { switch (gameEvent) { case GameplayEvents.ChopperHitBy m: JustHit(m.HitBy); SendEvent(new GameplayEvents.EnemyLostLife(_life)); break; } } private void JustHit(IGameObjectWithDamage o) { _hitAt = 0; _life -= o.Damage; } private Color GetColor() { var color = Color.White; foreach (var flashStartEndFrames in GetFlashStartEndFrames()) { if (_hitAt >= flashStartEndFrames.Item1 && _hitAt < flashStartEndFrames.Item2) { color = Color.OrangeRed; } } _hitAt++; return color; } private List<(int, int)> GetFlashStartEndFrames() { return new List<(int, int)> { (0, 3), (10, 13) }; } } }
34.463768
164
0.58894
[ "MIT" ]
Apress/monogame-mastery
chapter-11/start/Objects/ChopperSprite.cs
4,758
C#
// <copyright file="Container.cs" company="Automate The Planet Ltd."> // Copyright 2021 Automate The Planet Ltd. // Licensed under the Apache License, Version 2.0 (the "License"); // You may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // <author>Anton Angelov</author> // <site>https://bellatrix.solutions/</site> using System; using System.Diagnostics; using Bellatrix.Web.Events; namespace Bellatrix.Web.Controls { public class Container : Element { public Action Hover { get; set; } public Action Focus { get; set; } [DebuggerBrowsable(DebuggerBrowsableState.Never)] public Func<string> InnerText { get; set; } [DebuggerBrowsable(DebuggerBrowsableState.Never)] public Func<string> InnerHtml { get; set; } } }
37.875
85
0.719472
[ "Apache-2.0" ]
alexandrejulien/BELLATRIX
src/Bellatrix.Web/components/Container.cs
1,214
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ElementBohrModel : MonoBehaviour { public GameObject element; private bool elementSpawned = false; private float respawnTime = 30.0f; void OnTriggerEnter(Collider other) { if (other.gameObject.tag == "leftHand" || other.gameObject.tag == "rightHand") // 2 if (!elementSpawned) { Instantiate(element, transform.position + new Vector3(6,0,-6), transform.rotation); elementSpawned = true; StartCoroutine("Countdown", 10); } } //Allow Element to spawn after countdown private IEnumerator Countdown(int time) { while (time >= 0) { Debug.Log(time--); yield return new WaitForSeconds(1); } elementSpawned = false; Debug.Log("CountDown Complete: Can Spawn Element again"); } }
25.051282
99
0.593654
[ "MIT" ]
IantheFlyingHawaiian/CVRLabSJSU
Assets/Scripts/NewScripts/ElementBohrModel.cs
979
C#
using GameLibrary.Inventory; using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using TMPro; using GameLibrary; public class ItemLoader : MonoBehaviour { [SerializeField] private Image ItemImage; [SerializeField] public ItemType ItemType; [SerializeField] private ItemMapper ItemMapper; [SerializeField] private TMP_Text ItemNameLabel; public void OnEnable() { this.OnEquipmentChange(new CharacterEventArgs(LocalPlayer.Instance.Player.Character)); LocalPlayer.Instance.Player.Character.CharacterEquipmentChangeEvent += OnEquipmentChange; } private void SetNoItem() { ItemImage.sprite = ItemMapper.ItemSprites.Find(item => item.itemModel == ItemModel.NONE).itemSprite; ItemNameLabel.text = "Nothing"; } public void OnEquipmentChange(CharacterEventArgs eventArgs) { switch (this.ItemType) { case ItemType.HELMET: Debug.Log(LocalPlayer.Instance.Player.Character.Equipment.Helmet); if (LocalPlayer.Instance.Player.Character.Equipment.Helmet != null) { ItemImage.sprite = ItemMapper.ItemSprites.Find( item => item.itemModel == LocalPlayer.Instance.Player.Character.Equipment.Helmet.ItemModel).itemSprite; ItemNameLabel.text = LocalPlayer.Instance.Player.Character.Equipment.Helmet.Name; break; } SetNoItem(); break; case ItemType.BODY: if (LocalPlayer.Instance.Player.Character.Equipment.BodyItem != null) { ItemImage.sprite = ItemMapper.ItemSprites.Find( item => item.itemModel == LocalPlayer.Instance.Player.Character.Equipment.BodyItem.ItemModel).itemSprite; ItemNameLabel.text = LocalPlayer.Instance.Player.Character.Equipment.BodyItem.Name; break; } SetNoItem(); break; case ItemType.LEGS: if (LocalPlayer.Instance.Player.Character.Equipment.LegItem != null) { ItemImage.sprite = ItemMapper.ItemSprites.Find( item => item.itemModel == LocalPlayer.Instance.Player.Character.Equipment.LegItem.ItemModel).itemSprite; ItemNameLabel.text = LocalPlayer.Instance.Player.Character.Equipment.LegItem.Name; break; } SetNoItem(); break; case ItemType.BOOTS: if (LocalPlayer.Instance.Player.Character.Equipment.Boots != null) { ItemImage.sprite = ItemMapper.ItemSprites.Find( item => item.itemModel == LocalPlayer.Instance.Player.Character.Equipment.Boots.ItemModel).itemSprite; ItemNameLabel.text = LocalPlayer.Instance.Player.Character.Equipment.Boots.Name; break; } SetNoItem(); break; case ItemType.WEAPON: if (LocalPlayer.Instance.Player.Character.Equipment.Weapon != null) { ItemImage.sprite = ItemMapper.ItemSprites.Find( item => item.itemModel == LocalPlayer.Instance.Player.Character.Equipment.Weapon.ItemModel).itemSprite; ItemNameLabel.text = LocalPlayer.Instance.Player.Character.Equipment.Weapon.Name; break; } SetNoItem(); break; default: ItemImage= null; ItemNameLabel.text = "Undefined"; break; } } }
39.57732
127
0.58583
[ "MIT" ]
4rgetlahm/Object-Group-Game
Unity/Assets/Scripts/Items/ItemLoader.cs
3,839
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConvertSpeedUnits { class Program { static void Main(string[] args) { int distanceInMeters = int.Parse (Console.ReadLine()); int hours = int.Parse(Console.ReadLine()); int minutes = int.Parse(Console.ReadLine()); int seconds = int.Parse(Console.ReadLine()); float speedInMetersPerSecond = (float) (distanceInMeters / ((hours * 3600m) + (minutes * 60m) + (seconds))); Console.WriteLine(speedInMetersPerSecond); float speedInKmPerHour = (float) ((distanceInMeters * 0.001m) / (hours + (minutes / 60m) + (seconds / 3600m))); Console.WriteLine(speedInKmPerHour); float speedInMilesPerHour = (float) ((distanceInMeters / 1609f) / (hours + (minutes / 60f) + (seconds / 3600f))); Console.WriteLine(speedInMilesPerHour); } } }
33.566667
125
0.622642
[ "MIT" ]
MiraNedeva/SoftUni
Programming Fundamentals C#/1.Data Types And Variables-Exercices/Convert Speed Units/Program.cs
1,009
C#
using UnityEngine; public class BossSpriteController : MonoBehaviour { public GameplayStateManager GameplayStateManager; private void OnTriggerEnter2D(Collider2D collision) { var playerController = collision.GetComponentInParent<PlayerController>(); if (playerController != null) { this.GameplayStateManager.EndGame(GameOverState.Death, null); } } }
23.9375
77
0.759791
[ "MIT" ]
ThiagoDAraujoS/GGJ2021
Assets/Scripts/Boss/BossSpriteController.cs
385
C#
using System; using Newtonsoft.Json; using System.Xml.Serialization; namespace Essensoft.AspNetCore.Payment.Alipay.Domain { /// <summary> /// AlipayOpenMiniSetintentiondataSetModel Data Structure. /// </summary> [Serializable] public class AlipayOpenMiniSetintentiondataSetModel : AlipayObject { /// <summary> /// 本次更新动作类型,put:新增或覆盖,remove:删除 /// </summary> [JsonProperty("action")] [XmlElement("action")] public string Action { get; set; } /// <summary> /// 当前批次的唯一编号,对应本批次上传的多条意图数据,开发者自定义 /// </summary> [JsonProperty("batch_no")] [XmlElement("batch_no")] public string BatchNo { get; set; } /// <summary> /// 用于标识数据所属的服务类目 /// </summary> [JsonProperty("category")] [XmlElement("category")] public string Category { get; set; } /// <summary> /// 推送到服务库的数据列表,json array格式的字符串 /// </summary> [JsonProperty("data")] [XmlElement("data")] public string Data { get; set; } } }
26.119048
70
0.571559
[ "MIT" ]
ciker/PayMent-Core
src/Essensoft.AspNetCore.Payment.Alipay/Domain/AlipayOpenMiniSetintentiondataSetModel.cs
1,247
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.GoogleNative.Compute.Alpha { /// <summary> /// Creates a TargetHttpsProxy resource in the specified project and region using the data included in the request. /// </summary> [GoogleNativeResourceType("google-native:compute/alpha:RegionTargetHttpsProxy")] public partial class RegionTargetHttpsProxy : Pulumi.CustomResource { /// <summary> /// Optional. A URL referring to a networksecurity.AuthorizationPolicy resource that describes how the proxy should authorize inbound traffic. If left blank, access will not be restricted by an authorization policy. Refer to the AuthorizationPolicy resource for additional details. authorizationPolicy only applies to a global TargetHttpsProxy attached to globalForwardingRules with the loadBalancingScheme set to INTERNAL_SELF_MANAGED. Note: This field currently has no impact. /// </summary> [Output("authorizationPolicy")] public Output<string> AuthorizationPolicy { get; private set; } = null!; /// <summary> /// URL of a certificate map that identifies a certificate map associated with the given target proxy. This field can only be set for global target proxies. If set, sslCertificates will be ignored. /// </summary> [Output("certificateMap")] public Output<string> CertificateMap { get; private set; } = null!; /// <summary> /// Creation timestamp in RFC3339 text format. /// </summary> [Output("creationTimestamp")] public Output<string> CreationTimestamp { get; private set; } = null!; /// <summary> /// An optional description of this resource. Provide this property when you create the resource. /// </summary> [Output("description")] public Output<string> Description { get; private set; } = null!; /// <summary> /// Fingerprint of this resource. A hash of the contents stored in this object. This field is used in optimistic locking. This field will be ignored when inserting a TargetHttpsProxy. An up-to-date fingerprint must be provided in order to patch the TargetHttpsProxy; otherwise, the request will fail with error 412 conditionNotMet. To see the latest fingerprint, make a get() request to retrieve the TargetHttpsProxy. /// </summary> [Output("fingerprint")] public Output<string> Fingerprint { get; private set; } = null!; /// <summary> /// URLs to networkservices.HttpFilter resources enabled for xDS clients using this configuration. For example, https://networkservices.googleapis.com/beta/projects/project/locations/ locationhttpFilters/httpFilter Only filters that handle outbound connection and stream events may be specified. These filters work in conjunction with a default set of HTTP filters that may already be configured by Traffic Director. Traffic Director will determine the final location of these filters within xDS configuration based on the name of the HTTP filter. If Traffic Director positions multiple filters at the same location, those filters will be in the same order as specified in this list. httpFilters only applies for loadbalancers with loadBalancingScheme set to INTERNAL_SELF_MANAGED. See ForwardingRule for more details. /// </summary> [Output("httpFilters")] public Output<ImmutableArray<string>> HttpFilters { get; private set; } = null!; /// <summary> /// Type of resource. Always compute#targetHttpsProxy for target HTTPS proxies. /// </summary> [Output("kind")] public Output<string> Kind { get; private set; } = null!; /// <summary> /// Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// This field only applies when the forwarding rule that references this target proxy has a loadBalancingScheme set to INTERNAL_SELF_MANAGED. When this field is set to true, Envoy proxies set up inbound traffic interception and bind to the IP address and port specified in the forwarding rule. This is generally useful when using Traffic Director to configure Envoy as a gateway or middle proxy (in other words, not a sidecar proxy). The Envoy proxy listens for inbound requests and handles requests when it receives them. The default is false. /// </summary> [Output("proxyBind")] public Output<bool> ProxyBind { get; private set; } = null!; /// <summary> /// Specifies the QUIC override policy for this TargetHttpsProxy resource. This setting determines whether the load balancer attempts to negotiate QUIC with clients. You can specify NONE, ENABLE, or DISABLE. - When quic-override is set to NONE, Google manages whether QUIC is used. - When quic-override is set to ENABLE, the load balancer uses QUIC when possible. - When quic-override is set to DISABLE, the load balancer doesn't use QUIC. - If the quic-override flag is not specified, NONE is implied. /// </summary> [Output("quicOverride")] public Output<string> QuicOverride { get; private set; } = null!; /// <summary> /// URL of the region where the regional TargetHttpsProxy resides. This field is not applicable to global TargetHttpsProxies. /// </summary> [Output("region")] public Output<string> Region { get; private set; } = null!; /// <summary> /// Server-defined URL for the resource. /// </summary> [Output("selfLink")] public Output<string> SelfLink { get; private set; } = null!; /// <summary> /// Server-defined URL for this resource with the resource id. /// </summary> [Output("selfLinkWithId")] public Output<string> SelfLinkWithId { get; private set; } = null!; /// <summary> /// Optional. A URL referring to a networksecurity.ServerTlsPolicy resource that describes how the proxy should authenticate inbound traffic. serverTlsPolicy only applies to a global TargetHttpsProxy attached to globalForwardingRules with the loadBalancingScheme set to INTERNAL_SELF_MANAGED. If left blank, communications are not encrypted. Note: This field currently has no impact. /// </summary> [Output("serverTlsPolicy")] public Output<string> ServerTlsPolicy { get; private set; } = null!; /// <summary> /// URLs to SslCertificate resources that are used to authenticate connections between users and the load balancer. At least one SSL certificate must be specified. Currently, you may specify up to 15 SSL certificates. sslCertificates do not apply when the load balancing scheme is set to INTERNAL_SELF_MANAGED. /// </summary> [Output("sslCertificates")] public Output<ImmutableArray<string>> SslCertificates { get; private set; } = null!; /// <summary> /// URL of SslPolicy resource that will be associated with the TargetHttpsProxy resource. If not set, the TargetHttpsProxy resource has no SSL policy configured. /// </summary> [Output("sslPolicy")] public Output<string> SslPolicy { get; private set; } = null!; /// <summary> /// A fully-qualified or valid partial URL to the UrlMap resource that defines the mapping from URL to the BackendService. For example, the following are all valid URLs for specifying a URL map: - https://www.googleapis.compute/v1/projects/project/global/urlMaps/ url-map - projects/project/global/urlMaps/url-map - global/urlMaps/url-map /// </summary> [Output("urlMap")] public Output<string> UrlMap { get; private set; } = null!; /// <summary> /// Create a RegionTargetHttpsProxy resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public RegionTargetHttpsProxy(string name, RegionTargetHttpsProxyArgs args, CustomResourceOptions? options = null) : base("google-native:compute/alpha:RegionTargetHttpsProxy", name, args ?? new RegionTargetHttpsProxyArgs(), MakeResourceOptions(options, "")) { } private RegionTargetHttpsProxy(string name, Input<string> id, CustomResourceOptions? options = null) : base("google-native:compute/alpha:RegionTargetHttpsProxy", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing RegionTargetHttpsProxy resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static RegionTargetHttpsProxy Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new RegionTargetHttpsProxy(name, id, options); } } public sealed class RegionTargetHttpsProxyArgs : Pulumi.ResourceArgs { /// <summary> /// Optional. A URL referring to a networksecurity.AuthorizationPolicy resource that describes how the proxy should authorize inbound traffic. If left blank, access will not be restricted by an authorization policy. Refer to the AuthorizationPolicy resource for additional details. authorizationPolicy only applies to a global TargetHttpsProxy attached to globalForwardingRules with the loadBalancingScheme set to INTERNAL_SELF_MANAGED. Note: This field currently has no impact. /// </summary> [Input("authorizationPolicy")] public Input<string>? AuthorizationPolicy { get; set; } /// <summary> /// URL of a certificate map that identifies a certificate map associated with the given target proxy. This field can only be set for global target proxies. If set, sslCertificates will be ignored. /// </summary> [Input("certificateMap")] public Input<string>? CertificateMap { get; set; } /// <summary> /// An optional description of this resource. Provide this property when you create the resource. /// </summary> [Input("description")] public Input<string>? Description { get; set; } [Input("httpFilters")] private InputList<string>? _httpFilters; /// <summary> /// URLs to networkservices.HttpFilter resources enabled for xDS clients using this configuration. For example, https://networkservices.googleapis.com/beta/projects/project/locations/ locationhttpFilters/httpFilter Only filters that handle outbound connection and stream events may be specified. These filters work in conjunction with a default set of HTTP filters that may already be configured by Traffic Director. Traffic Director will determine the final location of these filters within xDS configuration based on the name of the HTTP filter. If Traffic Director positions multiple filters at the same location, those filters will be in the same order as specified in this list. httpFilters only applies for loadbalancers with loadBalancingScheme set to INTERNAL_SELF_MANAGED. See ForwardingRule for more details. /// </summary> public InputList<string> HttpFilters { get => _httpFilters ?? (_httpFilters = new InputList<string>()); set => _httpFilters = value; } /// <summary> /// Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. /// </summary> [Input("name")] public Input<string>? Name { get; set; } [Input("project")] public Input<string>? Project { get; set; } /// <summary> /// This field only applies when the forwarding rule that references this target proxy has a loadBalancingScheme set to INTERNAL_SELF_MANAGED. When this field is set to true, Envoy proxies set up inbound traffic interception and bind to the IP address and port specified in the forwarding rule. This is generally useful when using Traffic Director to configure Envoy as a gateway or middle proxy (in other words, not a sidecar proxy). The Envoy proxy listens for inbound requests and handles requests when it receives them. The default is false. /// </summary> [Input("proxyBind")] public Input<bool>? ProxyBind { get; set; } /// <summary> /// Specifies the QUIC override policy for this TargetHttpsProxy resource. This setting determines whether the load balancer attempts to negotiate QUIC with clients. You can specify NONE, ENABLE, or DISABLE. - When quic-override is set to NONE, Google manages whether QUIC is used. - When quic-override is set to ENABLE, the load balancer uses QUIC when possible. - When quic-override is set to DISABLE, the load balancer doesn't use QUIC. - If the quic-override flag is not specified, NONE is implied. /// </summary> [Input("quicOverride")] public Input<Pulumi.GoogleNative.Compute.Alpha.RegionTargetHttpsProxyQuicOverride>? QuicOverride { get; set; } [Input("region", required: true)] public Input<string> Region { get; set; } = null!; [Input("requestId")] public Input<string>? RequestId { get; set; } /// <summary> /// Optional. A URL referring to a networksecurity.ServerTlsPolicy resource that describes how the proxy should authenticate inbound traffic. serverTlsPolicy only applies to a global TargetHttpsProxy attached to globalForwardingRules with the loadBalancingScheme set to INTERNAL_SELF_MANAGED. If left blank, communications are not encrypted. Note: This field currently has no impact. /// </summary> [Input("serverTlsPolicy")] public Input<string>? ServerTlsPolicy { get; set; } [Input("sslCertificates")] private InputList<string>? _sslCertificates; /// <summary> /// URLs to SslCertificate resources that are used to authenticate connections between users and the load balancer. At least one SSL certificate must be specified. Currently, you may specify up to 15 SSL certificates. sslCertificates do not apply when the load balancing scheme is set to INTERNAL_SELF_MANAGED. /// </summary> public InputList<string> SslCertificates { get => _sslCertificates ?? (_sslCertificates = new InputList<string>()); set => _sslCertificates = value; } /// <summary> /// URL of SslPolicy resource that will be associated with the TargetHttpsProxy resource. If not set, the TargetHttpsProxy resource has no SSL policy configured. /// </summary> [Input("sslPolicy")] public Input<string>? SslPolicy { get; set; } /// <summary> /// A fully-qualified or valid partial URL to the UrlMap resource that defines the mapping from URL to the BackendService. For example, the following are all valid URLs for specifying a URL map: - https://www.googleapis.compute/v1/projects/project/global/urlMaps/ url-map - projects/project/global/urlMaps/url-map - global/urlMaps/url-map /// </summary> [Input("urlMap")] public Input<string>? UrlMap { get; set; } public RegionTargetHttpsProxyArgs() { } } }
67.404669
826
0.695607
[ "Apache-2.0" ]
AaronFriel/pulumi-google-native
sdk/dotnet/Compute/Alpha/RegionTargetHttpsProxy.cs
17,323
C#
using System.Collections.Generic; using System.Collections.ObjectModel; namespace WEBAPI.Areas.HelpPage.ModelDescriptions { public class EnumTypeModelDescription : ModelDescription { public EnumTypeModelDescription() { Values = new Collection<EnumValueDescription>(); } public Collection<EnumValueDescription> Values { get; private set; } } }
26.666667
76
0.705
[ "MIT" ]
marwenbhz/MULTITENANT
WEBAPI/Areas/HelpPage/ModelDescriptions/EnumTypeModelDescription.cs
400
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Azure.Devices.Client; using Microsoft.Azure.Devices.Provisioning.Client; using Microsoft.Azure.Devices.Provisioning.Client.Transport; using Microsoft.Azure.Devices.Shared; using System; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; namespace SymmetricKeySimulatedDevice { class Program { // //////////////////////////////////////////////////////// // Azure Device Provisioning Service (DPS) ID Scope private static string dpsIdScope = ""; // Registration ID private static string registrationId = "DPSSimulatedDevice1"; // Individual Enrollment Primary Key private const string individualEnrollmentPrimaryKey = ""; // Individual Enrollment Secondary Key private const string individualEnrollmentSecondaryKey = ""; // //////////////////////////////////////////////////////// private const string GlobalDeviceEndpoint = "global.azure-devices-provisioning.net"; public static int Main(string[] args) { if (string.IsNullOrWhiteSpace(dpsIdScope) && (args.Length > 0)) { dpsIdScope = args[0]; } if (string.IsNullOrWhiteSpace(dpsIdScope)) { Console.WriteLine("ProvisioningDeviceClientSymmetricKey <IDScope>"); return 1; } string primaryKey = string.Empty; string secondaryKey = string.Empty; if (!String.IsNullOrEmpty(registrationId) && !String.IsNullOrEmpty(individualEnrollmentPrimaryKey) && !String.IsNullOrEmpty(individualEnrollmentSecondaryKey)) { //Individual enrollment flow, the primary and secondary keys are the same as the individual enrollment keys primaryKey = individualEnrollmentPrimaryKey; secondaryKey = individualEnrollmentSecondaryKey; } else { Console.WriteLine("Invalid configuration provided, must provide individual enrollment keys"); return -1; } using (var security = new SecurityProviderSymmetricKey(registrationId, primaryKey, secondaryKey)) using (var transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.TcpOnly)) { ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create(GlobalDeviceEndpoint, dpsIdScope, security, transport); var provisioningDeviceLogic = new ProvisioningDeviceLogic(provClient, security); provisioningDeviceLogic.RunAsync().GetAwaiter().GetResult(); } return 0; } } public class ProvisioningDeviceLogic { #region Constructor readonly ProvisioningDeviceClient _provClient; readonly SecurityProvider _security; DeviceClient iotClient; // Delay between Telemetry readings in Seconds (default to 1 second) private int _telemetryDelay = 1; public ProvisioningDeviceLogic(ProvisioningDeviceClient provisioningDeviceClient, SecurityProvider security) { _provClient = provisioningDeviceClient; _security = security; } #endregion public async Task RunAsync() { Console.WriteLine($"RegistrationID = {_security.GetRegistrationID()}"); Console.Write("ProvisioningClient RegisterAsync . . . "); DeviceRegistrationResult result = await _provClient.RegisterAsync().ConfigureAwait(false); Console.WriteLine($"Device Registration Status: {result.Status}"); Console.WriteLine($"ProvisioningClient AssignedHub: {result.AssignedHub}; DeviceID: {result.DeviceId}"); if (result.Status != ProvisioningRegistrationStatusType.Assigned) { throw new Exception($"DeviceRegistrationResult.Status is NOT 'Assigned'"); } Console.WriteLine("Creating Symmetric Key DeviceClient authentication"); IAuthenticationMethod auth = new DeviceAuthenticationWithRegistrySymmetricKey(result.DeviceId, (_security as SecurityProviderSymmetricKey).GetPrimaryKey()); Console.WriteLine("Simulated Device. Ctrl-C to exit."); using (iotClient = DeviceClient.Create(result.AssignedHub, auth, TransportType.Amqp)) { Console.WriteLine("DeviceClient OpenAsync."); await iotClient.OpenAsync().ConfigureAwait(false); // TODO 1: Setup OnDesiredPropertyChanged Event Handling Console.WriteLine("Connecting SetDesiredPropertyUpdateCallbackAsync event handler..."); await iotClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertyChanged, null).ConfigureAwait(false); // TODO 2: Load Device Twin Properties Console.WriteLine("Loading Device Twin Properties..."); var twin = await iotClient.GetTwinAsync().ConfigureAwait(false); await OnDesiredPropertyChanged(twin.Properties.Desired, null); // Start reading and sending device telemetry Console.WriteLine("Start reading and sending device telemetry..."); await SendDeviceToCloudMessagesAsync(iotClient); //Console.WriteLine("DeviceClient CloseAsync."); //await iotClient.CloseAsync().ConfigureAwait(false); } } private async Task OnDesiredPropertyChanged(TwinCollection desiredProperties, object userContext) { Console.WriteLine("Desired Twin Property Changed:"); Console.WriteLine($"{desiredProperties.ToJson()}"); // Read the desired Twin Properties if (desiredProperties.Contains("telemetryDelay")) { string desiredTelemetryDelay = desiredProperties["telemetryDelay"]; if (desiredTelemetryDelay != null) { this._telemetryDelay = int.Parse(desiredTelemetryDelay); } // if desired telemetryDelay is null or unspecified, don't change it } // Report Twin Properties var reportedProperties = new TwinCollection(); reportedProperties["telemetryDelay"] = this._telemetryDelay; await iotClient.UpdateReportedPropertiesAsync(reportedProperties).ConfigureAwait(false); Console.WriteLine("Reported Twin Properties:"); Console.WriteLine($"{reportedProperties.ToJson()}"); } private async Task SendDeviceToCloudMessagesAsync(DeviceClient deviceClient) { // Initial telemetry values double minTemperature = 20; double minHumidity = 60; double minPressure = 1013.25; double minLatitude = 39.810492; double minLongitude = -98.556061; Random rand = new Random(); while (true) { double currentTemperature = minTemperature + rand.NextDouble() * 15; double currentHumidity = minHumidity + rand.NextDouble() * 20; double currentPressure = minPressure + rand.NextDouble() * 12; double currentLatitude = minLatitude + rand.NextDouble() * 0.5; double currentLongitude = minLongitude + rand.NextDouble() * 0.5; // Create JSON message var telemetryDataPoint = new { temperature = currentTemperature, humidity = currentHumidity, pressure = currentPressure, latitude = currentLatitude, longitude = currentLongitude }; var messageString = JsonConvert.SerializeObject(telemetryDataPoint); var message = new Message(Encoding.ASCII.GetBytes(messageString)); // Add a custom application property to the message. // An IoT hub can filter on these properties without access to the message body. message.Properties.Add("temperatureAlert", (currentTemperature > 30) ? "true" : "false"); // Send the telemetry message await deviceClient.SendEventAsync(message); Console.WriteLine("{0} > Sending message: {1}", DateTime.Now, messageString); // Delay before next Telemetry reading await Task.Delay(this._telemetryDelay * 1000); } } } }
41.166667
170
0.617859
[ "MIT" ]
AzureMentor/AZ-220-Microsoft-Azure-IoT-Developer
MSLearn/Modules/L05-individual-enrollment-of-device-in-dps/LabFiles-Completed/Program.cs
8,894
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Ms.V20180408.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class ShieldInfo : AbstractModel { /// <summary> /// 加固结果的返回码 /// </summary> [JsonProperty("ShieldCode")] public ulong? ShieldCode{ get; set; } /// <summary> /// 加固后app的大小 /// </summary> [JsonProperty("ShieldSize")] public ulong? ShieldSize{ get; set; } /// <summary> /// 加固后app的md5 /// </summary> [JsonProperty("ShieldMd5")] public string ShieldMd5{ get; set; } /// <summary> /// 加固后的APP下载地址 /// </summary> [JsonProperty("AppUrl")] public string AppUrl{ get; set; } /// <summary> /// 加固的提交时间 /// </summary> [JsonProperty("TaskTime")] public ulong? TaskTime{ get; set; } /// <summary> /// 任务唯一标识 /// </summary> [JsonProperty("ItemId")] public string ItemId{ get; set; } /// <summary> /// 加固版本,basic基础版,professional专业版 /// </summary> [JsonProperty("ServiceEdition")] public string ServiceEdition{ get; set; } /// <summary> /// 内部实现,用户禁止调用 /// </summary> internal override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "ShieldCode", this.ShieldCode); this.SetParamSimple(map, prefix + "ShieldSize", this.ShieldSize); this.SetParamSimple(map, prefix + "ShieldMd5", this.ShieldMd5); this.SetParamSimple(map, prefix + "AppUrl", this.AppUrl); this.SetParamSimple(map, prefix + "TaskTime", this.TaskTime); this.SetParamSimple(map, prefix + "ItemId", this.ItemId); this.SetParamSimple(map, prefix + "ServiceEdition", this.ServiceEdition); } } }
30.523256
85
0.592762
[ "Apache-2.0" ]
geffzhang/tencentcloud-sdk-dotnet
TencentCloud/Ms/V20180408/Models/ShieldInfo.cs
2,749
C#
using CadEditor; using System; //css_include shared_settings/SharedUtils.cs; //css_include shared_settings/BlockUtils.cs; public class Data { public OffsetRec getScreensOffset() { return new OffsetRec(0x7323, 1 , 16*15, 16, 15); } public bool isBigBlockEditorEnabled() { return false; } public bool isBlockEditorEnabled() { return true; } public bool isEnemyEditorEnabled() { return false; } public GetVideoPageAddrFunc getVideoPageAddrFunc() { return SharedUtils.fakeVideoAddr(); } public GetVideoChunkFunc getVideoChunkFunc() { return SharedUtils.getVideoChunk("chr-copy.bin"); } public SetVideoChunkFunc setVideoChunkFunc() { return null; } public bool isBuildScreenFromSmallBlocks() { return true; } public OffsetRec getBlocksOffset() { return new OffsetRec(0x7187, 1 , 0x1000); } public int getBlocksCount() { return 256; } public int getBigBlocksCount() { return 256; } public int getPalBytesAddr() { return 0x72b7; } public GetBlocksFunc getBlocksFunc() { return BlockUtils.getBlocksLinear2x2Masked;} public SetBlocksFunc setBlocksFunc() { return BlockUtils.setBlocksLinear2x2Masked;} public GetPalFunc getPalFunc() { return SharedUtils.readPalFromBin(new[] {"pal-copy.bin"}); } public SetPalFunc setPalFunc() { return null;} }
48.034483
115
0.69921
[ "MIT" ]
spiiin/CadEditor
CadEditor/settings_nes/happily_ever_after_unl/Settings_HappilyEverAfter-copyright2.cs
1,393
C#
using System; using System.Text; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; namespace IO.Swagger.Model { /// <summary> /// /// </summary> [DataContract] public class PartsGetBendTableResponse200 { /// <summary> /// Gets or Sets Table /// </summary> [DataMember(Name="table", EmitDefaultValue=false)] [JsonProperty(PropertyName = "table")] public PartsGetBendTableResponse200Table Table { get; set; } /// <summary> /// The document microversion /// </summary> /// <value>The document microversion</value> [DataMember(Name="sourceMicroversion", EmitDefaultValue=false)] [JsonProperty(PropertyName = "sourceMicroversion")] public string SourceMicroversion { get; set; } /// <summary> /// Get the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class PartsGetBendTableResponse200 {\n"); sb.Append(" Table: ").Append(Table).Append("\n"); sb.Append(" SourceMicroversion: ").Append(SourceMicroversion).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Get the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } } }
28.907407
82
0.661115
[ "MIT" ]
OnShape-MR/Onshape-For-Mixed-Reality
Assets/OnShape/API/Model/PartsGetBendTableResponse200.cs
1,561
C#
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.OpenApi.Models; namespace WebApi { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddMvcCore().AddApiExplorer(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Documentation API", Version = "v1" }); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseSwagger(); app.UseSwaggerUI(opt => { //opt.SwaggerEndpoint("/api/documentation/swagger.json", "Documentation API V1"); opt.SwaggerEndpoint("/swagger/v1/swagger.json", "Documentation API V1"); }); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
30.508475
107
0.572778
[ "MIT" ]
livcunhabezerra/desafio-csharp-easy-level
ProjetoSiagri/WebApi/Startup.cs
1,800
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using JohnLambe.Util.Collections; using System.Reflection; using JohnLambe.Util.Reflection; namespace JohnLambe.Tests.JLUtilsTest.Reflection { [TestClass] public class PropertyInfoExtensionTest { #region SetValueConverted [TestMethod] public void SetValueConverted_IntToString() { // Arrange: PropertyInfo pi = typeof(TestTargetClass).GetProperty("StrProperty"); var obj = new TestTargetClass(); // Act: pi.SetValueConverted(obj, 123); // Assert: Assert.AreEqual("123", obj.StrProperty); } [TestMethod] public void SetValueConverted_StringToLong() { // Arrange: PropertyInfo pi = typeof(TestTargetClass).GetProperty("LongProperty"); var obj = new TestTargetClass(); // Act: pi.SetValueConverted(obj, "10000000000"); // Assert: Assert.AreEqual(10000000000, obj.LongProperty); } [TestMethod] public void SetValueConverted_BoolToString() { // Arrange: PropertyInfo pi = typeof(TestTargetClass).GetProperty("StrProperty"); var obj = new TestTargetClass(); // Act: pi.SetValueConverted(obj, true); // Assert: Assert.AreEqual("True", obj.StrProperty); } [TestMethod] public void SetValueConverted_ObjectToString() { // Arrange: PropertyInfo pi = typeof(TestTargetClass).GetProperty("StrProperty"); var obj = new TestTargetClass(); // Act: pi.SetValueConverted(obj, obj); Console.WriteLine(obj.ToString()); // Assert: Assert.AreEqual(obj.ToString(), obj.StrProperty); } #endregion #region GetValueConverted [TestMethod] public void GetValueConverted_StringToInt() { // Arrange: PropertyInfo pi = typeof(TestTargetClass).GetProperty("StrProperty"); var obj = new TestTargetClass() { StrProperty = "5678" }; // Act / Assert: Assert.AreEqual(5678,pi.GetValueConverted<int>(obj)); } [TestMethod] public void GetValueConverted_LongToString() { // Arrange: PropertyInfo pi = typeof(TestTargetClass).GetProperty("LongProperty"); var obj = new TestTargetClass() { LongProperty = 5000000000000 }; // Act / Assert: Assert.AreEqual("5000000000000", pi.GetValueConverted<string>(obj)); } #endregion public class TestTargetClass { public string StrProperty { get; set; } public long LongProperty { get; set; } } } }
26.692308
82
0.56196
[ "MIT" ]
JohnLambe/JLCSUtils
JLCSUtils/JLUtilsTest/Reflection/PropertyInfoExtensionTest.cs
3,125
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable disable using System.Collections.Generic; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.UserInterface; using osu.Game.Beatmaps.Timing; using osu.Game.Rulesets.Scoring; using osu.Game.Screens.Play.Break; namespace osu.Game.Screens.Play { public class BreakOverlay : Container { /// <summary> /// The duration of the break overlay fading. /// </summary> public const double BREAK_FADE_DURATION = BreakPeriod.MIN_BREAK_DURATION / 2; private const float remaining_time_container_max_size = 0.3f; private const int vertical_margin = 25; private readonly Container fadeContainer; private IReadOnlyList<BreakPeriod> breaks; public IReadOnlyList<BreakPeriod> Breaks { get => breaks; set { breaks = value; if (IsLoaded) initializeBreaks(); } } public override bool RemoveCompletedTransforms => false; private readonly Container remainingTimeAdjustmentBox; private readonly Container remainingTimeBox; private readonly RemainingTimeCounter remainingTimeCounter; private readonly BreakArrows breakArrows; public BreakOverlay(bool letterboxing, ScoreProcessor scoreProcessor) { RelativeSizeAxes = Axes.Both; BreakInfo info; Child = fadeContainer = new Container { Alpha = 0, RelativeSizeAxes = Axes.Both, Children = new Drawable[] { new LetterboxOverlay { Alpha = letterboxing ? 1 : 0, Anchor = Anchor.Centre, Origin = Anchor.Centre, }, remainingTimeAdjustmentBox = new Container { Anchor = Anchor.Centre, Origin = Anchor.Centre, AutoSizeAxes = Axes.Y, RelativeSizeAxes = Axes.X, Width = 0, Child = remainingTimeBox = new Container { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.X, Height = 8, CornerRadius = 4, Masking = true, Child = new Box { RelativeSizeAxes = Axes.Both } } }, remainingTimeCounter = new RemainingTimeCounter { Anchor = Anchor.Centre, Origin = Anchor.BottomCentre, Margin = new MarginPadding { Bottom = vertical_margin }, }, info = new BreakInfo { Anchor = Anchor.Centre, Origin = Anchor.TopCentre, Margin = new MarginPadding { Top = vertical_margin }, }, breakArrows = new BreakArrows { Anchor = Anchor.Centre, Origin = Anchor.Centre, } } }; if (scoreProcessor != null) { info.AccuracyDisplay.Current.BindTo(scoreProcessor.Accuracy); info.GradeDisplay.Current.BindTo(scoreProcessor.Rank); } } protected override void LoadComplete() { base.LoadComplete(); initializeBreaks(); } private void initializeBreaks() { FinishTransforms(true); Scheduler.CancelDelayedTasks(); if (breaks == null) return; // we need breaks. foreach (var b in breaks) { if (!b.HasEffect) continue; using (BeginAbsoluteSequence(b.StartTime)) { fadeContainer.FadeIn(BREAK_FADE_DURATION); breakArrows.Show(BREAK_FADE_DURATION); remainingTimeAdjustmentBox .ResizeWidthTo(remaining_time_container_max_size, BREAK_FADE_DURATION, Easing.OutQuint) .Delay(b.Duration - BREAK_FADE_DURATION) .ResizeWidthTo(0); remainingTimeBox .ResizeWidthTo(0, b.Duration - BREAK_FADE_DURATION) .Then() .ResizeWidthTo(1); remainingTimeCounter.CountTo(b.Duration).CountTo(0, b.Duration); using (BeginDelayedSequence(b.Duration - BREAK_FADE_DURATION)) { fadeContainer.FadeOut(BREAK_FADE_DURATION); breakArrows.Hide(BREAK_FADE_DURATION); } } } } } }
35.21519
112
0.479152
[ "MIT" ]
peppy/osu-new
osu.Game/Screens/Play/BreakOverlay.cs
5,407
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Security.Cryptography.Encryption.RC2.Tests; using System.Text; using Test.Cryptography; using Xunit; namespace System.Security.Cryptography.Tests { [SkipOnPlatform(TestPlatforms.Browser, "Not supported on Browser")] public abstract partial class ECKeyFileTests<T> where T : ECAlgorithm { protected abstract T CreateKey(); protected abstract void Exercise(T key); protected virtual Func<T, byte[]> PublicKeyWriteArrayFunc { get; } = null; protected virtual WriteKeyToSpanFunc PublicKeyWriteSpanFunc { get; } = null; // This would need to be virtualized if there was ever a platform that // allowed explicit in ECDH or ECDSA but not the other. public static bool SupportsExplicitCurves { get; } = EcDiffieHellman.Tests.ECDiffieHellmanFactory.ExplicitCurvesSupported; public static bool CanDeriveNewPublicKey { get; } = EcDiffieHellman.Tests.ECDiffieHellmanFactory.CanDeriveNewPublicKey; public static bool SupportsBrainpool { get; } = IsCurveSupported(ECCurve.NamedCurves.brainpoolP160r1.Oid); public static bool SupportsSect163k1 { get; } = IsCurveSupported(EccTestData.Sect163k1Key1.Curve.Oid); public static bool SupportsSect283k1 { get; } = IsCurveSupported(EccTestData.Sect283k1Key1.Curve.Oid); public static bool SupportsC2pnb163v1 { get; } = IsCurveSupported(EccTestData.C2pnb163v1Key1.Curve.Oid); // Some platforms support explicitly specifying these curves, but do not support specifying them by name. public static bool ExplicitNamedSameSupport { get; } = !PlatformDetection.IsAndroid; public static bool SupportsSect163k1Explicit { get; } = SupportsSect163k1 || (!ExplicitNamedSameSupport && SupportsExplicitCurves); public static bool SupportsC2pnb163v1Explicit { get; } = SupportsC2pnb163v1 || (!ExplicitNamedSameSupport && SupportsExplicitCurves); private static bool IsCurveSupported(Oid oid) { return EcDiffieHellman.Tests.ECDiffieHellmanFactory.IsCurveValid(oid); } [Theory] [InlineData(false)] [InlineData(true)] public void UseAfterDispose(bool importKey) { T key = CreateKey(); if (importKey) { key.ImportParameters(EccTestData.GetNistP256ReferenceKey()); } byte[] ecPrivate; byte[] pkcs8Private; byte[] pkcs8EncryptedPrivate; byte[] subjectPublicKeyInfo; string pwStr = "Hello"; // Because the PBE algorithm uses PBES2 the string->byte encoding is UTF-8. byte[] pwBytes = Encoding.UTF8.GetBytes(pwStr); PbeParameters pbeParameters = new PbeParameters( PbeEncryptionAlgorithm.Aes192Cbc, HashAlgorithmName.SHA256, 3072); // Ensure the key was loaded, then dispose it. // Also ensures all of the inputs are valid for the disposed tests. using (key) { ecPrivate = key.ExportECPrivateKey(); pkcs8Private = key.ExportPkcs8PrivateKey(); pkcs8EncryptedPrivate = key.ExportEncryptedPkcs8PrivateKey(pwStr, pbeParameters); subjectPublicKeyInfo = key.ExportSubjectPublicKeyInfo(); } Assert.Throws<ObjectDisposedException>(() => key.ImportECPrivateKey(ecPrivate, out _)); Assert.Throws<ObjectDisposedException>(() => key.ImportPkcs8PrivateKey(pkcs8Private, out _)); Assert.Throws<ObjectDisposedException>(() => key.ImportEncryptedPkcs8PrivateKey(pwStr, pkcs8EncryptedPrivate, out _)); Assert.Throws<ObjectDisposedException>(() => key.ImportEncryptedPkcs8PrivateKey(pwBytes, pkcs8EncryptedPrivate, out _)); Assert.Throws<ObjectDisposedException>(() => key.ImportSubjectPublicKeyInfo(subjectPublicKeyInfo, out _)); Assert.Throws<ObjectDisposedException>(() => key.ExportECPrivateKey()); Assert.Throws<ObjectDisposedException>(() => key.TryExportECPrivateKey(ecPrivate, out _)); Assert.Throws<ObjectDisposedException>(() => key.ExportPkcs8PrivateKey()); Assert.Throws<ObjectDisposedException>(() => key.TryExportPkcs8PrivateKey(pkcs8Private, out _)); Assert.Throws<ObjectDisposedException>(() => key.ExportEncryptedPkcs8PrivateKey(pwStr, pbeParameters)); Assert.Throws<ObjectDisposedException>(() => key.TryExportEncryptedPkcs8PrivateKey(pwStr, pbeParameters, pkcs8EncryptedPrivate, out _)); Assert.Throws<ObjectDisposedException>(() => key.ExportEncryptedPkcs8PrivateKey(pwBytes, pbeParameters)); Assert.Throws<ObjectDisposedException>(() => key.TryExportEncryptedPkcs8PrivateKey(pwBytes, pbeParameters, pkcs8EncryptedPrivate, out _)); Assert.Throws<ObjectDisposedException>(() => key.ExportSubjectPublicKeyInfo()); Assert.Throws<ObjectDisposedException>(() => key.TryExportSubjectPublicKeyInfo(subjectPublicKeyInfo, out _)); // Check encrypted import with the wrong password. // It shouldn't do enough work to realize it was wrong. pwBytes = Array.Empty<byte>(); Assert.Throws<ObjectDisposedException>(() => key.ImportEncryptedPkcs8PrivateKey((ReadOnlySpan<char>)"", pkcs8EncryptedPrivate, out _)); Assert.Throws<ObjectDisposedException>(() => key.ImportEncryptedPkcs8PrivateKey(pwBytes, pkcs8EncryptedPrivate, out _)); } [Fact] public void ReadWriteNistP521Pkcs8() { const string base64 = @" MIHuAgEAMBAGByqGSM49AgEGBSuBBAAjBIHWMIHTAgEBBEIBpV+HhaVzC67h1rPT AQaff9ZNiwTM6lfv1ZYeaPM/q0NUUWbKZVPNOP9xPRKJxpi9fQhrVeAbW9XtJ+Nj A3axFmahgYkDgYYABAB1HyYyTHPO9dReuzKTfjBg41GWCldZStA+scoMXqdHEhM2 a6mR0kQGcX+G/e/eCG4JuVSlfcD16UWXVtYMKq5t4AGo3bs/AsjCNSRyn1SLfiMy UjPvZ90wdSuSTyl0WePC4Sro2PT+RFTjhHwYslXKzvWXN7kY4d5A+V6f/k9Xt5FT oA=="; ReadWriteBase64Pkcs8(base64, EccTestData.GetNistP521Key2()); } [Fact] public void ReadWriteNistP521Pkcs8_ECDH() { const string base64 = @" MIHsAgEAMA4GBSuBBAEMBgUrgQQAIwSB1jCB0wIBAQRCAaVfh4Wlcwuu4daz0wEG n3/WTYsEzOpX79WWHmjzP6tDVFFmymVTzTj/cT0SicaYvX0Ia1XgG1vV7SfjYwN2 sRZmoYGJA4GGAAQAdR8mMkxzzvXUXrsyk34wYONRlgpXWUrQPrHKDF6nRxITNmup kdJEBnF/hv3v3ghuCblUpX3A9elFl1bWDCqubeABqN27PwLIwjUkcp9Ui34jMlIz 72fdMHUrkk8pdFnjwuEq6Nj0/kRU44R8GLJVys71lze5GOHeQPlen/5PV7eRU6A="; ReadWriteBase64Pkcs8( base64, EccTestData.GetNistP521Key2(), isSupported: false); } [Fact] public void ReadWriteNistP521SubjectPublicKeyInfo() { const string base64 = @" MIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQAdR8mMkxzzvXUXrsyk34wYONRlgpX WUrQPrHKDF6nRxITNmupkdJEBnF/hv3v3ghuCblUpX3A9elFl1bWDCqubeABqN27 PwLIwjUkcp9Ui34jMlIz72fdMHUrkk8pdFnjwuEq6Nj0/kRU44R8GLJVys71lze5 GOHeQPlen/5PV7eRU6A="; ReadWriteBase64SubjectPublicKeyInfo(base64, EccTestData.GetNistP521Key2()); } [Fact] public void ReadWriteNistP521SubjectPublicKeyInfo_ECDH() { const string base64 = @" MIGZMA4GBSuBBAEMBgUrgQQAIwOBhgAEAHUfJjJMc8711F67MpN+MGDjUZYKV1lK 0D6xygxep0cSEzZrqZHSRAZxf4b9794Ibgm5VKV9wPXpRZdW1gwqrm3gAajduz8C yMI1JHKfVIt+IzJSM+9n3TB1K5JPKXRZ48LhKujY9P5EVOOEfBiyVcrO9Zc3uRjh 3kD5Xp/+T1e3kVOg"; ReadWriteBase64SubjectPublicKeyInfo( base64, EccTestData.GetNistP521Key2(), isSupported: false); } [Fact] public void ReadNistP521EncryptedPkcs8_Pbes2_Aes128_Sha384() { // PBES2, PBKDF2 (SHA384), AES128 const string base64 = @" MIIBXTBXBgkqhkiG9w0BBQ0wSjApBgkqhkiG9w0BBQwwHAQI/JyXWyp/t3kCAggA MAwGCCqGSIb3DQIKBQAwHQYJYIZIAWUDBAECBBA3H8mbFK5afB5GzIemCCQkBIIB AKAz1z09ATUA8UfoDMwTyXiHUS8Mb/zkUCH+I7rav4orhAnSyYAyLKcHeGne+kUa 8ewQ5S7oMMLXE0HHQ8CpORlSgxTssqTAHigXEqdRb8nQ8hJJa2dFtNXyUeFtxZ7p x+aSLD6Y3J+mgzeVp1ICgROtuRjA9RYjUdd/3cy2BAlW+Atfs/300Jhkke3H0Gqc F71o65UNB+verEgN49rQK7FAFtoVI2oRjHLO1cGjxZkbWe2KLtgJWsgmexRq3/a+ Pfuapj3LAHALZtDNMZ+QCFN2ZXUSFNWiBSwnwCAtfFCn/EchPo3MFR3K0q/qXTua qtlbnispri1a/EghiaPQ0po="; ReadWriteBase64EncryptedPkcs8( base64, "qwerty", new PbeParameters( PbeEncryptionAlgorithm.TripleDes3KeyPkcs12, HashAlgorithmName.SHA1, 12321), EccTestData.GetNistP521Key2()); } [Fact] public void ReadNistP521EncryptedPkcs8_Pbes2_Aes128_Sha384_PasswordBytes() { // PBES2, PBKDF2 (SHA384), AES128 // [SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Suppression approved. Unit test key.")] const string base64 = @" MIIBXTBXBgkqhkiG9w0BBQ0wSjApBgkqhkiG9w0BBQwwHAQI/JyXWyp/t3kCAggA MAwGCCqGSIb3DQIKBQAwHQYJYIZIAWUDBAECBBA3H8mbFK5afB5GzIemCCQkBIIB AKAz1z09ATUA8UfoDMwTyXiHUS8Mb/zkUCH+I7rav4orhAnSyYAyLKcHeGne+kUa 8ewQ5S7oMMLXE0HHQ8CpORlSgxTssqTAHigXEqdRb8nQ8hJJa2dFtNXyUeFtxZ7p x+aSLD6Y3J+mgzeVp1ICgROtuRjA9RYjUdd/3cy2BAlW+Atfs/300Jhkke3H0Gqc F71o65UNB+verEgN49rQK7FAFtoVI2oRjHLO1cGjxZkbWe2KLtgJWsgmexRq3/a+ Pfuapj3LAHALZtDNMZ+QCFN2ZXUSFNWiBSwnwCAtfFCn/EchPo3MFR3K0q/qXTua qtlbnispri1a/EghiaPQ0po="; ReadWriteBase64EncryptedPkcs8( base64, "qwerty"u8.ToArray(), new PbeParameters( PbeEncryptionAlgorithm.Aes256Cbc, HashAlgorithmName.SHA1, 12321), EccTestData.GetNistP521Key2()); } [ConditionalFact(typeof(RC2Factory), nameof(RC2Factory.IsSupported))] public void ReadNistP256EncryptedPkcs8_Pbes1_RC2_MD5() { const string base64 = @" MIGwMBsGCSqGSIb3DQEFBjAOBAiVk8SDhLdiNwICCAAEgZB2rI9tf7jjGdEwJNrS 8F/xNIo/0OSUSkQyg5n/ovRK1IodzPpWqipqM8TGfZk4sxn7h7RBmX2FlMkTLO4i mVannH3jd9cmCAz0aewDO0/LgmvDnzWiJ/CoDamzwC8bzDocq1Y/PsVYsYzSrJ7n m8STNpW+zSpHWlpHpWHgXGq4wrUKJifxOv6Rm5KTYcvUT38="; ReadWriteBase64EncryptedPkcs8( base64, "secp256r1", new PbeParameters( PbeEncryptionAlgorithm.TripleDes3KeyPkcs12, HashAlgorithmName.SHA1, 1024), EccTestData.GetNistP256ReferenceKey()); } [Fact] public void ReadWriteNistP256ECPrivateKey() { const string base64 = @" MHcCAQEEIHChLC2xaEXtVv9oz8IaRys/BNfWhRv2NJ8tfVs0UrOKoAoGCCqGSM49 AwEHoUQDQgAEgQHs5HRkpurXDPaabivT2IaRoyYtIsuk92Ner/JmgKjYoSumHVmS NfZ9nLTVjxeD08pD548KWrqmJAeZNsDDqQ=="; ReadWriteBase64ECPrivateKey( base64, EccTestData.GetNistP256ReferenceKey()); } [Fact] public void ReadWriteNistP256ExplicitECPrivateKey() { ReadWriteBase64ECPrivateKey( @" MIIBaAIBAQQgcKEsLbFoRe1W/2jPwhpHKz8E19aFG/Y0ny19WzRSs4qggfowgfcC AQEwLAYHKoZIzj0BAQIhAP////8AAAABAAAAAAAAAAAAAAAA//////////////// MFsEIP////8AAAABAAAAAAAAAAAAAAAA///////////////8BCBaxjXYqjqT57Pr vVV2mIa8ZR0GsMxTsPY7zjw+J9JgSwMVAMSdNgiG5wSTamZ44ROdJreBn36QBEEE axfR8uEsQkf4vOblY6RA8ncDfYEt6zOg9KE5RdiYwpZP40Li/hp/m47n60p8D54W K84zV2sxXs7LtkBoN79R9QIhAP////8AAAAA//////////+85vqtpxeehPO5ysL8 YyVRAgEBoUQDQgAEgQHs5HRkpurXDPaabivT2IaRoyYtIsuk92Ner/JmgKjYoSum HVmSNfZ9nLTVjxeD08pD548KWrqmJAeZNsDDqQ==", EccTestData.GetNistP256ReferenceKeyExplicit(), SupportsExplicitCurves); } [Fact] public void ReadWriteNistP256ExplicitPkcs8() { ReadWriteBase64Pkcs8( @" MIIBeQIBADCCAQMGByqGSM49AgEwgfcCAQEwLAYHKoZIzj0BAQIhAP////8AAAAB AAAAAAAAAAAAAAAA////////////////MFsEIP////8AAAABAAAAAAAAAAAAAAAA ///////////////8BCBaxjXYqjqT57PrvVV2mIa8ZR0GsMxTsPY7zjw+J9JgSwMV AMSdNgiG5wSTamZ44ROdJreBn36QBEEEaxfR8uEsQkf4vOblY6RA8ncDfYEt6zOg 9KE5RdiYwpZP40Li/hp/m47n60p8D54WK84zV2sxXs7LtkBoN79R9QIhAP////8A AAAA//////////+85vqtpxeehPO5ysL8YyVRAgEBBG0wawIBAQQgcKEsLbFoRe1W /2jPwhpHKz8E19aFG/Y0ny19WzRSs4qhRANCAASBAezkdGSm6tcM9ppuK9PYhpGj Ji0iy6T3Y16v8maAqNihK6YdWZI19n2ctNWPF4PTykPnjwpauqYkB5k2wMOp", EccTestData.GetNistP256ReferenceKeyExplicit(), SupportsExplicitCurves); } [Fact] public void ReadWriteNistP256ExplicitEncryptedPkcs8() { ReadWriteBase64EncryptedPkcs8( @" MIIBoTAbBgkqhkiG9w0BBQMwDgQIQqYZ3N87K0ICAggABIIBgOHAWa6wz144p0uT qZsQAbQcIpAFBQRC382dxiOHCV11OyZg264SmxS9iY1OEwIr/peACLu+Fk7zPKhv Ox1hYz/OeLoKKdtBMqrp65JmH73jG8qeAMuYNj83AIERY7Cckuc2fEC2GTEJcNWs olE+0p4H6yIvXI48NEQazj5w9zfOGvLmP6Kw6nX+SV3fzM9jHskU226LnDdokGVg an6/hV1r+2+n2MujhfNzQd/5vW5zx7PN/1aMVMz3wUv9t8scDppeMR5CNCMkxlRA cQ2lfx2vqFuY70EckgumDqm7AtKK2bLlA6XGTb8HuqKHA0l1zrul9AOBC1g33isD 5CJu1CCT34adV4E4G44uiRQUtf+K8m5Oeo8FI/gGBxdQyOh1k8TNsM+p32gTU8HH 89M5R+s1ayQI7jVPGHXm8Ch7lxvqo6FZAu6+vh23vTwVShUTpGYd0XguE6XKJjGx eWDIWFuFRj58uAQ65/viFausHWt1BdywcwcyVRb2eLI5MR7DWA==", "explicit", new PbeParameters( PbeEncryptionAlgorithm.Aes128Cbc, HashAlgorithmName.SHA256, 1234), EccTestData.GetNistP256ReferenceKeyExplicit(), SupportsExplicitCurves); } [Fact] public void ReadWriteNistP256ExplicitSubjectPublicKeyInfo() { ReadWriteBase64SubjectPublicKeyInfo( @" MIIBSzCCAQMGByqGSM49AgEwgfcCAQEwLAYHKoZIzj0BAQIhAP////8AAAABAAAA AAAAAAAAAAAA////////////////MFsEIP////8AAAABAAAAAAAAAAAAAAAA//// ///////////8BCBaxjXYqjqT57PrvVV2mIa8ZR0GsMxTsPY7zjw+J9JgSwMVAMSd NgiG5wSTamZ44ROdJreBn36QBEEEaxfR8uEsQkf4vOblY6RA8ncDfYEt6zOg9KE5 RdiYwpZP40Li/hp/m47n60p8D54WK84zV2sxXs7LtkBoN79R9QIhAP////8AAAAA //////////+85vqtpxeehPO5ysL8YyVRAgEBA0IABIEB7OR0ZKbq1wz2mm4r09iG kaMmLSLLpPdjXq/yZoCo2KErph1ZkjX2fZy01Y8Xg9PKQ+ePClq6piQHmTbAw6k=", EccTestData.GetNistP256ReferenceKeyExplicit(), SupportsExplicitCurves); } [Fact] public void ReadWriteBrainpoolKey1ECPrivateKey() { ReadWriteBase64ECPrivateKey( @" MFQCAQEEFMXZRFR94RXbJYjcb966O0c+nE2WoAsGCSskAwMCCAEBAaEsAyoABI5i jwk5x2KSdsrb/pnAHDZQk1TictLI7vH2zDIF0AV+ud5sqeMQUJY=", EccTestData.BrainpoolP160r1Key1, SupportsBrainpool); } [Fact] public void ReadWriteBrainpoolKey1Pkcs8() { ReadWriteBase64Pkcs8( @" MGQCAQAwFAYHKoZIzj0CAQYJKyQDAwIIAQEBBEkwRwIBAQQUxdlEVH3hFdsliNxv 3ro7Rz6cTZahLAMqAASOYo8JOcdiknbK2/6ZwBw2UJNU4nLSyO7x9swyBdAFfrne bKnjEFCW", EccTestData.BrainpoolP160r1Key1, SupportsBrainpool); } [Fact] public void ReadWriteBrainpoolKey1EncryptedPkcs8() { ReadWriteBase64EncryptedPkcs8( @" MIGHMBsGCSqGSIb3DQEFAzAOBAhSgCZvbsatLQICCAAEaKGDyoSVej1yNPCn7K6q ooI857+joe6NZjR+w1xuH4JfrQZGvelWZ2AWtQezuz4UzPLnL3Nyf6jjPPuKarpk HiDaMtpw7yT5+32Vkxv5C2jvqNPpicmEFpf2wJ8yVLQtMOKAF2sOwxN/", "12345", new PbeParameters( PbeEncryptionAlgorithm.Aes192Cbc, HashAlgorithmName.SHA384, 4096), EccTestData.BrainpoolP160r1Key1, SupportsBrainpool); } [Fact] public void ReadWriteBrainpoolKey1SubjectPublicKeyInfo() { ReadWriteBase64SubjectPublicKeyInfo( @" MEIwFAYHKoZIzj0CAQYJKyQDAwIIAQEBAyoABI5ijwk5x2KSdsrb/pnAHDZQk1Ti ctLI7vH2zDIF0AV+ud5sqeMQUJY=", EccTestData.BrainpoolP160r1Key1, SupportsBrainpool); } [Fact] public void ReadWriteSect163k1Key1ECPrivateKey() { ReadWriteBase64ECPrivateKey( @" MFMCAQEEFQPBmVrfrowFGNwT3+YwS7AQF+akEqAHBgUrgQQAAaEuAywABAYXnjcZ zIElQ1/mRYnV/KbcGIdVHQeI/rti/8kkjYs5iv4+C1w8ArP+Nw==", EccTestData.Sect163k1Key1, SupportsSect163k1); } [Fact] public void ReadWriteSect163k1Key1Pkcs8() { ReadWriteBase64Pkcs8( @" MGMCAQAwEAYHKoZIzj0CAQYFK4EEAAEETDBKAgEBBBUDwZla366MBRjcE9/mMEuw EBfmpBKhLgMsAAQGF543GcyBJUNf5kWJ1fym3BiHVR0HiP67Yv/JJI2LOYr+Pgtc PAKz/jc=", EccTestData.Sect163k1Key1, SupportsSect163k1); } [Fact] public void ReadWriteSect163k1Key1EncryptedPkcs8() { ReadWriteBase64EncryptedPkcs8( @" MIGHMBsGCSqGSIb3DQEFAzAOBAjLBuCZyPt15QICCAAEaPa9V9VJoB8G+RIgZaYv z4xl+rpvkDrDI0Xnh8oj1CLQldy2N77pdk3pOg9TwJo+r+eKfIJgBVezW2O615ww f+ESRyxDnBgKz6H2RKeenyrwVhxF98SyJzAdP637vR3QmDNAWWAgoUhg", "Koblitz", new PbeParameters( PbeEncryptionAlgorithm.Aes256Cbc, HashAlgorithmName.SHA256, 7), EccTestData.Sect163k1Key1, SupportsSect163k1); } [Fact] public void ReadWriteSect163k1Key1SubjectPublicKeyInfo() { ReadWriteBase64SubjectPublicKeyInfo( @" MEAwEAYHKoZIzj0CAQYFK4EEAAEDLAAEBheeNxnMgSVDX+ZFidX8ptwYh1UdB4j+ u2L/ySSNizmK/j4LXDwCs/43", EccTestData.Sect163k1Key1, SupportsSect163k1); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/64446", typeof(PlatformSupport), nameof(PlatformSupport.IsAndroidVersionAtLeast31))] public void ReadWriteSect163k1Key1ExplicitECPrivateKey() { ReadWriteBase64ECPrivateKey( @" MIHHAgEBBBUDwZla366MBRjcE9/mMEuwEBfmpBKgezB5AgEBMCUGByqGSM49AQIw GgICAKMGCSqGSM49AQIDAzAJAgEDAgEGAgEHMAYEAQEEAQEEKwQC/hPAU3u8Eayq B9eT3k5tXlyU7ugCiQcPsF04/1gyHy6ABTbVOMzao9kCFQQAAAAAAAAAAAACAQii 4MwNmfil7wIBAqEuAywABAYXnjcZzIElQ1/mRYnV/KbcGIdVHQeI/rti/8kkjYs5 iv4+C1w8ArP+Nw==", EccTestData.Sect163k1Key1Explicit, SupportsSect163k1Explicit); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/64446", typeof(PlatformSupport), nameof(PlatformSupport.IsAndroidVersionAtLeast31))] public void ReadWriteSect163k1Key1ExplicitPkcs8() { ReadWriteBase64Pkcs8( @" MIHYAgEAMIGEBgcqhkjOPQIBMHkCAQEwJQYHKoZIzj0BAjAaAgIAowYJKoZIzj0B AgMDMAkCAQMCAQYCAQcwBgQBAQQBAQQrBAL+E8BTe7wRrKoH15PeTm1eXJTu6AKJ Bw+wXTj/WDIfLoAFNtU4zNqj2QIVBAAAAAAAAAAAAAIBCKLgzA2Z+KXvAgECBEww SgIBAQQVA8GZWt+ujAUY3BPf5jBLsBAX5qQSoS4DLAAEBheeNxnMgSVDX+ZFidX8 ptwYh1UdB4j+u2L/ySSNizmK/j4LXDwCs/43", EccTestData.Sect163k1Key1Explicit, SupportsSect163k1Explicit); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/64446", typeof(PlatformSupport), nameof(PlatformSupport.IsAndroidVersionAtLeast31))] public void ReadWriteSect163k1Key1ExplicitEncryptedPkcs8() { ReadWriteBase64EncryptedPkcs8( @" MIIBADAbBgkqhkiG9w0BBQMwDgQICAkWq2tKYZUCAggABIHgjBfngwE9DbCEaznz +55MjSGbQH0NMgIRCJtQLbrI7888+KmTL6hWYPH6CQzTsi1unWrMAH2JKa7dkIe9 FWNXW7bmhcokVDh/OTXOV9QPZ3O4m19a9XOl0wNlbi47XQ3KUkcbzyFNYlDMSzFw HRfW8+aIkyYAvYCoA4buRfigBe0xy1VKyE5aUkX0EFjx4gqC3Q5mjDMFOxlKNjVV clSZg6tg9J7bTQsDAN0uYpBc1r8DiSQbKMxg+q13yBciXJzfmkQRtNVXQPsseiUm z2NFvWcpK0Fh9fCVGuXV9sjJ5qE=", "Koblitz", new PbeParameters( PbeEncryptionAlgorithm.Aes128Cbc, HashAlgorithmName.SHA256, 12), EccTestData.Sect163k1Key1Explicit, SupportsSect163k1Explicit); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/64446", typeof(PlatformSupport), nameof(PlatformSupport.IsAndroidVersionAtLeast31))] public void ReadWriteSect163k1Key1ExplicitSubjectPublicKeyInfo() { ReadWriteBase64SubjectPublicKeyInfo( @" MIG1MIGEBgcqhkjOPQIBMHkCAQEwJQYHKoZIzj0BAjAaAgIAowYJKoZIzj0BAgMD MAkCAQMCAQYCAQcwBgQBAQQBAQQrBAL+E8BTe7wRrKoH15PeTm1eXJTu6AKJBw+w XTj/WDIfLoAFNtU4zNqj2QIVBAAAAAAAAAAAAAIBCKLgzA2Z+KXvAgECAywABAYX njcZzIElQ1/mRYnV/KbcGIdVHQeI/rti/8kkjYs5iv4+C1w8ArP+Nw==", EccTestData.Sect163k1Key1Explicit, SupportsSect163k1Explicit); } [Fact] public void ReadWriteSect283k1Key1ECPrivateKey() { ReadWriteBase64ECPrivateKey( @" MIGAAgEBBCQAtPGuHn/c1LDoIFPAipCIUrJiMebAFnD8xsPqLF0/7UDt8DegBwYF K4EEABChTANKAAQHUncL0z5qbuIJbLaxIOdJe0e2wHehR8tX2vaTkJ2EBxbup6oE fbmZXDVgPF5rL4zf8Otx03rjQxughJ66sTpMkAPHlp9VzZA=", EccTestData.Sect283k1Key1, SupportsSect283k1); } [Fact] public void ReadWriteSect283k1Key1Pkcs8() { ReadWriteBase64Pkcs8( @" MIGQAgEAMBAGByqGSM49AgEGBSuBBAAQBHkwdwIBAQQkALTxrh5/3NSw6CBTwIqQ iFKyYjHmwBZw/MbD6ixdP+1A7fA3oUwDSgAEB1J3C9M+am7iCWy2sSDnSXtHtsB3 oUfLV9r2k5CdhAcW7qeqBH25mVw1YDxeay+M3/DrcdN640MboISeurE6TJADx5af Vc2Q", EccTestData.Sect283k1Key1, SupportsSect283k1); } [Fact] public void ReadWriteSect283k1Key1EncryptedPkcs8() { ReadWriteBase64EncryptedPkcs8( @" MIG4MBsGCSqGSIb3DQEFAzAOBAhf/Ix8WHVvxQICCAAEgZheT2iB2sBmNjV2qIgI DsNyPY+0rwbWR8MHZcRN0zAL9Q3kawaZyWeKe4j3m3Y39YWURVymYeLAm70syrEw 057W6kNVXxR/hEq4MlHJZxZdS+R6LGpEvWFEWiuN0wBtmhO24+KmqPMH8XhGszBv nTvuaAMG/xvXzKoigakX+1D60cmftPsC7t23SF+xMdzfZNlJGrxXFYX1Gg==", "12345", new PbeParameters( PbeEncryptionAlgorithm.Aes192Cbc, HashAlgorithmName.SHA384, 4096), EccTestData.Sect283k1Key1, SupportsSect283k1); } [Fact] public void ReadWriteSect283k1Key1SubjectPublicKeyInfo() { ReadWriteBase64SubjectPublicKeyInfo( @" MF4wEAYHKoZIzj0CAQYFK4EEABADSgAEB1J3C9M+am7iCWy2sSDnSXtHtsB3oUfL V9r2k5CdhAcW7qeqBH25mVw1YDxeay+M3/DrcdN640MboISeurE6TJADx5afVc2Q", EccTestData.Sect283k1Key1, SupportsSect283k1); } [Fact] public void ReadWriteC2pnb163v1ECPrivateKey() { ReadWriteBase64ECPrivateKey( @" MFYCAQEEFQD00koUBxIvRFlnvh2TwAk6ZTZ5hqAKBggqhkjOPQMAAaEuAywABAIR Jy8cVYJCaIjpG9aSV3SUIyJIqgQnCDD3oQCa1nCojekr1ZJIzIE7RQ==", EccTestData.C2pnb163v1Key1, SupportsC2pnb163v1); } [Fact] public void ReadWriteC2pnb163v1Pkcs8() { ReadWriteBase64Pkcs8( @" MGYCAQAwEwYHKoZIzj0CAQYIKoZIzj0DAAEETDBKAgEBBBUA9NJKFAcSL0RZZ74d k8AJOmU2eYahLgMsAAQCEScvHFWCQmiI6RvWkld0lCMiSKoEJwgw96EAmtZwqI3p K9WSSMyBO0U=", EccTestData.C2pnb163v1Key1, SupportsC2pnb163v1); } [Fact] public void ReadWriteC2pnb163v1EncryptedPkcs8() { ReadWriteBase64EncryptedPkcs8( @" MIGPMBsGCSqGSIb3DQEFAzAOBAjdV9IDq+L+5gICCAAEcI1e6RA8kMcYB+PvOcCU Jj65nXTIrMPmZ0DmFMF9WBg0J+yzxgDhBVynpT2uJntY4FuDlvdpcLRK1EGLZYKf qYc5zJMYkRZ178bE3DtfrP3UxD34YvbRl2aeu334+wJOm7ApXv81ugt4OoCiPhdg wiA=", "secret", new PbeParameters( PbeEncryptionAlgorithm.Aes192Cbc, HashAlgorithmName.SHA512, 1024), EccTestData.C2pnb163v1Key1, SupportsC2pnb163v1); } [Fact] public void ReadWriteC2pnb163v1SubjectPublicKeyInfo() { ReadWriteBase64SubjectPublicKeyInfo( @" MEMwEwYHKoZIzj0CAQYIKoZIzj0DAAEDLAAEAhEnLxxVgkJoiOkb1pJXdJQjIkiq BCcIMPehAJrWcKiN6SvVkkjMgTtF", EccTestData.C2pnb163v1Key1, SupportsC2pnb163v1); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/64446", typeof(PlatformSupport), nameof(PlatformSupport.IsAndroidVersionAtLeast31))] public void ReadWriteC2pnb163v1ExplicitECPrivateKey() { ReadWriteBase64ECPrivateKey( @" MIIBBwIBAQQVAPTSShQHEi9EWWe+HZPACTplNnmGoIG6MIG3AgEBMCUGByqGSM49 AQIwGgICAKMGCSqGSM49AQIDAzAJAgEBAgECAgEIMEQEFQclRrVDUjSkIuB4lnX0 MsiUNd5SQgQUyVF9BtUkDTz/OMdLILbNTW+d1NkDFQDSwPsVdghg3vHu9NaW5naH VhUXVAQrBAevaZiVRhA9eTKfzD10iA8zu+gDywHsIyEbWWat6h0/h/fqWEiu8LfK nwIVBAAAAAAAAAAAAAHmD8iCHMdNrq/BAgECoS4DLAAEAhEnLxxVgkJoiOkb1pJX dJQjIkiqBCcIMPehAJrWcKiN6SvVkkjMgTtF", EccTestData.C2pnb163v1Key1Explicit, SupportsC2pnb163v1Explicit); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/64446", typeof(PlatformSupport), nameof(PlatformSupport.IsAndroidVersionAtLeast31))] public void ReadWriteC2pnb163v1ExplicitPkcs8() { ReadWriteBase64Pkcs8( @" MIIBFwIBADCBwwYHKoZIzj0CATCBtwIBATAlBgcqhkjOPQECMBoCAgCjBgkqhkjO PQECAwMwCQIBAQIBAgIBCDBEBBUHJUa1Q1I0pCLgeJZ19DLIlDXeUkIEFMlRfQbV JA08/zjHSyC2zU1vndTZAxUA0sD7FXYIYN7x7vTWluZ2h1YVF1QEKwQHr2mYlUYQ PXkyn8w9dIgPM7voA8sB7CMhG1lmreodP4f36lhIrvC3yp8CFQQAAAAAAAAAAAAB 5g/IghzHTa6vwQIBAgRMMEoCAQEEFQD00koUBxIvRFlnvh2TwAk6ZTZ5hqEuAywA BAIRJy8cVYJCaIjpG9aSV3SUIyJIqgQnCDD3oQCa1nCojekr1ZJIzIE7RQ==", EccTestData.C2pnb163v1Key1Explicit, SupportsC2pnb163v1Explicit); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/64446", typeof(PlatformSupport), nameof(PlatformSupport.IsAndroidVersionAtLeast31))] public void ReadWriteC2pnb163v1ExplicitEncryptedPkcs8() { ReadWriteBase64EncryptedPkcs8( @" MIIBQTAbBgkqhkiG9w0BBQMwDgQI9+ZZnHaqxb0CAggABIIBIM+n6x/Q1hs5OW0F oOKZmQ0mKNRKb23SMqwo0bJlxseIOVdYzOV2LH1hSWeJb7FMxo6OJXb2CpYSPqv1 v3lhdLC5t/ViqAOhG70KF+Dy/vZr8rWXRFqy+OdqwxOes/lBsG+Ws9+uEk8+Gm2G xMHXJNKliSUePlT3wC7z8bCkEvLF7hkGjEAgcABry5Ohq3W2by6Dnd8YWJNgeiW/ Vu5rT1ThAus7w2TJjWrrEqBbIlQ9nm6/MMj9nYnVVfpPAOk/qX9Or7TmK+Sei88Q staXBhfJk9ec8laiPpNbhHJSZ2Ph3Snb6SA7MYi5nIMP4RPxOM2eUet4/ueV1O3U wxcZ+wOsnebIwy4ftKL+klh5EXv/9S5sCjC8g8J2cA6GmcZbiQ==", "secret", new PbeParameters( PbeEncryptionAlgorithm.Aes192Cbc, HashAlgorithmName.SHA512, 1024), EccTestData.C2pnb163v1Key1Explicit, SupportsC2pnb163v1Explicit); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/64446", typeof(PlatformSupport), nameof(PlatformSupport.IsAndroidVersionAtLeast31))] public void ReadWriteC2pnb163v1ExplicitSubjectPublicKeyInfo() { ReadWriteBase64SubjectPublicKeyInfo( @" MIH0MIHDBgcqhkjOPQIBMIG3AgEBMCUGByqGSM49AQIwGgICAKMGCSqGSM49AQID AzAJAgEBAgECAgEIMEQEFQclRrVDUjSkIuB4lnX0MsiUNd5SQgQUyVF9BtUkDTz/ OMdLILbNTW+d1NkDFQDSwPsVdghg3vHu9NaW5naHVhUXVAQrBAevaZiVRhA9eTKf zD10iA8zu+gDywHsIyEbWWat6h0/h/fqWEiu8LfKnwIVBAAAAAAAAAAAAAHmD8iC HMdNrq/BAgECAywABAIRJy8cVYJCaIjpG9aSV3SUIyJIqgQnCDD3oQCa1nCojekr 1ZJIzIE7RQ==", EccTestData.C2pnb163v1Key1Explicit, SupportsC2pnb163v1Explicit); } [Fact] public void NoFuzzySubjectPublicKeyInfo() { using (T key = CreateKey()) { int bytesRead = -1; byte[] ecPriv = key.ExportECPrivateKey(); Assert.ThrowsAny<CryptographicException>( () => key.ImportSubjectPublicKeyInfo(ecPriv, out bytesRead)); Assert.Equal(-1, bytesRead); byte[] pkcs8 = key.ExportPkcs8PrivateKey(); Assert.ThrowsAny<CryptographicException>( () => key.ImportSubjectPublicKeyInfo(pkcs8, out bytesRead)); Assert.Equal(-1, bytesRead); ReadOnlySpan<byte> passwordBytes = ecPriv.AsSpan(0, 15); byte[] encryptedPkcs8 = key.ExportEncryptedPkcs8PrivateKey( passwordBytes, new PbeParameters( PbeEncryptionAlgorithm.Aes256Cbc, HashAlgorithmName.SHA512, 123)); Assert.ThrowsAny<CryptographicException>( () => key.ImportSubjectPublicKeyInfo(encryptedPkcs8, out bytesRead)); Assert.Equal(-1, bytesRead); } } [Fact] public void NoFuzzyECPrivateKey() { using (T key = CreateKey()) { int bytesRead = -1; byte[] spki = key.ExportSubjectPublicKeyInfo(); Assert.ThrowsAny<CryptographicException>( () => key.ImportECPrivateKey(spki, out bytesRead)); Assert.Equal(-1, bytesRead); byte[] pkcs8 = key.ExportPkcs8PrivateKey(); Assert.ThrowsAny<CryptographicException>( () => key.ImportECPrivateKey(pkcs8, out bytesRead)); Assert.Equal(-1, bytesRead); ReadOnlySpan<byte> passwordBytes = spki.AsSpan(0, 15); byte[] encryptedPkcs8 = key.ExportEncryptedPkcs8PrivateKey( passwordBytes, new PbeParameters( PbeEncryptionAlgorithm.Aes256Cbc, HashAlgorithmName.SHA512, 123)); Assert.ThrowsAny<CryptographicException>( () => key.ImportECPrivateKey(encryptedPkcs8, out bytesRead)); Assert.Equal(-1, bytesRead); } } [Fact] public void NoFuzzyPkcs8() { using (T key = CreateKey()) { int bytesRead = -1; byte[] spki = key.ExportSubjectPublicKeyInfo(); Assert.ThrowsAny<CryptographicException>( () => key.ImportPkcs8PrivateKey(spki, out bytesRead)); Assert.Equal(-1, bytesRead); byte[] ecPriv = key.ExportECPrivateKey(); Assert.ThrowsAny<CryptographicException>( () => key.ImportPkcs8PrivateKey(ecPriv, out bytesRead)); Assert.Equal(-1, bytesRead); ReadOnlySpan<byte> passwordBytes = spki.AsSpan(0, 15); byte[] encryptedPkcs8 = key.ExportEncryptedPkcs8PrivateKey( passwordBytes, new PbeParameters( PbeEncryptionAlgorithm.Aes256Cbc, HashAlgorithmName.SHA512, 123)); Assert.ThrowsAny<CryptographicException>( () => key.ImportPkcs8PrivateKey(encryptedPkcs8, out bytesRead)); Assert.Equal(-1, bytesRead); } } [Fact] public void NoFuzzyEncryptedPkcs8() { using (T key = CreateKey()) { int bytesRead = -1; byte[] spki = key.ExportSubjectPublicKeyInfo(); byte[] empty = Array.Empty<byte>(); Assert.ThrowsAny<CryptographicException>( () => key.ImportEncryptedPkcs8PrivateKey(empty, spki, out bytesRead)); Assert.Equal(-1, bytesRead); byte[] ecPriv = key.ExportECPrivateKey(); Assert.ThrowsAny<CryptographicException>( () => key.ImportEncryptedPkcs8PrivateKey(empty, ecPriv, out bytesRead)); Assert.Equal(-1, bytesRead); byte[] pkcs8 = key.ExportPkcs8PrivateKey(); Assert.ThrowsAny<CryptographicException>( () => key.ImportEncryptedPkcs8PrivateKey(empty, pkcs8, out bytesRead)); Assert.Equal(-1, bytesRead); } } [Fact] public void NoPrivKeyFromPublicOnly() { using (T key = CreateKey()) { ECParameters parameters = EccTestData.GetNistP521Key2(); parameters.D = null; key.ImportParameters(parameters); Assert.ThrowsAny<CryptographicException>( () => key.ExportECPrivateKey()); Assert.ThrowsAny<CryptographicException>( () => key.TryExportECPrivateKey(Span<byte>.Empty, out _)); Assert.ThrowsAny<CryptographicException>( () => key.ExportPkcs8PrivateKey()); Assert.ThrowsAny<CryptographicException>( () => key.TryExportPkcs8PrivateKey(Span<byte>.Empty, out _)); Assert.ThrowsAny<CryptographicException>( () => key.ExportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte>.Empty, new PbeParameters(PbeEncryptionAlgorithm.Aes192Cbc, HashAlgorithmName.SHA256, 72))); Assert.ThrowsAny<CryptographicException>( () => key.TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte>.Empty, new PbeParameters(PbeEncryptionAlgorithm.Aes192Cbc, HashAlgorithmName.SHA256, 72), Span<byte>.Empty, out _)); } } [Fact] public void BadPbeParameters() { using (T key = CreateKey()) { Assert.ThrowsAny<ArgumentNullException>( () => key.ExportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte>.Empty, null)); Assert.ThrowsAny<ArgumentNullException>( () => key.ExportEncryptedPkcs8PrivateKey( ReadOnlySpan<char>.Empty, null)); Assert.ThrowsAny<ArgumentNullException>( () => key.TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte>.Empty, null, Span<byte>.Empty, out _)); Assert.ThrowsAny<ArgumentNullException>( () => key.TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan<char>.Empty, null, Span<byte>.Empty, out _)); // PKCS12 requires SHA-1 Assert.ThrowsAny<CryptographicException>( () => key.ExportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte>.Empty, new PbeParameters(PbeEncryptionAlgorithm.TripleDes3KeyPkcs12, HashAlgorithmName.SHA256, 72))); Assert.ThrowsAny<CryptographicException>( () => key.TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte>.Empty, new PbeParameters(PbeEncryptionAlgorithm.TripleDes3KeyPkcs12, HashAlgorithmName.SHA256, 72), Span<byte>.Empty, out _)); // PKCS12 requires SHA-1 Assert.ThrowsAny<CryptographicException>( () => key.ExportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte>.Empty, new PbeParameters(PbeEncryptionAlgorithm.TripleDes3KeyPkcs12, HashAlgorithmName.MD5, 72))); Assert.ThrowsAny<CryptographicException>( () => key.TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte>.Empty, new PbeParameters(PbeEncryptionAlgorithm.TripleDes3KeyPkcs12, HashAlgorithmName.MD5, 72), Span<byte>.Empty, out _)); // PKCS12 requires a char-based password Assert.ThrowsAny<CryptographicException>( () => key.ExportEncryptedPkcs8PrivateKey( new byte[3], new PbeParameters(PbeEncryptionAlgorithm.TripleDes3KeyPkcs12, HashAlgorithmName.SHA1, 72))); Assert.ThrowsAny<CryptographicException>( () => key.TryExportEncryptedPkcs8PrivateKey( new byte[3], new PbeParameters(PbeEncryptionAlgorithm.TripleDes3KeyPkcs12, HashAlgorithmName.SHA1, 72), Span<byte>.Empty, out _)); // Unknown encryption algorithm Assert.ThrowsAny<CryptographicException>( () => key.ExportEncryptedPkcs8PrivateKey( new byte[3], new PbeParameters(0, HashAlgorithmName.SHA1, 72))); Assert.ThrowsAny<CryptographicException>( () => key.TryExportEncryptedPkcs8PrivateKey( new byte[3], new PbeParameters(0, HashAlgorithmName.SHA1, 72), Span<byte>.Empty, out _)); // Unknown encryption algorithm (negative enum value) Assert.ThrowsAny<CryptographicException>( () => key.ExportEncryptedPkcs8PrivateKey( new byte[3], new PbeParameters((PbeEncryptionAlgorithm)(-5), HashAlgorithmName.SHA1, 72))); Assert.ThrowsAny<CryptographicException>( () => key.TryExportEncryptedPkcs8PrivateKey( new byte[3], new PbeParameters((PbeEncryptionAlgorithm)(-5), HashAlgorithmName.SHA1, 72), Span<byte>.Empty, out _)); // Unknown encryption algorithm (overly-large enum value) Assert.ThrowsAny<CryptographicException>( () => key.ExportEncryptedPkcs8PrivateKey( new byte[3], new PbeParameters((PbeEncryptionAlgorithm)15, HashAlgorithmName.SHA1, 72))); Assert.ThrowsAny<CryptographicException>( () => key.TryExportEncryptedPkcs8PrivateKey( new byte[3], new PbeParameters((PbeEncryptionAlgorithm)15, HashAlgorithmName.SHA1, 72), Span<byte>.Empty, out _)); // Unknown hash algorithm Assert.ThrowsAny<CryptographicException>( () => key.ExportEncryptedPkcs8PrivateKey( new byte[3], new PbeParameters(PbeEncryptionAlgorithm.Aes192Cbc, new HashAlgorithmName("Potato"), 72))); Assert.ThrowsAny<CryptographicException>( () => key.TryExportEncryptedPkcs8PrivateKey( new byte[3], new PbeParameters(PbeEncryptionAlgorithm.Aes192Cbc, new HashAlgorithmName("Potato"), 72), Span<byte>.Empty, out _)); } } [Fact] public void DecryptPkcs12WithBytes() { using (T key = CreateKey()) { string charBased = "hello"; byte[] byteBased = Encoding.UTF8.GetBytes(charBased); byte[] encrypted = key.ExportEncryptedPkcs8PrivateKey( charBased, new PbeParameters( PbeEncryptionAlgorithm.TripleDes3KeyPkcs12, HashAlgorithmName.SHA1, 123)); Assert.ThrowsAny<CryptographicException>( () => key.ImportEncryptedPkcs8PrivateKey(byteBased, encrypted, out _)); } } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/62547", TestPlatforms.Android)] public void DecryptPkcs12PbeTooManyIterations() { // pbeWithSHAAnd3-KeyTripleDES-CBC with 600,001 iterations byte[] high3DesIterationKey = Convert.FromBase64String(@" MIG6MCUGCiqGSIb3DQEMAQMwFwQQWOZyFrGwhyGTEd2nbKuLSQIDCSfBBIGQCgPLkx0OwmK3lJ9o VAdJAg/2nvOhboOHciu5I6oh5dRkxeDjUJixsadd3uhiZb5v7UgiohBQsFv+PWU12rmz6sgWR9rK V2UqV6Y5vrHJDlNJGI+CQKzOTF7LXyOT+EqaXHD+25TM2/kcZjZrOdigkgQBAFhbfn2/hV/t0TPe Tj/54rcY3i0gXT6da/r/o+qV"); using (T key = CreateKey()) { Assert.ThrowsAny<CryptographicException>( () => key.ImportEncryptedPkcs8PrivateKey((ReadOnlySpan<char>)"test", high3DesIterationKey, out _)); } } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/62547", TestPlatforms.Android)] public void ReadWriteEc256EncryptedPkcs8_Pbes2HighIterations() { // pkcs5PBES2 hmacWithSHA256 aes128-CBC with 600,001 iterations ReadWriteBase64EncryptedPkcs8(@" MIH1MGAGCSqGSIb3DQEFDTBTMDIGCSqGSIb3DQEFDDAlBBA+rne0bUkwr614vLfQkwO4AgMJJ8Ew DAYIKoZIhvcNAgkFADAdBglghkgBZQMEAQIEEIm3c9r5igQ9Vlv1mKTZYp0EgZC8KZfmJtfYmsl4 Z0Dc85ugFvtFHVeRbcvfYmFns23WL3gpGQ0mj4BKxttX+WuDk9duAsCslNLvXFY7m3MQRkWA6QHT A8DiR3j0l5TGBkErbTUrjmB3ftvEmmF9mleRLj6qEYmmKdCV2Tfk1YBOZ2mpB9bpCPipUansyqWs xoMaz20Yx+2TSN5dSm2FcD+0YFI=", "test", new PbeParameters( PbeEncryptionAlgorithm.Aes128Cbc, HashAlgorithmName.SHA256, 600_001), EccTestData.GetNistP256ReferenceKey()); } private void ReadWriteBase64EncryptedPkcs8( string base64EncryptedPkcs8, string password, PbeParameters pbe, in ECParameters expected, bool isSupported=true) { if (isSupported) { ReadWriteKey( base64EncryptedPkcs8, expected, (T key, ReadOnlySpan<byte> source, out int read) => key.ImportEncryptedPkcs8PrivateKey(password, source, out read), key => key.ExportEncryptedPkcs8PrivateKey(password, pbe), (T key, Span<byte> destination, out int bytesWritten) => key.TryExportEncryptedPkcs8PrivateKey(password, pbe, destination, out bytesWritten), isEncrypted: true); } else { byte[] encrypted = Convert.FromBase64String(base64EncryptedPkcs8); using (T key = CreateKey()) { // Wrong password Assert.ThrowsAny<CryptographicException>( () => key.ImportEncryptedPkcs8PrivateKey(encrypted.AsSpan(1, 14), encrypted, out _)); Assert.ThrowsAny<CryptographicException>( () => key.ImportEncryptedPkcs8PrivateKey(password + password, encrypted, out _)); int bytesRead = -1; Exception e = Assert.ThrowsAny<Exception>( () => key.ImportEncryptedPkcs8PrivateKey(password, encrypted, out bytesRead)); Assert.True( e is PlatformNotSupportedException || e is CryptographicException, "e is PlatformNotSupportedException || e is CryptographicException"); Assert.Equal(-1, bytesRead); } } } private void ReadWriteBase64EncryptedPkcs8( string base64EncryptedPkcs8, byte[] passwordBytes, PbeParameters pbe, in ECParameters expected, bool isSupported=true) { if (isSupported) { ReadWriteKey( base64EncryptedPkcs8, expected, (T key, ReadOnlySpan<byte> source, out int read) => key.ImportEncryptedPkcs8PrivateKey(passwordBytes, source, out read), key => key.ExportEncryptedPkcs8PrivateKey(passwordBytes, pbe), (T key, Span<byte> destination, out int bytesWritten) => key.TryExportEncryptedPkcs8PrivateKey(passwordBytes, pbe, destination, out bytesWritten), isEncrypted: true); } else { byte[] encrypted = Convert.FromBase64String(base64EncryptedPkcs8); byte[] wrongPassword = new byte[passwordBytes.Length + 2]; RandomNumberGenerator.Fill(wrongPassword); using (T key = CreateKey()) { // Wrong password Assert.ThrowsAny<CryptographicException>( () => key.ImportEncryptedPkcs8PrivateKey(wrongPassword, encrypted, out _)); Assert.ThrowsAny<CryptographicException>( () => key.ImportEncryptedPkcs8PrivateKey((ReadOnlySpan<char>)"ThisBetterNotBeThePassword!", encrypted, out _)); int bytesRead = -1; Exception e = Assert.ThrowsAny<Exception>( () => key.ImportEncryptedPkcs8PrivateKey(passwordBytes, encrypted, out bytesRead)); Assert.True( e is PlatformNotSupportedException || e is CryptographicException, "e is PlatformNotSupportedException || e is CryptographicException"); Assert.Equal(-1, bytesRead); } } } private void ReadWriteBase64ECPrivateKey(string base64Pkcs8, in ECParameters expected, bool isSupported=true) { if (isSupported) { ReadWriteKey( base64Pkcs8, expected, (T key, ReadOnlySpan<byte> source, out int read) => key.ImportECPrivateKey(source, out read), key => key.ExportECPrivateKey(), (T key, Span<byte> destination, out int bytesWritten) => key.TryExportECPrivateKey(destination, out bytesWritten)); } else { using (T key = CreateKey()) { Exception e = Assert.ThrowsAny<Exception>( () => key.ImportECPrivateKey(Convert.FromBase64String(base64Pkcs8), out _)); Assert.True( e is PlatformNotSupportedException || e is CryptographicException, $"e should be PlatformNotSupportedException or CryptographicException.\n\te is {e.ToString()}"); } } } private void ReadWriteBase64Pkcs8(string base64Pkcs8, in ECParameters expected, bool isSupported=true) { if (isSupported) { ReadWriteKey( base64Pkcs8, expected, (T key, ReadOnlySpan<byte> source, out int read) => key.ImportPkcs8PrivateKey(source, out read), key => key.ExportPkcs8PrivateKey(), (T key, Span<byte> destination, out int bytesWritten) => key.TryExportPkcs8PrivateKey(destination, out bytesWritten)); } else { using (T key = CreateKey()) { Exception e = Assert.ThrowsAny<Exception>( () => key.ImportPkcs8PrivateKey(Convert.FromBase64String(base64Pkcs8), out _)); Assert.True( e is PlatformNotSupportedException || e is CryptographicException, "e is PlatformNotSupportedException || e is CryptographicException"); } } } private void ReadWriteBase64SubjectPublicKeyInfo( string base64SubjectPublicKeyInfo, in ECParameters expected, bool isSupported = true) { if (isSupported) { ECParameters expectedPublic = expected; expectedPublic.D = null; ReadWriteKey( base64SubjectPublicKeyInfo, expectedPublic, (T key, ReadOnlySpan<byte> source, out int read) => key.ImportSubjectPublicKeyInfo(source, out read), key => key.ExportSubjectPublicKeyInfo(), (T key, Span<byte> destination, out int written) => key.TryExportSubjectPublicKeyInfo(destination, out written), writePublicArrayFunc: PublicKeyWriteArrayFunc, writePublicSpanFunc: PublicKeyWriteSpanFunc); } else { using (T key = CreateKey()) { Exception e = Assert.ThrowsAny<Exception>( () => key.ImportSubjectPublicKeyInfo(Convert.FromBase64String(base64SubjectPublicKeyInfo), out _)); Assert.True( e is PlatformNotSupportedException || e is CryptographicException, "e is PlatformNotSupportedException || e is CryptographicException"); } } } private void ReadWriteKey( string base64, in ECParameters expected, ReadKeyAction readAction, Func<T, byte[]> writeArrayFunc, WriteKeyToSpanFunc writeSpanFunc, bool isEncrypted = false, Func<T, byte[]> writePublicArrayFunc = null, WriteKeyToSpanFunc writePublicSpanFunc = null) { bool isPrivateKey = expected.D != null; byte[] derBytes = Convert.FromBase64String(base64); byte[] arrayExport; byte[] tooBig; const int OverAllocate = 30; const int WriteShift = 6; using (T key = CreateKey()) { readAction(key, derBytes, out int bytesRead); Assert.Equal(derBytes.Length, bytesRead); arrayExport = writeArrayFunc(key); if (writePublicArrayFunc is not null) { byte[] publicArrayExport = writePublicArrayFunc(key); Assert.Equal(arrayExport, publicArrayExport); Assert.True(writePublicSpanFunc(key, publicArrayExport, out int publicExportWritten)); Assert.Equal(publicExportWritten, publicArrayExport.Length); Assert.Equal(arrayExport, publicArrayExport); } ECParameters ecParameters = key.ExportParameters(isPrivateKey); EccTestBase.AssertEqual(expected, ecParameters); } // It's not reasonable to assume that arrayExport and derBytes have the same // contents, because the SubjectPublicKeyInfo and PrivateKeyInfo formats both // have the curve identifier in the AlgorithmIdentifier.Parameters field, and // either the input or the output may have chosen to then not emit it in the // optional domainParameters field of the ECPrivateKey blob. // // Once we have exported the data to normalize it, though, we should see // consistency in the answer format. using (T key = CreateKey()) { Assert.ThrowsAny<CryptographicException>( () => readAction(key, arrayExport.AsSpan(1), out _)); Assert.ThrowsAny<CryptographicException>( () => readAction(key, arrayExport.AsSpan(0, arrayExport.Length - 1), out _)); readAction(key, arrayExport, out int bytesRead); Assert.Equal(arrayExport.Length, bytesRead); ECParameters ecParameters = key.ExportParameters(isPrivateKey); EccTestBase.AssertEqual(expected, ecParameters); Assert.False( writeSpanFunc(key, Span<byte>.Empty, out int bytesWritten), "Write to empty span"); Assert.Equal(0, bytesWritten); Assert.False( writeSpanFunc( key, derBytes.AsSpan(0, Math.Min(derBytes.Length, arrayExport.Length) - 1), out bytesWritten), "Write to too-small span"); Assert.Equal(0, bytesWritten); tooBig = new byte[arrayExport.Length + OverAllocate]; tooBig.AsSpan().Fill(0xC4); Assert.True(writeSpanFunc(key, tooBig.AsSpan(WriteShift), out bytesWritten)); Assert.Equal(arrayExport.Length, bytesWritten); Assert.Equal(0xC4, tooBig[WriteShift - 1]); Assert.Equal(0xC4, tooBig[WriteShift + bytesWritten + 1]); // If encrypted, the data should have had a random salt applied, so unstable. // Otherwise, we've normalized the data (even for private keys) so the output // should match what it output previously. if (isEncrypted) { Assert.NotEqual( arrayExport.ByteArrayToHex(), tooBig.AsSpan(WriteShift, bytesWritten).ByteArrayToHex()); } else { Assert.Equal( arrayExport.ByteArrayToHex(), tooBig.AsSpan(WriteShift, bytesWritten).ByteArrayToHex()); } } using (T key = CreateKey()) { readAction(key, tooBig.AsSpan(WriteShift), out int bytesRead); Assert.Equal(arrayExport.Length, bytesRead); arrayExport.AsSpan().Fill(0xCA); Assert.True( writeSpanFunc(key, arrayExport, out int bytesWritten), "Write to precisely allocated Span"); if (isEncrypted) { Assert.NotEqual( tooBig.AsSpan(WriteShift, bytesWritten).ByteArrayToHex(), arrayExport.ByteArrayToHex()); } else { Assert.Equal( tooBig.AsSpan(WriteShift, bytesWritten).ByteArrayToHex(), arrayExport.ByteArrayToHex()); } } } protected delegate void ReadKeyAction(T key, ReadOnlySpan<byte> source, out int bytesRead); protected delegate bool WriteKeyToSpanFunc(T key, Span<byte> destination, out int bytesWritten); } }
41.859304
150
0.619141
[ "MIT" ]
ChaseKnowlden/runtime
src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/EC/ECKeyFileTests.cs
55,338
C#
using Firebend.AutoCrud.EntityFramework.Elastic.Implementations.Abstractions; using Microsoft.Extensions.Logging; namespace Firebend.AutoCrud.EntityFramework.Elastic.Implementations { public class SqlServerDbCreator : AbstractDbCreator { public SqlServerDbCreator(ILogger<SqlServerDbCreator> logger) : base(logger) { } protected override string GetSqlCommand(string dbName) => $@" IF NOT EXISTS (SELECT * FROM sys.databases WHERE name = N'{dbName}') BEGIN CREATE DATABASE [{dbName}]; END;"; } }
28.578947
84
0.734807
[ "MIT" ]
djayd/auto-crud
Firebend.AutoCrud.EntityFramework.Elastic/Implementations/SqlServerDbCreator.cs
543
C#
using MasterServerToolkit.Networking; using System; namespace MasterServerToolkit.MasterServer { /// <summary> /// This class is a central class, which can be used by entities (clients and servers) /// that need to connect to master server, and access it's functionality /// </summary> public static class Mst { /// <summary> /// Version of the framework /// </summary> public static string Version => "v4.0.1"; /// <summary> /// Just name of the framework /// </summary> public static string Name => "MASTER SERVER TOOLKIT"; /// <summary> /// Main connection to master server /// </summary> public static IClientSocket Connection { get; private set; } /// <summary> /// Advanced master server framework settings /// </summary> public static MstAdvancedSettings Advanced { get; private set; } /// <summary> /// Collection of methods, that can be used BY CLIENT, connected to master server /// </summary> public static MstClient Client { get; private set; } /// <summary> /// Collection of methods, that can be used from your servers /// </summary> public static MstServer Server { get; private set; } /// <summary> /// Contains methods to help work with threads /// </summary> public static MstConcurrency Concurrency { get; private set; } /// <summary> /// Contains methods for creating some of the common types /// (server sockets, messages and etc) /// </summary> public static MstCreate Create { get; set; } /// <summary> /// Contains helper methods, that couldn't be added to any other /// object /// </summary> public static MstHelper Helper { get; set; } /// <summary> /// Contains security-related stuff (encryptions, permission requests) /// </summary> public static MstSecurity Security { get; private set; } /// <summary> /// Default events channel /// </summary> public static MstEventsChannel Events { get; private set; } /// <summary> /// Contains methods, that work with runtime data /// </summary> public static MstRuntime Runtime { get; private set; } /// <summary> /// Contains command line / terminal values, which were provided /// when starting the process /// </summary> public static MstArgs Args { get; private set; } public static MstProperties Options { get; private set; } static Mst() { // Initialize helpers to work with MSF Helper = new MstHelper(); // Initialize advanced settings Advanced = new MstAdvancedSettings(); // Initialize runtime data Runtime = new MstRuntime(); // Initialize work with command line arguments Args = new MstArgs(); // List of options you can use in game Options = new MstProperties(); // Create a default connection Connection = Advanced.ClientSocketFactory(); // Initialize parts of framework, that act as "clients" Client = new MstClient(Connection); Server = new MstServer(Connection); Security = new MstSecurity(Connection); // Other stuff Create = new MstCreate(); Concurrency = new MstConcurrency(); Events = new MstEventsChannel("default", true); } } }
32.575221
90
0.573485
[ "MIT" ]
itsnotyoutoday/MST
Assets/MasterServerToolkit/MasterServer/Scripts/Mst/Mst.cs
3,683
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using Microsoft.ML.Probabilistic.Compiler; using Microsoft.ML.Probabilistic.Collections; using Microsoft.ML.Probabilistic.Compiler.CodeModel; namespace Microsoft.ML.Probabilistic.Models { #if SUPPRESS_XMLDOC_WARNINGS #pragma warning disable 1591 #endif internal class MethodInvoke : IModelExpression { /// <summary> /// Helps build class declarations /// </summary> private static readonly CodeBuilder Builder = CodeBuilder.Instance; // The factor or constraint method internal MethodInfo method; // The arguments internal List<IModelExpression> args = new List<IModelExpression>(); // The return value (or null if void) internal IModelExpression returnValue; // The operator if this method was created from an operator internal Variable.Operator? op = null; // Attributes of the method invocation i.e. the factor or constraint. internal List<ICompilerAttribute> attributes = new List<ICompilerAttribute>(); internal List<IStatementBlock> Containers { get; } // Provides global ordering for ModelBuilder internal readonly int timestamp; private static readonly GlobalCounter globalCounter = new GlobalCounter(); internal static int GetTimestamp() { return globalCounter.GetNext(); } internal MethodInvoke(MethodInfo method, params IModelExpression[] args) : this(StatementBlock.GetOpenBlocks(), method, args) { } internal MethodInvoke(IEnumerable<IStatementBlock> containers, MethodInfo method, params IModelExpression[] args) { this.timestamp = GetTimestamp(); this.method = method; this.args.AddRange(args); this.Containers = new List<IStatementBlock>(containers); foreach (IModelExpression arg in args) { if (ReferenceEquals(arg, null)) throw new ArgumentNullException(); if (arg is Variable) { Variable v = (Variable) arg; if (v.IsObserved) continue; foreach (ConditionBlock cb in v.GetContainers<ConditionBlock>()) { if (!this.Containers.Contains(cb)) { throw new InvalidOperationException($"{arg} was created in condition {cb} and cannot be used outside. " + $"To give {arg} a conditional definition, use SetTo inside {cb} rather than assignment (=). " + $"If you are using GetCopyFor, make sure you call GetCopyFor outside of conflicting conditional statements."); } } } } foreach (ConditionBlock cb in StatementBlock.EnumerateBlocks<ConditionBlock>(containers)) { cb.ConditionVariableUntyped.constraints.Add(this); } } /// <summary> /// The name of the method /// </summary> public string Name { get { return method.Name; } } /// <summary> /// The method arguments /// </summary> public List<IModelExpression> Arguments { get { return args; } } /// <summary> /// The expression the return value of the method will be assigned to. /// </summary> public IModelExpression ReturnValue { get { return returnValue; } } public void AddAttribute(ICompilerAttribute attr) { InferenceEngine.InvalidateAllEngines(this); attributes.Add(attr); } /// <summary> /// Inline method for adding an attribute to a method invoke. This method /// returns the method invoke object, so that is can be used in an inline expression. /// </summary> /// <param name="attr">The attribute to add</param> /// <returns>This object</returns> public MethodInvoke Attrib(ICompilerAttribute attr) { AddAttribute(attr); return this; } /// <summary> /// Get all attributes of this variable having type AttributeType. /// </summary> /// <typeparam name="AttributeType"></typeparam> /// <returns></returns> public IEnumerable<AttributeType> GetAttributes<AttributeType>() where AttributeType : ICompilerAttribute { // find the base variable foreach (ICompilerAttribute attr in attributes) { if (attr is AttributeType) yield return (AttributeType) attr; } } public IExpression GetExpression() { IExpression expr = GetMethodInvokeExpression(); if (returnValue == null) return expr; expr = Builder.AssignExpr(returnValue.GetExpression(), expr); return expr; } /// <summary> /// True if the expression is an operator applied to a loop index and all other variable references are observed. /// </summary> /// <returns></returns> internal bool CanBeInlined() { if (op == null) return false; bool hasLoopIndex = false; for (int i = 0; i < args.Count; i++) { if (args[i] is Variable<int> v) { if (v.IsLoopIndex) hasLoopIndex = true; else if (!IsDeterminedByObservations(v)) return false; } else return false; } return hasLoopIndex; } private static bool IsDeterminedByObservations(Variable<int> v) { if (v.IsObserved) return true; else if (v.definition != null) return v.definition.AllVariablesAreObserved(); else return v.conditionalDefinitions.Values.All(condDef => condDef.AllVariablesAreObserved()); } private bool AllVariablesAreObserved() { if (op == null) return false; return args.All(arg => (arg is Variable<int> v) && IsDeterminedByObservations(v)); } internal IExpression GetMethodInvokeExpression(bool inline = false) { IExpression[] argExprs = new IExpression[args.Count]; for (int i = 0; i < argExprs.Length; i++) { argExprs[i] = args[i].GetExpression(); } if (inline || CanBeInlined()) { if (op == Variable.Operator.Plus) return Builder.BinaryExpr(argExprs[0], BinaryOperator.Add, argExprs[1]); else if (op == Variable.Operator.Minus) return Builder.BinaryExpr(argExprs[0], BinaryOperator.Subtract, argExprs[1]); else if (op == Variable.Operator.LessThan) return Builder.BinaryExpr(argExprs[0], BinaryOperator.LessThan, argExprs[1]); else if (op == Variable.Operator.LessThanOrEqual) return Builder.BinaryExpr(argExprs[0], BinaryOperator.LessThanOrEqual, argExprs[1]); else if (op == Variable.Operator.GreaterThan) return Builder.BinaryExpr(argExprs[0], BinaryOperator.GreaterThan, argExprs[1]); else if (op == Variable.Operator.GreaterThanOrEqual) return Builder.BinaryExpr(argExprs[0], BinaryOperator.GreaterThanOrEqual, argExprs[1]); else if (op == Variable.Operator.Equal) return Builder.BinaryExpr(argExprs[0], BinaryOperator.ValueEquality, argExprs[1]); else if (op == Variable.Operator.NotEqual) return Builder.BinaryExpr(argExprs[0], BinaryOperator.ValueInequality, argExprs[1]); } IMethodInvokeExpression imie; if (method.IsGenericMethod && !method.ContainsGenericParameters) { imie = Builder.StaticGenericMethod(method, argExprs); } else { imie = Builder.StaticMethod(method, argExprs); } return imie; } public override string ToString() { StringBuilder sb = new StringBuilder(method.Name); sb.Append('('); bool isFirst = true; foreach (IModelExpression arg in args) { if (!isFirst) sb.Append(','); else isFirst = false; if(arg != null) sb.Append(arg.ToString()); } sb.Append(')'); return sb.ToString(); } internal IEnumerable<IModelExpression> returnValueAndArgs() { if (returnValue != null) yield return returnValue; foreach (IModelExpression arg in args) yield return arg; } /// <summary> /// Get the set of ranges used as indices in the arguments of the MethodInvoke, that are not included in its ForEach containers. /// </summary> /// <returns></returns> internal Set<Range> GetLocalRangeSet() { Set<Range> ranges = new Set<Range>(); foreach (IModelExpression arg in returnValueAndArgs()) ForEachRange(arg, ranges.Add); foreach (IStatementBlock b in Containers) { if (b is HasRange) { HasRange br = (HasRange) b; ranges.Remove(br.Range); } } return ranges; } /// <summary> /// Get the set of ranges used as indices in the arguments of the MethodInvoke, that are not included in its ForEach containers. /// </summary> /// <returns></returns> internal List<Range> GetLocalRangeList() { List<Range> ranges = new List<Range>(); foreach (IModelExpression arg in returnValueAndArgs()) { ForEachRange(arg, delegate(Range r) { if (!ranges.Contains(r)) ranges.Add(r); }); } foreach (IStatementBlock b in Containers) { if (b is HasRange) { HasRange br = (HasRange) b; ranges.Remove(br.Range); } } return ranges; } internal static void ForEachRange(IModelExpression arg, Action<Range> action) { if (arg is Range) { action((Range) arg); return; } else if (arg is Variable) { Variable v = (Variable) arg; if (v.IsLoopIndex) { action(v.loopRange); } if (v.IsArrayElement) { ForEachRange(v.ArrayVariable, action); // must add item indices after array's indices foreach (IModelExpression expr in v.indices) { ForEachRange(expr, action); } } } } /// <summary> /// Get a dictionary mapping all array indexer expressions (including sub-expressions) to a list of their Range indexes, in order. /// </summary> /// <param name="args"></param> /// <returns></returns> internal static Dictionary<IModelExpression, List<List<Range>>> GetRangeBrackets(IEnumerable<IModelExpression> args) { Dictionary<IModelExpression, List<List<Range>>> dict = new Dictionary<IModelExpression, List<List<Range>>>(); foreach (IModelExpression arg in args) { List<List<Range>> brackets = GetRangeBrackets(arg, dict); dict[arg] = brackets; } return dict; } /// <summary> /// If arg is an array indexer expression, get a list of all Range indexes, in order. Indexes that are not Ranges instead get their Ranges added to dict. /// </summary> /// <param name="arg"></param> /// <param name="dict"></param> /// <returns></returns> internal static List<List<Range>> GetRangeBrackets(IModelExpression arg, IDictionary<IModelExpression, List<List<Range>>> dict) { if (arg is Variable) { Variable v = (Variable) arg; if (v.IsArrayElement) { List<List<Range>> brackets = GetRangeBrackets(v.ArrayVariable, dict); List<Range> indices = new List<Range>(); // must add item indices after array's indices foreach (IModelExpression expr in v.indices) { if (expr is Range) indices.Add((Range) expr); else { List<List<Range>> argBrackets = GetRangeBrackets(expr, dict); dict[expr] = argBrackets; } } brackets.Add(indices); return brackets; } } return new List<List<Range>>(); } internal static int CompareRanges(IDictionary<IModelExpression, List<List<Range>>> dict, Range a, Range b) { foreach (List<List<Range>> brackets in dict.Values) { bool aInPreviousBracket = false; bool bInPreviousBracket = false; foreach (List<Range> bracket in brackets) { bool aInThisBracket = false; bool bInThisBracket = false; foreach (Range range in bracket) { if (range == a) aInThisBracket = true; if (range == b) bInThisBracket = true; } if (bInThisBracket && aInPreviousBracket && !bInPreviousBracket) return -1; if (aInThisBracket && bInPreviousBracket && !aInPreviousBracket) return 1; aInPreviousBracket = aInThisBracket; bInPreviousBracket = bInThisBracket; } } return 0; } /// <summary> /// True if arg is indexed by at least the given ranges. /// </summary> /// <param name="arg"></param> /// <param name="ranges"></param> /// <returns></returns> internal static bool IsIndexedByAll(IModelExpression arg, ICollection<Range> ranges) { Set<Range> argRanges = new Set<Range>(); ForEachRange(arg, argRanges.Add); foreach (Range r in ranges) { if (!argRanges.Contains(r)) return false; } return true; } /*internal string GetReturnValueName() { if (method == null) return ""; if (op != null) { return args[0].Name + " " + op + " " + args[1].Name; } string; }*/ } #if SUPPRESS_XMLDOC_WARNINGS #pragma warning restore 1591 #endif }
38.024272
162
0.53964
[ "MIT" ]
christabella/infer
src/Compiler/Infer/Models/MethodInvoke.cs
15,666
C#
using System; using System.Collections.Generic; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using MS.Core; namespace System.Security.AccessControl { public static class __ControlFlags { } }
18.75
39
0.773333
[ "MIT" ]
RixianOpenTech/RxWrappers
Source/Wrappers/mscorlib/System.Security.AccessControl.ControlFlags.cs
225
C#
namespace BioinformaticsTranslateTool { partial class Form1 { /// <summary> ///Gerekli tasarımcı değişkeni. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> ///Kullanılan tüm kaynakları temizleyin. /// </summary> ///<param name="disposing">yönetilen kaynaklar dispose edilmeliyse doğru; aksi halde yanlış.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer üretilen kod /// <summary> /// Tasarımcı desteği için gerekli metot - bu metodun ///içeriğini kod düzenleyici ile değiştirmeyin. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1)); this.clear2 = new System.Windows.Forms.PictureBox(); this.selection2 = new System.Windows.Forms.ComboBox(); this.selection1 = new System.Windows.Forms.ComboBox(); this.clear1 = new System.Windows.Forms.PictureBox(); this.swap = new System.Windows.Forms.PictureBox(); this.label2 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.translate = new System.Windows.Forms.PictureBox(); this.sequence2 = new System.Windows.Forms.RichTextBox(); this.sequence1 = new System.Windows.Forms.RichTextBox(); this.toolTip1 = new System.Windows.Forms.ToolTip(this.components); ((System.ComponentModel.ISupportInitialize)(this.clear2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.clear1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.swap)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.translate)).BeginInit(); this.SuspendLayout(); // // clear2 // this.clear2.Cursor = System.Windows.Forms.Cursors.Hand; this.clear2.Image = ((System.Drawing.Image)(resources.GetObject("clear2.Image"))); this.clear2.Location = new System.Drawing.Point(728, 22); this.clear2.Name = "clear2"; this.clear2.Size = new System.Drawing.Size(51, 44); this.clear2.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; this.clear2.TabIndex = 26; this.clear2.TabStop = false; this.toolTip1.SetToolTip(this.clear2, "Delete Sequence2"); this.clear2.Click += new System.EventHandler(this.clear2_Click); // // selection2 // this.selection2.BackColor = System.Drawing.Color.LightSlateGray; this.selection2.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.selection2.FlatStyle = System.Windows.Forms.FlatStyle.System; this.selection2.Font = new System.Drawing.Font("Consolas", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(162))); this.selection2.ForeColor = System.Drawing.Color.White; this.selection2.FormattingEnabled = true; this.selection2.Items.AddRange(new object[] { "Amino Acid", "Protein", "DNA"}); this.selection2.Location = new System.Drawing.Point(436, 32); this.selection2.Name = "selection2"; this.selection2.Size = new System.Drawing.Size(212, 26); this.selection2.TabIndex = 25; // // selection1 // this.selection1.BackColor = System.Drawing.Color.LightSlateGray; this.selection1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.selection1.FlatStyle = System.Windows.Forms.FlatStyle.System; this.selection1.Font = new System.Drawing.Font("Consolas", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(162))); this.selection1.ForeColor = System.Drawing.Color.White; this.selection1.FormattingEnabled = true; this.selection1.Items.AddRange(new object[] { "DNA", "Amino Acid"}); this.selection1.Location = new System.Drawing.Point(14, 32); this.selection1.Name = "selection1"; this.selection1.Size = new System.Drawing.Size(212, 26); this.selection1.TabIndex = 24; // // clear1 // this.clear1.Cursor = System.Windows.Forms.Cursors.Hand; this.clear1.Image = ((System.Drawing.Image)(resources.GetObject("clear1.Image"))); this.clear1.Location = new System.Drawing.Point(289, 21); this.clear1.Name = "clear1"; this.clear1.Size = new System.Drawing.Size(51, 45); this.clear1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; this.clear1.TabIndex = 23; this.clear1.TabStop = false; this.toolTip1.SetToolTip(this.clear1, "Delete Sequence1"); this.clear1.Click += new System.EventHandler(this.clear1_Click); // // swap // this.swap.Cursor = System.Windows.Forms.Cursors.Hand; this.swap.Image = ((System.Drawing.Image)(resources.GetObject("swap.Image"))); this.swap.Location = new System.Drawing.Point(346, 197); this.swap.Name = "swap"; this.swap.Size = new System.Drawing.Size(84, 74); this.swap.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; this.swap.TabIndex = 22; this.swap.TabStop = false; this.toolTip1.SetToolTip(this.swap, "Swap Sequences"); this.swap.Click += new System.EventHandler(this.swap_Click); // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Consolas", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(162))); this.label2.ForeColor = System.Drawing.Color.White; this.label2.Location = new System.Drawing.Point(432, 9); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(216, 19); this.label2.TabIndex = 21; this.label2.Text = "Please enter a sequence"; // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Consolas", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(162))); this.label1.ForeColor = System.Drawing.Color.White; this.label1.Location = new System.Drawing.Point(10, 10); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(216, 19); this.label1.TabIndex = 20; this.label1.Text = "Please enter a sequence"; // // translate // this.translate.Cursor = System.Windows.Forms.Cursors.Hand; this.translate.Image = ((System.Drawing.Image)(resources.GetObject("translate.Image"))); this.translate.Location = new System.Drawing.Point(346, 95); this.translate.Name = "translate"; this.translate.Size = new System.Drawing.Size(84, 74); this.translate.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; this.translate.TabIndex = 19; this.translate.TabStop = false; this.toolTip1.SetToolTip(this.translate, "Translate"); this.translate.Click += new System.EventHandler(this.translate_Click); // // sequence2 // this.sequence2.BackColor = System.Drawing.Color.LightSlateGray; this.sequence2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.sequence2.Font = new System.Drawing.Font("Consolas", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(162))); this.sequence2.ForeColor = System.Drawing.Color.White; this.sequence2.Location = new System.Drawing.Point(436, 72); this.sequence2.Name = "sequence2"; this.sequence2.ReadOnly = true; this.sequence2.Size = new System.Drawing.Size(343, 234); this.sequence2.TabIndex = 18; this.sequence2.Text = ""; // // sequence1 // this.sequence1.BackColor = System.Drawing.Color.LightSlateGray; this.sequence1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.sequence1.Font = new System.Drawing.Font("Consolas", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(162))); this.sequence1.ForeColor = System.Drawing.Color.White; this.sequence1.Location = new System.Drawing.Point(14, 72); this.sequence1.Name = "sequence1"; this.sequence1.Size = new System.Drawing.Size(326, 234); this.sequence1.TabIndex = 17; this.sequence1.Text = ""; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.LightSlateGray; this.ClientSize = new System.Drawing.Size(790, 325); this.Controls.Add(this.clear2); this.Controls.Add(this.selection2); this.Controls.Add(this.selection1); this.Controls.Add(this.clear1); this.Controls.Add(this.swap); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.translate); this.Controls.Add(this.sequence2); this.Controls.Add(this.sequence1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; this.MaximizeBox = false; this.Name = "Form1"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Translate Tool"; ((System.ComponentModel.ISupportInitialize)(this.clear2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.clear1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.swap)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.translate)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.PictureBox clear2; private System.Windows.Forms.ToolTip toolTip1; private System.Windows.Forms.ComboBox selection2; private System.Windows.Forms.ComboBox selection1; private System.Windows.Forms.PictureBox clear1; private System.Windows.Forms.PictureBox swap; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label1; private System.Windows.Forms.PictureBox translate; private System.Windows.Forms.RichTextBox sequence2; private System.Windows.Forms.RichTextBox sequence1; } }
52.29386
161
0.600268
[ "MIT" ]
tolgailtuzer/Bioinformatics
SequenceTranslationTool/BioinformaticsTranslateTool/Form1.Designer.cs
11,946
C#
#region copyright // <copyright file="DebugStateChangedEventArgs.cs" company="Christopher McNeely"> // The MIT License (MIT) // Copyright (c) Christopher McNeely // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT // NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // </copyright> #endregion using System; namespace Evands.Pellucid.Diagnostics { /// <summary> /// Information provided when the debug state for the program changes. /// </summary> public class DebugStateChangedEventArgs : EventArgs { /// <summary> /// Initializes a new instance of the <see cref="DebugStateChangedEventArgs"/> class. /// </summary> /// <param name="isDebugEnabled">A value indicating whether the debug state is enabled.</param> public DebugStateChangedEventArgs(bool isDebugEnabled) { IsDebugEnabled = isDebugEnabled; } /// <summary> /// Gets a value indicating whether debugging is on or off for the program. /// </summary> public bool IsDebugEnabled { get; private set; } } }
46.477273
129
0.718826
[ "MIT" ]
ProfessorAire/Evands.Pellucid-Crestron
src/Evands.Pellucid/Diagnostics/DebugStateChangedEventArgs.cs
2,047
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.InteropServices; using SlimDX; using VVVV.PluginInterfaces.V1; using VVVV.PluginInterfaces.V2; using VVVV.DX11; using FeralTic.DX11; using FeralTic.DX11.Resources; using AE_HapTools; using System.IO; namespace VVVV.HapTreats.Nodes { [PluginInfo(Name = "HapAVITexture", Category = "DX11.Texture2d", Version = "1.0", Author = "A&E")] public class AE_HapAVITextureNode : IPluginEvaluate, IDisposable, IDX11ResourceHost { [Input("Filename", StringType = StringType.Filename, IsSingle = true)] protected IDiffSpread<string> inputFilename; [Input("Frame Index", IsSingle = true)] protected IDiffSpread<int> frameIndex; [Output("Texture")] protected Pin<DX11Resource<DX11Texture2D>> outputTexture; [Output("Current Frame Format")] protected ISpread<SlimDX.DXGI.Format> currentFrameFormat; [Output("Size")] protected ISpread<Vector2> size; [Output("Frame Rate")] protected ISpread<float> frameRate; [Output("Frame Count")] protected ISpread<int> frameCount; private AE_HapAVI avi; private bool isValid = false; private bool currentFrameChanged = false; private AE_HapFrame currentFrame; private void reset() { isValid = false; size[0] = new Vector2(); frameCount[0] = 0; outputTexture[0] = new DX11Resource<DX11Texture2D>(); currentFrame = null; } private void init() { if (inputFilename[0] == null || ! File.Exists(inputFilename[0])) { reset(); return; } avi = new AE_HapAVI(inputFilename[0]); size[0] = new Vector2(avi.imageWidth, avi.imageHeight); frameRate[0] = avi.frameRate; frameCount[0] = avi.frameCount; outputTexture[0] = new DX11Resource<DX11Texture2D>(); isValid = true; getFrameAtIndex(0); } private void getFrameAtIndex(int index) { if (!isValid) return; currentFrame = avi.getHapFrameAndDDSHeaderAtIndex(index % avi.frameCount); currentFrameFormat[0] = (SlimDX.DXGI.Format)currentFrame.compressionType; currentFrameChanged = true; } public void Evaluate(int spreadMax) { if (inputFilename.IsChanged) init(); if (frameIndex.IsChanged) getFrameAtIndex(frameIndex[0]); } public void Dispose() { if (outputTexture[0] != null) outputTexture[0].Dispose(); } public void Update(DX11RenderContext context) { if (!isValid) return; if (!currentFrameChanged) return; var tex = outputTexture[0][context]; if (tex != null) tex.Dispose(); SlimDX.Direct3D11.ImageLoadInformation li = SlimDX.Direct3D11.ImageLoadInformation.FromDefaults(); li.MipLevels = 1; outputTexture[0][context] = DX11Texture2D.FromMemory(context, currentFrame.frameData, li); currentFrameChanged = false; } public void Destroy(DX11RenderContext context, bool force) { if (outputTexture[0] != null) outputTexture[0].Dispose(); } } }
27.34375
110
0.603143
[ "BSD-3-Clause" ]
artistsandengineers/AE_HapTools
vvvv-HapTreats/vvvv-HapTreats/AE_HapAVITextureNode.cs
3,502
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: Microsoft.AspNetCore.Mvc.ApplicationParts.ProvideApplicationPartFactoryAttribute("Microsoft.AspNetCore.Mvc.ApplicationParts.CompiledRazorAssemblyApplicationPartFac" + "tory, Microsoft.AspNetCore.Mvc.Razor")] [assembly: System.Reflection.AssemblyCompanyAttribute("SolirusTest")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyProductAttribute("SolirusTest")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyTitleAttribute("SolirusTest.Views")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
46.615385
177
0.688119
[ "MIT" ]
Fabus94/NeuraLinkLightsDemoFabioAleksiev
obj/Debug/netcoreapp2.1/IriSearch.RazorTargetAssemblyInfo.cs
1,212
C#
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using Mono.Cecil; namespace DotNetApis.Cecil { public static partial class CecilExtensions { /// <summary> /// Enumerates this type reference and all of its declaring type, walking "up" from most-nested to top-level. /// </summary> private static IEnumerable<TypeReference> ThisAndDeclaringTypes(TypeReference @this) { yield return @this; while (@this.DeclaringType != null) { @this = @this.DeclaringType; yield return @this; } } /// <summary> /// Enumerates this type reference and all of its declaring type, walking "down" from the top-level type and ending at this type reference. /// </summary> public static IEnumerable<TypeReference> DeclaringTypesAndThis(this TypeReference @this) => ThisAndDeclaringTypes(@this).Reverse(); /// <summary> /// Returns the base type (if other than Object, ValueType, MulticastDelegate, or Enum) and the interfaces for this type. Does not return implicitly-implemented interfaces. /// </summary> public static IEnumerable<TypeReference> BaseTypeAndInterfaces(this TypeDefinition type) { var baseType = type.BaseType; if (baseType != null && baseType.FullName != "System.Object" && baseType.FullName != "System.ValueType" && baseType.FullName != "System.Enum" && baseType.FullName != "System.MulticastDelegate") yield return baseType; foreach (var i in type.Interfaces) yield return i.InterfaceType; } /// <summary> /// Whether an enum type definition has the <c>[Flags]</c> attribute. /// </summary> public static bool EnumHasFlagsAttribute(this TypeDefinition @this) => @this.CustomAttributes.Any(x => x.AttributeType.Namespace == "System" && x.AttributeType.Name == "FlagsAttribute"); } }
42.612245
205
0.641762
[ "MIT" ]
StephenCleary/DotNetApis
service/DotNetApis.Cecil/CecilExtensions.Types.cs
2,090
C#
using System; using UIKit; using Foundation; namespace Forms9Patch.iOS { /// <summary> /// UIT ext view extensions. /// </summary> public static class UITextViewExtensions { /// <summary> /// Numbers the of lines. /// </summary> /// <returns>The of lines.</returns> /// <param name="view">View.</param> public static uint NumberOfLines(this UITextView view) { var layoutManager = view.LayoutManager; var numberOfGlyphs = (uint)layoutManager.NumberOfGlyphs; //var lineRange = new NSRange(0, 1); nuint index = 0; uint numberOfLines = 0; while (index < numberOfGlyphs) { layoutManager.GetLineFragmentRect(index, out NSRange range); index = (nuint)(range.Location + range.Length); numberOfLines++; } return numberOfLines; } public static void PropertiesFromControlState(this UILabel label, TextControlState state) { if (state.AttributedString != null) label.AttributedText = state.AttributedString; else label.Text = state.Text; label.Font = state.Font; label.TextAlignment = state.HorizontalTextAlignment; label.LineBreakMode = state.LineBreakMode; } internal static NSMutableAttributedString AddCharacterSpacing(this NSAttributedString attributedString, string text, double characterSpacing) { if (attributedString == null && characterSpacing == 0) return null; NSMutableAttributedString mutableAttributedString = attributedString as NSMutableAttributedString; if (attributedString == null || attributedString.Length == 0) { mutableAttributedString = text == null ? new NSMutableAttributedString() : new NSMutableAttributedString(text); } else { mutableAttributedString = new NSMutableAttributedString(attributedString); } AddKerningAdjustment(mutableAttributedString, text, characterSpacing); return mutableAttributedString; } internal static void AddKerningAdjustment(NSMutableAttributedString mutableAttributedString, string text, double characterSpacing) { if (!string.IsNullOrEmpty(text)) { if (characterSpacing == 0 && !mutableAttributedString.HasCharacterAdjustment()) return; mutableAttributedString.AddAttribute ( UIStringAttributeKey.KerningAdjustment, NSObject.FromObject(characterSpacing), new NSRange(0, text.Length - 1) ); } } internal static bool HasCharacterAdjustment(this NSMutableAttributedString mutableAttributedString) { if (mutableAttributedString == null) return false; NSRange removalRange; var attributes = mutableAttributedString.GetAttributes(0, out removalRange); for (uint i = 0; i < attributes.Count; i++) if (attributes.Keys[i] is NSString nSString && nSString == UIStringAttributeKey.KerningAdjustment) return true; return false; } } }
34.57
149
0.59271
[ "MIT" ]
Mourad57/Forms9Patch
Forms9Patch/Forms9Patch.iOS/Extensions/UITextViewExtensions.cs
3,459
C#
using Microsoft.AspNetCore.SignalR; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SignalRSample.Hubs { public class ChatHub : Hub { public override async Task OnConnectedAsync() { await Clients.All.SendAsync("Broadcast", "server", $"a new client connected {this.Context.ConnectionId}"); await base.OnConnectedAsync(); } public override async Task OnDisconnectedAsync(Exception exception) { await Clients.All.SendAsync("Broadcast", "server", $"client {this.Context.ConnectionId} disconnected, {exception.GetType().Name}"); await base.OnDisconnectedAsync(exception); } public async Task MyMessage(string user, string message) { await base.Clients.All.SendAsync("Broadcast", user, message); } } }
30.16129
96
0.636364
[ "MIT" ]
christiannagel/aspnetcoredec2019
day4/SignalRSample/SignalRSample/Hubs/ChatHub.cs
937
C#
using System; using System.Collections.Generic; using Shadowsocks.Encryption.Exception; namespace Shadowsocks.Encryption.Stream { public class StreamSodiumEncryptor : StreamEncryptor, IDisposable { const int CIPHER_SALSA20 = 1; const int CIPHER_CHACHA20 = 2; const int CIPHER_CHACHA20_IETF = 3; const int SODIUM_BLOCK_SIZE = 64; protected int _encryptBytesRemaining; protected int _decryptBytesRemaining; protected ulong _encryptIC; protected ulong _decryptIC; protected byte[] _encryptBuf; protected byte[] _decryptBuf; public StreamSodiumEncryptor(string method, string password) : base(method, password) { _encryptBuf = new byte[MAX_INPUT_SIZE + SODIUM_BLOCK_SIZE]; _decryptBuf = new byte[MAX_INPUT_SIZE + SODIUM_BLOCK_SIZE]; } private static Dictionary<string, EncryptorInfo> _ciphers = new Dictionary<string, EncryptorInfo> { { "salsa20", new EncryptorInfo(32, 8, CIPHER_SALSA20) }, { "chacha20", new EncryptorInfo(32, 8, CIPHER_CHACHA20) }, { "chacha20-ietf", new EncryptorInfo(32, 12, CIPHER_CHACHA20_IETF) } }; protected override Dictionary<string, EncryptorInfo> getCiphers() { return _ciphers; } public static List<string> SupportedCiphers() { return new List<string>(_ciphers.Keys); } protected override void cipherUpdate(bool isEncrypt, int length, byte[] buf, byte[] outbuf) { // TODO write a unidirection cipher so we don't have to if if if int bytesRemaining; ulong ic; byte[] sodiumBuf; byte[] iv; int ret = -1; if (isEncrypt) { bytesRemaining = _encryptBytesRemaining; ic = _encryptIC; sodiumBuf = _encryptBuf; iv = _encryptIV; } else { bytesRemaining = _decryptBytesRemaining; ic = _decryptIC; sodiumBuf = _decryptBuf; iv = _decryptIV; } int padding = bytesRemaining; Buffer.BlockCopy(buf, 0, sodiumBuf, padding, length); switch (_cipher) { case CIPHER_SALSA20: ret = Sodium.crypto_stream_salsa20_xor_ic(sodiumBuf, sodiumBuf, (ulong)(padding + length), iv, ic, _key); break; case CIPHER_CHACHA20: ret = Sodium.crypto_stream_chacha20_xor_ic(sodiumBuf, sodiumBuf, (ulong)(padding + length), iv, ic, _key); break; case CIPHER_CHACHA20_IETF: ret = Sodium.crypto_stream_chacha20_ietf_xor_ic(sodiumBuf, sodiumBuf, (ulong)(padding + length), iv, (uint)ic, _key); break; } if (ret != 0) throw new CryptoErrorException(); Buffer.BlockCopy(sodiumBuf, padding, outbuf, 0, length); padding += length; ic += (ulong)padding / SODIUM_BLOCK_SIZE; bytesRemaining = padding % SODIUM_BLOCK_SIZE; if (isEncrypt) { _encryptBytesRemaining = bytesRemaining; _encryptIC = ic; } else { _decryptBytesRemaining = bytesRemaining; _decryptIC = ic; } } public override void Dispose() { } } }
34.527778
138
0.53875
[ "Apache-2.0" ]
1195992737/shadowsocks-windows
shadowsocks-csharp/Encryption/Stream/StreamSodiumEncryptor.cs
3,731
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by \generate-code.bat. // // Changes to this file will be lost when the code is regenerated. // The build server regenerates the code before each build and a pre-build // step will regenerate the code on each local build. // // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. // Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // </auto-generated> //------------------------------------------------------------------------------ // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; using UnitsNet.Units; namespace UnitsNet { /// <inheritdoc /> /// <summary> /// In chemistry, the molar mass M is a physical property defined as the mass of a given substance (chemical element or chemical compound) divided by the amount of substance. /// </summary> public struct MolarMass { /// <summary> /// The numeric value this quantity was constructed with. /// </summary> private readonly double _value; /// <summary> /// The unit this quantity was constructed with. /// </summary> private readonly MolarMassUnit _unit; /// <summary> /// The numeric value this quantity was constructed with. /// </summary> public double Value => _value; /// <inheritdoc /> public MolarMassUnit Unit => _unit; /// <summary> /// Creates the quantity with the given numeric value and unit. /// </summary> /// <param name="value">The numeric value to construct this quantity with.</param> /// <param name="unit">The unit representation to construct this quantity with.</param> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> public MolarMass(double value, MolarMassUnit unit) { _value = value; _unit = unit; } /// <summary> /// The base unit of Duration, which is Second. All conversions go via this value. /// </summary> public static MolarMassUnit BaseUnit { get; } = MolarMassUnit.KilogramPerMole; /// <summary> /// Represents the largest possible value of Duration /// </summary> public static MolarMass MaxValue { get; } = new MolarMass(double.MaxValue, BaseUnit); /// <summary> /// Represents the smallest possible value of Duration /// </summary> public static MolarMass MinValue { get; } = new MolarMass(double.MinValue, BaseUnit); /// <summary> /// Gets an instance of this quantity with a value of 0 in the base unit Second. /// </summary> public static MolarMass Zero { get; } = new MolarMass(0, BaseUnit); #region Conversion Properties /// <summary> /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MolarMassUnit.CentigramPerMole"/> /// </summary> public double CentigramsPerMole => As(MolarMassUnit.CentigramPerMole); /// <summary> /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MolarMassUnit.DecagramPerMole"/> /// </summary> public double DecagramsPerMole => As(MolarMassUnit.DecagramPerMole); /// <summary> /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MolarMassUnit.DecigramPerMole"/> /// </summary> public double DecigramsPerMole => As(MolarMassUnit.DecigramPerMole); /// <summary> /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MolarMassUnit.GramPerMole"/> /// </summary> public double GramsPerMole => As(MolarMassUnit.GramPerMole); /// <summary> /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MolarMassUnit.HectogramPerMole"/> /// </summary> public double HectogramsPerMole => As(MolarMassUnit.HectogramPerMole); /// <summary> /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MolarMassUnit.KilogramPerMole"/> /// </summary> public double KilogramsPerMole => As(MolarMassUnit.KilogramPerMole); /// <summary> /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MolarMassUnit.KilopoundPerMole"/> /// </summary> public double KilopoundsPerMole => As(MolarMassUnit.KilopoundPerMole); /// <summary> /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MolarMassUnit.MegapoundPerMole"/> /// </summary> public double MegapoundsPerMole => As(MolarMassUnit.MegapoundPerMole); /// <summary> /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MolarMassUnit.MicrogramPerMole"/> /// </summary> public double MicrogramsPerMole => As(MolarMassUnit.MicrogramPerMole); /// <summary> /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MolarMassUnit.MilligramPerMole"/> /// </summary> public double MilligramsPerMole => As(MolarMassUnit.MilligramPerMole); /// <summary> /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MolarMassUnit.NanogramPerMole"/> /// </summary> public double NanogramsPerMole => As(MolarMassUnit.NanogramPerMole); /// <summary> /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MolarMassUnit.PoundPerMole"/> /// </summary> public double PoundsPerMole => As(MolarMassUnit.PoundPerMole); #endregion #region Static Factory Methods /// <summary> /// Creates a <see cref="MolarMass"/> from <see cref="MolarMassUnit.CentigramPerMole"/>. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> public static MolarMass FromCentigramsPerMole(double centigramspermole) => new MolarMass(centigramspermole, MolarMassUnit.CentigramPerMole); /// <summary> /// Creates a <see cref="MolarMass"/> from <see cref="MolarMassUnit.DecagramPerMole"/>. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> public static MolarMass FromDecagramsPerMole(double decagramspermole) => new MolarMass(decagramspermole, MolarMassUnit.DecagramPerMole); /// <summary> /// Creates a <see cref="MolarMass"/> from <see cref="MolarMassUnit.DecigramPerMole"/>. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> public static MolarMass FromDecigramsPerMole(double decigramspermole) => new MolarMass(decigramspermole, MolarMassUnit.DecigramPerMole); /// <summary> /// Creates a <see cref="MolarMass"/> from <see cref="MolarMassUnit.GramPerMole"/>. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> public static MolarMass FromGramsPerMole(double gramspermole) => new MolarMass(gramspermole, MolarMassUnit.GramPerMole); /// <summary> /// Creates a <see cref="MolarMass"/> from <see cref="MolarMassUnit.HectogramPerMole"/>. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> public static MolarMass FromHectogramsPerMole(double hectogramspermole) => new MolarMass(hectogramspermole, MolarMassUnit.HectogramPerMole); /// <summary> /// Creates a <see cref="MolarMass"/> from <see cref="MolarMassUnit.KilogramPerMole"/>. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> public static MolarMass FromKilogramsPerMole(double kilogramspermole) => new MolarMass(kilogramspermole, MolarMassUnit.KilogramPerMole); /// <summary> /// Creates a <see cref="MolarMass"/> from <see cref="MolarMassUnit.KilopoundPerMole"/>. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> public static MolarMass FromKilopoundsPerMole(double kilopoundspermole) => new MolarMass(kilopoundspermole, MolarMassUnit.KilopoundPerMole); /// <summary> /// Creates a <see cref="MolarMass"/> from <see cref="MolarMassUnit.MegapoundPerMole"/>. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> public static MolarMass FromMegapoundsPerMole(double megapoundspermole) => new MolarMass(megapoundspermole, MolarMassUnit.MegapoundPerMole); /// <summary> /// Creates a <see cref="MolarMass"/> from <see cref="MolarMassUnit.MicrogramPerMole"/>. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> public static MolarMass FromMicrogramsPerMole(double microgramspermole) => new MolarMass(microgramspermole, MolarMassUnit.MicrogramPerMole); /// <summary> /// Creates a <see cref="MolarMass"/> from <see cref="MolarMassUnit.MilligramPerMole"/>. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> public static MolarMass FromMilligramsPerMole(double milligramspermole) => new MolarMass(milligramspermole, MolarMassUnit.MilligramPerMole); /// <summary> /// Creates a <see cref="MolarMass"/> from <see cref="MolarMassUnit.NanogramPerMole"/>. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> public static MolarMass FromNanogramsPerMole(double nanogramspermole) => new MolarMass(nanogramspermole, MolarMassUnit.NanogramPerMole); /// <summary> /// Creates a <see cref="MolarMass"/> from <see cref="MolarMassUnit.PoundPerMole"/>. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> public static MolarMass FromPoundsPerMole(double poundspermole) => new MolarMass(poundspermole, MolarMassUnit.PoundPerMole); /// <summary> /// Dynamically convert from value and unit enum <see cref="MolarMassUnit" /> to <see cref="MolarMass" />. /// </summary> /// <param name="value">Value to convert from.</param> /// <param name="fromUnit">Unit to convert from.</param> /// <returns>MolarMass unit value.</returns> public static MolarMass From(double value, MolarMassUnit fromUnit) { return new MolarMass(value, fromUnit); } #endregion #region Conversion Methods /// <summary> /// Convert to the unit representation <paramref name="unit" />. /// </summary> /// <returns>Value converted to the specified unit.</returns> public double As(MolarMassUnit unit) => GetValueAs(unit); /// <summary> /// Converts this Duration to another Duration with the unit representation <paramref name="unit" />. /// </summary> /// <returns>A Duration with the specified unit.</returns> public MolarMass ToUnit(MolarMassUnit unit) { var convertedValue = GetValueAs(unit); return new MolarMass(convertedValue, unit); } /// <summary> /// Converts the current value + unit to the base unit. /// This is typically the first step in converting from one unit to another. /// </summary> /// <returns>The value in the base unit representation.</returns> private double GetValueInBaseUnit() { return Unit switch { MolarMassUnit.CentigramPerMole => (_value / 1e3) * 1e-2d, MolarMassUnit.DecagramPerMole => (_value / 1e3) * 1e1d, MolarMassUnit.DecigramPerMole => (_value / 1e3) * 1e-1d, MolarMassUnit.GramPerMole => _value / 1e3, MolarMassUnit.HectogramPerMole => (_value / 1e3) * 1e2d, MolarMassUnit.KilogramPerMole => (_value / 1e3) * 1e3d, MolarMassUnit.KilopoundPerMole => (_value * 0.45359237) * 1e3d, MolarMassUnit.MegapoundPerMole => (_value * 0.45359237) * 1e6d, MolarMassUnit.MicrogramPerMole => (_value / 1e3) * 1e-6d, MolarMassUnit.MilligramPerMole => (_value / 1e3) * 1e-3d, MolarMassUnit.NanogramPerMole => (_value / 1e3) * 1e-9d, MolarMassUnit.PoundPerMole => _value * 0.45359237, _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") }; } private double GetValueAs(MolarMassUnit unit) { if (Unit == unit) return _value; var baseUnitValue = GetValueInBaseUnit(); return unit switch { MolarMassUnit.CentigramPerMole => (baseUnitValue * 1e3) / 1e-2d, MolarMassUnit.DecagramPerMole => (baseUnitValue * 1e3) / 1e1d, MolarMassUnit.DecigramPerMole => (baseUnitValue * 1e3) / 1e-1d, MolarMassUnit.GramPerMole => baseUnitValue * 1e3, MolarMassUnit.HectogramPerMole => (baseUnitValue * 1e3) / 1e2d, MolarMassUnit.KilogramPerMole => (baseUnitValue * 1e3) / 1e3d, MolarMassUnit.KilopoundPerMole => (baseUnitValue / 0.45359237) / 1e3d, MolarMassUnit.MegapoundPerMole => (baseUnitValue / 0.45359237) / 1e6d, MolarMassUnit.MicrogramPerMole => (baseUnitValue * 1e3) / 1e-6d, MolarMassUnit.MilligramPerMole => (baseUnitValue * 1e3) / 1e-3d, MolarMassUnit.NanogramPerMole => (baseUnitValue * 1e3) / 1e-9d, MolarMassUnit.PoundPerMole => baseUnitValue / 0.45359237, _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") }; } #endregion } }
48.768977
182
0.62286
[ "MIT-feh" ]
AIKICo/UnitsNet
UnitsNet.NanoFramework/GeneratedCode/Quantities/MolarMass.g.cs
14,777
C#
using System; namespace Demo.Refit.Mvc.Models { public class ErrorViewModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); } }
17.75
70
0.661972
[ "MIT" ]
gciandro13/refit-exp
Demo.Refit.Mvc/Demo.Refit.Mvc/ViewModels/ErrorViewModel.cs
213
C#
using System; namespace UnityEngine.Build.Pipeline { /// <summary> /// Struct containing detailed information about a built asset bundle /// </summary> [Serializable] public struct BundleDetails : IEquatable<BundleDetails> { [SerializeField] string m_FileName; [SerializeField] uint m_Crc; [SerializeField] string m_Hash; [SerializeField] string[] m_Dependencies; /// <summary> /// Specific file name on disk of the asset bundle. /// </summary> public string FileName { get { return m_FileName; } set { m_FileName = value; } } /// <summary> /// Cyclic redundancy check of the content contained inside of the asset bundle. /// This value will not change between identical asset bundles with different compression options. /// </summary> public uint Crc { get { return m_Crc; } set { m_Crc = value; } } /// <summary> /// The hash version of the content contained inside of the asset bundle. /// This value will not change between identical asset bundles with different compression options. /// </summary> public Hash128 Hash { get { return Hash128.Parse(m_Hash); } set { m_Hash = value.ToString(); } } /// <summary> /// The array of all dependent asset bundles for this asset bundle. /// </summary> public string[] Dependencies { get { return m_Dependencies; } set { m_Dependencies = value; } } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is BundleDetails && Equals((BundleDetails)obj); } public override int GetHashCode() { unchecked { var hashCode = (FileName != null ? FileName.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (int)Crc; hashCode = (hashCode * 397) ^ Hash.GetHashCode(); hashCode = (hashCode * 397) ^ (Dependencies != null ? Dependencies.GetHashCode() : 0); return hashCode; } } public static bool operator ==(BundleDetails a, BundleDetails b) { return a.Equals(b); } public static bool operator !=(BundleDetails a, BundleDetails b) { return !(a == b); } public bool Equals(BundleDetails other) { return string.Equals(FileName, other.FileName) && Crc == other.Crc && Hash.Equals(other.Hash) && Equals(Dependencies, other.Dependencies); } } }
29.852632
150
0.542666
[ "MIT" ]
TalipSalihoglu/Endless-Run-Game
Covid-Run/Library/PackageCache/com.unity.scriptablebuildpipeline@1.7.3/Runtime/Shared/BundleDetails.cs
2,838
C#
// Copyright © 2017 Dmitry Sikorsky. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using ExtCore.Data.EntityFramework; using ExtCore.WebApplication.Extensions; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System.Reflection; namespace WebApplication { public class Startup { private readonly IConfiguration _configuration; private readonly string _extensionsPath; public Startup(IHostingEnvironment hostingEnvironment, IConfiguration configuration, ILoggerFactory loggerFactory) { this._configuration = configuration; this._extensionsPath = hostingEnvironment.ContentRootPath + this._configuration["Extensions:Path"]; loggerFactory.AddConsole(); loggerFactory.AddDebug(); } public void ConfigureServices(IServiceCollection services) { services.AddExtCore(this._extensionsPath); services.Configure<StorageContextOptions>(options => { options.ConnectionString = this._configuration.GetConnectionString("Default"); options.MigrationsAssembly = typeof(DesignTimeStorageContextFactory).GetTypeInfo().Assembly.FullName; } ); DesignTimeStorageContextFactory.Initialize(services.BuildServiceProvider()); } public void Configure(IApplicationBuilder applicationBuilder, IHostingEnvironment hostingEnvironment) { if (hostingEnvironment.IsDevelopment()) { applicationBuilder.UseDeveloperExceptionPage(); applicationBuilder.UseDatabaseErrorPage(); } applicationBuilder.UseExtCore(); } } }
37.301887
122
0.693475
[ "Apache-2.0" ]
sihombingevita/bootcamp-moonlay-eshop
src/Backend.WebApp/Startup.cs
1,980
C#
using System; using System.Collections.Generic; using System.Net.Http; namespace Modio { internal class Request { public Request(HttpMethod method, Uri endpoint, HttpContent? body = null) { Method = method; Endpoint = endpoint; Body = body; Headers = new Dictionary<string, string>(); Parameters = new Dictionary<string, string>(); } public IDictionary<string, string> Headers { get; private set; } public HttpMethod Method { get; set; } public Uri Endpoint { get; set; } public IDictionary<string, string> Parameters { get; private set; } public HttpContent? Body { get; set; } } }
28.84
81
0.600555
[ "Apache-2.0", "MIT" ]
nickelc/modio.net
Modio/Http/Request.cs
721
C#
using CommandLine; using NLog; using NLog.Config; using NLog.Targets; using System; using System.Collections.Generic; using System.Diagnostics; namespace Typewriter { public class Program { internal static Logger Logger => LogManager.GetLogger("Typewriter"); public static void Main(string[] args) { Parser.Default.ParseArguments<Options>(args) .WithParsed(opts => GenerateSDK(opts, args)) .WithNotParsed((errs) => HandleError(errs)); } private static void GenerateSDK(Options options, string[] args) { var stopwatch = new Stopwatch(); stopwatch.Start(); SetupLogging(options.Verbosity); Logger.Info($"Typewriter is running with the following arguments: {Environment.NewLine} {string.Join(' ', args)}"); string csdlContents = MetadataResolver.GetMetadata(options.Metadata); switch (options.GenerationMode) { case GenerationMode.Files: Generator.GenerateFiles(csdlContents, options); break; case GenerationMode.Metadata: Generator.WriteCleanAnnotatedMetadata(csdlContents, options); break; case GenerationMode.Transform: Generator.Transform(csdlContents, options); break; case GenerationMode.TransformWithDocs: Generator.TransformWithDocs(csdlContents, options); break; case GenerationMode.Full: default: Generator.GenerateFilesFromCleanMetadata(csdlContents, options); break; } stopwatch.Stop(); Logger.Info($"Generation time: {stopwatch.Elapsed } seconds."); } private static void SetupLogging(VerbosityLevel verbosity) { var config = new LoggingConfiguration(); config.AddTarget(new ConsoleTarget() { DetectConsoleAvailable =true, Layout = @"${date:format=HH\:mm\:ss} ${logger} ${message}", Name = "Console" }); switch (verbosity) { case VerbosityLevel.Minimal: config.AddRule(LogLevel.Warn, LogLevel.Fatal, "Console" ); break; case VerbosityLevel.Info: config.AddRule(LogLevel.Info, LogLevel.Fatal, "Console"); break; case VerbosityLevel.Debug: config.AddRule(LogLevel.Debug, LogLevel.Fatal, "Console"); break; case VerbosityLevel.Trace: config.AddRule(LogLevel.Trace, LogLevel.Fatal, "Console"); break; default: config.AddRule(LogLevel.Warn, LogLevel.Fatal, "Console"); break; } LogManager.Configuration = config; // Activate configuration } private static void HandleError(IEnumerable<Error> errors) { foreach (Error item in errors) { Console.Write(item.ToString()); } } } }
34.505155
128
0.536899
[ "MIT" ]
Dakoni4400/MSGraph-SDK-Code-Generator
src/Typewriter/Program.cs
3,349
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Runtime.InteropServices; namespace WebAssembly.Instructions { /// <summary> /// Tests the <see cref="Int64Load32Signed"/> instruction. /// </summary> [TestClass] public class Int64Load32SignedTests { /// <summary> /// Tests compilation and execution of the <see cref="Int64Load32Signed"/> instruction. /// </summary> [TestMethod] public void Int64Load32Signed_Compiled_Offset0() { var compiled = MemoryReadTestBase<long>.CreateInstance( new GetLocal(), new Int64Load32Signed(), new End() ); using (compiled) { Assert.IsNotNull(compiled); Assert.IsNotNull(compiled.Exports); var memory = compiled.Exports.Memory; Assert.AreNotEqual(IntPtr.Zero, memory.Start); var exports = compiled.Exports; Assert.AreEqual(0, exports.Test(0)); var testData = Samples.Memory; Marshal.Copy(testData, 0, memory.Start, testData.Length); Assert.AreEqual(67306238, exports.Test(0)); Assert.AreEqual(84148994, exports.Test(1)); Assert.AreEqual(100992003, exports.Test(2)); Assert.AreEqual(117835012, exports.Test(3)); Assert.AreEqual(134678021, exports.Test(4)); Assert.AreEqual(1023936262, exports.Test(5)); Assert.AreEqual(-667088889, exports.Test(6)); Assert.AreEqual(702037256, exports.Test(7)); Assert.AreEqual(-601237443, exports.Test(8)); Assert.AreEqual(0, exports.Test((int)Memory.PageSize - 4)); MemoryAccessOutOfRangeException x; x = Assert.ThrowsException<MemoryAccessOutOfRangeException>(() => exports.Test((int)Memory.PageSize - 3)); Assert.AreEqual(Memory.PageSize - 3, x.Offset); Assert.AreEqual(4u, x.Length); x = Assert.ThrowsException<MemoryAccessOutOfRangeException>(() => exports.Test((int)Memory.PageSize - 2)); Assert.AreEqual(Memory.PageSize - 2, x.Offset); Assert.AreEqual(4u, x.Length); x = Assert.ThrowsException<MemoryAccessOutOfRangeException>(() => exports.Test((int)Memory.PageSize - 1)); Assert.AreEqual(Memory.PageSize - 1, x.Offset); Assert.AreEqual(4u, x.Length); x = Assert.ThrowsException<MemoryAccessOutOfRangeException>(() => exports.Test((int)Memory.PageSize)); Assert.AreEqual(Memory.PageSize, x.Offset); Assert.AreEqual(4u, x.Length); Assert.ThrowsException<OverflowException>(() => exports.Test(unchecked((int)uint.MaxValue))); } } /// <summary> /// Tests compilation and execution of the <see cref="Int64Load32Signed"/> instruction. /// </summary> [TestMethod] public void Int64Load32Signed_Compiled_Offset1() { var compiled = MemoryReadTestBase<long>.CreateInstance( new GetLocal(), new Int64Load32Signed { Offset = 1, }, new End() ); using (compiled) { Assert.IsNotNull(compiled); Assert.IsNotNull(compiled.Exports); var memory = compiled.Exports.Memory; Assert.AreNotEqual(IntPtr.Zero, memory.Start); var exports = compiled.Exports; Assert.AreEqual(0, exports.Test(0)); var testData = Samples.Memory; Marshal.Copy(testData, 0, memory.Start, testData.Length); Assert.AreEqual(84148994, exports.Test(0)); Assert.AreEqual(100992003, exports.Test(1)); Assert.AreEqual(117835012, exports.Test(2)); Assert.AreEqual(134678021, exports.Test(3)); Assert.AreEqual(1023936262, exports.Test(4)); Assert.AreEqual(-667088889, exports.Test(5)); Assert.AreEqual(702037256, exports.Test(6)); Assert.AreEqual(-601237443, exports.Test(7)); Assert.AreEqual(14428632, exports.Test(8)); Assert.AreEqual(0, exports.Test((int)Memory.PageSize - 5)); MemoryAccessOutOfRangeException x; x = Assert.ThrowsException<MemoryAccessOutOfRangeException>(() => exports.Test((int)Memory.PageSize - 4)); Assert.AreEqual(Memory.PageSize - 3, x.Offset); Assert.AreEqual(4u, x.Length); x = Assert.ThrowsException<MemoryAccessOutOfRangeException>(() => exports.Test((int)Memory.PageSize - 3)); Assert.AreEqual(Memory.PageSize - 2, x.Offset); Assert.AreEqual(4u, x.Length); x = Assert.ThrowsException<MemoryAccessOutOfRangeException>(() => exports.Test((int)Memory.PageSize - 2)); Assert.AreEqual(Memory.PageSize - 1, x.Offset); Assert.AreEqual(4u, x.Length); x = Assert.ThrowsException<MemoryAccessOutOfRangeException>(() => exports.Test((int)Memory.PageSize - 1)); Assert.AreEqual(Memory.PageSize, x.Offset); Assert.AreEqual(4u, x.Length); Assert.ThrowsException<OverflowException>(() => exports.Test(unchecked((int)uint.MaxValue))); } } } }
42.871212
122
0.570596
[ "Apache-2.0" ]
dfinity-lab/dotnet-webassembly
WebAssembly.Tests/Instructions/Int64Load32SignedTests.cs
5,661
C#
using System; namespace _14_Miscellaneous { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); } } }
14.230769
46
0.535135
[ "MIT" ]
vsundupey/The-HackerRank-Interview-Preparation-Kit
14-Miscellaneous/Program.cs
187
C#
using AutoMapper; namespace Project.API.Base.MapperAdapters { public class AutoMapperAdapter : IMapperAdapter { private readonly IMapper _mapper; public AutoMapperAdapter(IMapper mapper) { _mapper = mapper; } public TTarget Adapt<TSource, TTarget>(TSource source) { return _mapper.Map<TTarget>(source); } } }
21.263158
62
0.608911
[ "Apache-2.0" ]
TaigoSantos/Visual-Studio-Achitecture
dotnet-architecture-standard/Project.API.Base/MapperAdapters/AutoMapperAdapter.cs
406
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 © 2020")] [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("1a76c543-6ec4-4da1-a505-ebb79fe8a51c")] // 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
[ "Apache-2.0" ]
erwin-io/POSWeb
ConsoleApp1/Properties/AssemblyInfo.cs
1,393
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CountingArray; namespace Quicksort { /// <summary> /// Defines a static class that provides an implementation of quick sort. /// </summary> public static class QuickSortImplementation { /// <summary> /// Sorts the given list using the quicksort algorithm. /// /// This version uses recursion to sort the items by dividing and conquering. /// </summary> /// <typeparam name="T">The type of items that should be sorted.</typeparam> /// <param name="items">The items that should be sorted.</param> /// <returns>Returns a new array that represents the sorted items.</returns> public static T[] Sort<T>(T[] items) where T : IComparable<T> { if (items == null) throw new ArgumentNullException("items"); T[] result = new T[items.Length]; items.CopyTo(result, 0); return SortInternal(result, 0, result.Length - 1, new Random((int)DateTime.Now.Ticks)); } /// <summary> /// Sorts the items recursively within the given lower bound and upper bound (inclusive) /// </summary> /// <typeparam name="T">The type of objects that are being sorted.</typeparam> /// <param name="items">The list of items that should be sorted.</param> /// <param name="lowerBound">The lower bound that determines the smallest limit for items being swapped in the array.</param> /// <param name="upperBound">The upper bound that determines the largest limit for items being swapped in the array.</param> /// <param name="rng">The random number generator that should be used for selecting pivot values.</param> /// <returns></returns> private static T[] SortInternal<T>(T[] items, int lowerBound, int upperBound, Random rng) where T : IComparable<T> { if (lowerBound >= upperBound) return items; // Select our piviot point int pivot = rng.Next(lowerBound, upperBound); T p = items[pivot]; // Swap(T, T) was inlined to increase performance T f = items[pivot]; items[pivot] = items[upperBound]; items[upperBound] = f; int storeIndex = lowerBound; // Move all items that are smaller to the left of the pivot and all that are larger to the right for (int i = lowerBound; i < upperBound; i++) { // This is a big bottleneck for value types because // they need to be boxed to call CompareTo(T) if (items[i].CompareTo(p) < 0) { T f1 = items[i]; items[i] = items[storeIndex]; items[storeIndex] = f1; storeIndex++; } } T f2 = items[storeIndex]; items[storeIndex] = items[upperBound]; items[upperBound] = f2; SortInternal(items, lowerBound, storeIndex - 1, rng); SortInternal(items, storeIndex + 1, upperBound, rng); return items; } /// <summary> /// Sorts the given list using the quicksort algorithm. /// /// This version uses recursion to sort the items by dividing and conquering. /// Because sorting results only use integers, this version of quicksort is actually faster /// than the previous. The reason is that it can compare integers using the provided operator and not by calling CompareTo(). /// That prevents the boxing from occurring for the call and therefore speeds up the algorithm even though it is manipulating more /// values. (The swap and compare values) /// </summary> /// <typeparam name="T">The type of items that should be sorted.</typeparam> /// <param name="items">The items that should be sorted.</param> /// <returns>Returns a new array that represents the sorted items.</returns> public static SortingResult SortWithSortingResult(int[] numbers) { if (numbers == null) throw new ArgumentNullException("items"); int[] result = new int[numbers.Length]; numbers.CopyTo(result, 0); int swaps = 0; int compares = 0; SortInternalWithSortingResult(result, 0, result.Length - 1, new Random((int)DateTime.Now.Ticks), ref swaps, ref compares); return new SortingResult() { AlgorithmName = "Quicksort", Compares = compares, Swaps = swaps, SortedItems = result }; } /// <summary> /// Sorts the items recursively within the given lower bound and upper bound (inclusive) /// </summary> /// <typeparam name="T">The type of objects that are being sorted.</typeparam> /// <param name="items">The list of items that should be sorted.</param> /// <param name="lowerBound">The lower bound that determines the smallest limit for items being swapped in the array.</param> /// <param name="upperBound">The upper bound that determines the largest limit for items being swapped in the array.</param> /// <param name="rng">The random number generator that should be used for selecting pivot values.</param> /// <returns></returns> private static void SortInternalWithSortingResult(int[] items, int lowerBound, int upperBound, Random rng, ref int currentSwapCount, ref int currentCompareCount) { if (lowerBound >= upperBound) return; // Select our piviot point int pivot = rng.Next(lowerBound, upperBound); int p = items[pivot]; // Inline Swap to prevent extra method call (Swap() likely wont be inlined by the C# or IL compiler) int f = items[pivot]; items[pivot] = items[upperBound]; items[upperBound] = f; currentSwapCount++; int storeIndex = lowerBound; // Move all items that are smaller to the left of the pivot and all that are larger to the right for (int i = lowerBound; i < upperBound; i++) { if (items[i] < p) { int f1 = items[i]; items[i] = items[storeIndex]; items[storeIndex] = f1; currentSwapCount++; storeIndex++; } currentCompareCount++; } int f2 = items[storeIndex]; items[storeIndex] = items[upperBound]; items[upperBound] = f2; currentSwapCount++; SortInternalWithSortingResult(items, lowerBound, storeIndex - 1, rng, ref currentSwapCount, ref currentCompareCount); SortInternalWithSortingResult(items, storeIndex + 1, upperBound, rng, ref currentSwapCount, ref currentCompareCount); } } }
42.630058
169
0.570305
[ "Apache-2.0" ]
KallynGowdy/SortingAlgorithms
Quicksort/QuickSortImplementation.cs
7,377
C#
using My2K48.Events; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace My2K48.Missions { class CellsCombinedMission : Mission { public CellsCombinedMission(EventPublisher eventPublisher) : base(eventPublisher) { this.id = Guid.NewGuid(); this.complete = false; this.title = "Cells Combined"; this.actual = 0; this.goal = 10; this.score = new Point(1000); } public override void handle(Event e) { if (this.complete) { return; } this.updateActual(++this.actual); Task.Factory.StartNew(() => { }); } public override bool isSubscribed(Event e) { return e.GetType().Name == "CellCombined"; } } }
18.146341
83
0.669355
[ "MIT" ]
cpuga05/My2k48
My2K48/Missions/CellsCombinedMission.cs
746
C#
// ----------------------------------------------------------------------------- // GENERATED CODE - DO NOT EDIT // ----------------------------------------------------------------------------- using System; using System.Linq; using System.Collections.Generic; using Hl7.Fhir.Model; using Hl7.Fhir.Utility; using System.Xml.Serialization; using System.Xml; using System.Xml.Linq; using System.Threading; namespace Hl7.Fhir.CustomSerializer { public partial class FhirCustomXmlReader { private void Parse(EffectEvidenceSynthesis result, XmlReader reader, OperationOutcome outcome, string locationPath, CancellationToken cancellationToken) { // skip ignored elements while (ShouldSkipNodeType(reader.NodeType)) if (!reader.Read()) return; if (reader.IsEmptyElement) return; // otherwise proceed to read all the other nodes while (reader.Read()) { if (cancellationToken.IsCancellationRequested) return; if (reader.IsStartElement()) { switch (reader.Name) { case "id": result.IdElement = new Hl7.Fhir.Model.Id(); Parse(result.IdElement as Hl7.Fhir.Model.Id, reader, outcome, locationPath + ".id", cancellationToken); // 10 break; case "meta": result.Meta = new Hl7.Fhir.Model.Meta(); Parse(result.Meta as Hl7.Fhir.Model.Meta, reader, outcome, locationPath + ".meta", cancellationToken); // 20 break; case "implicitRules": result.ImplicitRulesElement = new Hl7.Fhir.Model.FhirUri(); Parse(result.ImplicitRulesElement as Hl7.Fhir.Model.FhirUri, reader, outcome, locationPath + ".implicitRules", cancellationToken); // 30 break; case "language": result.LanguageElement = new Hl7.Fhir.Model.Code(); Parse(result.LanguageElement as Hl7.Fhir.Model.Code, reader, outcome, locationPath + ".language", cancellationToken); // 40 break; case "text": result.Text = new Hl7.Fhir.Model.Narrative(); Parse(result.Text as Hl7.Fhir.Model.Narrative, reader, outcome, locationPath + ".text", cancellationToken); // 50 break; case "contained": // FirstChildOf(reader); // 60 var ContainedResource = Parse(reader, outcome, locationPath + ".contained["+result.Contained.Count+"]", cancellationToken); if (ContainedResource != null) result.Contained.Add(ContainedResource); if (!reader.Read()) return; break; case "extension": var newItem_extension = new Hl7.Fhir.Model.Extension(); Parse(newItem_extension, reader, outcome, locationPath + ".extension["+result.Extension.Count+"]", cancellationToken); // 70 result.Extension.Add(newItem_extension); break; case "modifierExtension": var newItem_modifierExtension = new Hl7.Fhir.Model.Extension(); Parse(newItem_modifierExtension, reader, outcome, locationPath + ".modifierExtension["+result.ModifierExtension.Count+"]", cancellationToken); // 80 result.ModifierExtension.Add(newItem_modifierExtension); break; case "url": result.UrlElement = new Hl7.Fhir.Model.FhirUri(); Parse(result.UrlElement as Hl7.Fhir.Model.FhirUri, reader, outcome, locationPath + ".url", cancellationToken); // 90 break; case "identifier": var newItem_identifier = new Hl7.Fhir.Model.Identifier(); Parse(newItem_identifier, reader, outcome, locationPath + ".identifier["+result.Identifier.Count+"]", cancellationToken); // 100 result.Identifier.Add(newItem_identifier); break; case "version": result.VersionElement = new Hl7.Fhir.Model.FhirString(); Parse(result.VersionElement as Hl7.Fhir.Model.FhirString, reader, outcome, locationPath + ".version", cancellationToken); // 110 break; case "name": result.NameElement = new Hl7.Fhir.Model.FhirString(); Parse(result.NameElement as Hl7.Fhir.Model.FhirString, reader, outcome, locationPath + ".name", cancellationToken); // 120 break; case "title": result.TitleElement = new Hl7.Fhir.Model.FhirString(); Parse(result.TitleElement as Hl7.Fhir.Model.FhirString, reader, outcome, locationPath + ".title", cancellationToken); // 130 break; case "status": result.StatusElement = new Hl7.Fhir.Model.Code<Hl7.Fhir.Model.PublicationStatus>(); Parse(result.StatusElement as Hl7.Fhir.Model.Code<Hl7.Fhir.Model.PublicationStatus>, reader, outcome, locationPath + ".status", cancellationToken); // 140 break; case "date": result.DateElement = new Hl7.Fhir.Model.FhirDateTime(); Parse(result.DateElement as Hl7.Fhir.Model.FhirDateTime, reader, outcome, locationPath + ".date", cancellationToken); // 150 break; case "publisher": result.PublisherElement = new Hl7.Fhir.Model.FhirString(); Parse(result.PublisherElement as Hl7.Fhir.Model.FhirString, reader, outcome, locationPath + ".publisher", cancellationToken); // 160 break; case "contact": var newItem_contact = new Hl7.Fhir.Model.ContactDetail(); Parse(newItem_contact, reader, outcome, locationPath + ".contact["+result.Contact.Count+"]", cancellationToken); // 170 result.Contact.Add(newItem_contact); break; case "description": result.Description = new Hl7.Fhir.Model.Markdown(); Parse(result.Description as Hl7.Fhir.Model.Markdown, reader, outcome, locationPath + ".description", cancellationToken); // 180 break; case "note": var newItem_note = new Hl7.Fhir.Model.Annotation(); Parse(newItem_note, reader, outcome, locationPath + ".note["+result.Note.Count+"]", cancellationToken); // 190 result.Note.Add(newItem_note); break; case "useContext": var newItem_useContext = new Hl7.Fhir.Model.UsageContext(); Parse(newItem_useContext, reader, outcome, locationPath + ".useContext["+result.UseContext.Count+"]", cancellationToken); // 200 result.UseContext.Add(newItem_useContext); break; case "jurisdiction": var newItem_jurisdiction = new Hl7.Fhir.Model.CodeableConcept(); Parse(newItem_jurisdiction, reader, outcome, locationPath + ".jurisdiction["+result.Jurisdiction.Count+"]", cancellationToken); // 210 result.Jurisdiction.Add(newItem_jurisdiction); break; case "copyright": result.Copyright = new Hl7.Fhir.Model.Markdown(); Parse(result.Copyright as Hl7.Fhir.Model.Markdown, reader, outcome, locationPath + ".copyright", cancellationToken); // 220 break; case "approvalDate": result.ApprovalDateElement = new Hl7.Fhir.Model.Date(); Parse(result.ApprovalDateElement as Hl7.Fhir.Model.Date, reader, outcome, locationPath + ".approvalDate", cancellationToken); // 230 break; case "lastReviewDate": result.LastReviewDateElement = new Hl7.Fhir.Model.Date(); Parse(result.LastReviewDateElement as Hl7.Fhir.Model.Date, reader, outcome, locationPath + ".lastReviewDate", cancellationToken); // 240 break; case "effectivePeriod": result.EffectivePeriod = new Hl7.Fhir.Model.Period(); Parse(result.EffectivePeriod as Hl7.Fhir.Model.Period, reader, outcome, locationPath + ".effectivePeriod", cancellationToken); // 250 break; case "topic": var newItem_topic = new Hl7.Fhir.Model.CodeableConcept(); Parse(newItem_topic, reader, outcome, locationPath + ".topic["+result.Topic.Count+"]", cancellationToken); // 260 result.Topic.Add(newItem_topic); break; case "author": var newItem_author = new Hl7.Fhir.Model.ContactDetail(); Parse(newItem_author, reader, outcome, locationPath + ".author["+result.Author.Count+"]", cancellationToken); // 270 result.Author.Add(newItem_author); break; case "editor": var newItem_editor = new Hl7.Fhir.Model.ContactDetail(); Parse(newItem_editor, reader, outcome, locationPath + ".editor["+result.Editor.Count+"]", cancellationToken); // 280 result.Editor.Add(newItem_editor); break; case "reviewer": var newItem_reviewer = new Hl7.Fhir.Model.ContactDetail(); Parse(newItem_reviewer, reader, outcome, locationPath + ".reviewer["+result.Reviewer.Count+"]", cancellationToken); // 290 result.Reviewer.Add(newItem_reviewer); break; case "endorser": var newItem_endorser = new Hl7.Fhir.Model.ContactDetail(); Parse(newItem_endorser, reader, outcome, locationPath + ".endorser["+result.Endorser.Count+"]", cancellationToken); // 300 result.Endorser.Add(newItem_endorser); break; case "relatedArtifact": var newItem_relatedArtifact = new Hl7.Fhir.Model.RelatedArtifact(); Parse(newItem_relatedArtifact, reader, outcome, locationPath + ".relatedArtifact["+result.RelatedArtifact.Count+"]", cancellationToken); // 310 result.RelatedArtifact.Add(newItem_relatedArtifact); break; case "synthesisType": result.SynthesisType = new Hl7.Fhir.Model.CodeableConcept(); Parse(result.SynthesisType as Hl7.Fhir.Model.CodeableConcept, reader, outcome, locationPath + ".synthesisType", cancellationToken); // 320 break; case "studyType": result.StudyType = new Hl7.Fhir.Model.CodeableConcept(); Parse(result.StudyType as Hl7.Fhir.Model.CodeableConcept, reader, outcome, locationPath + ".studyType", cancellationToken); // 330 break; case "population": result.Population = new Hl7.Fhir.Model.ResourceReference(); Parse(result.Population as Hl7.Fhir.Model.ResourceReference, reader, outcome, locationPath + ".population", cancellationToken); // 340 break; case "exposure": result.Exposure = new Hl7.Fhir.Model.ResourceReference(); Parse(result.Exposure as Hl7.Fhir.Model.ResourceReference, reader, outcome, locationPath + ".exposure", cancellationToken); // 350 break; case "exposureAlternative": result.ExposureAlternative = new Hl7.Fhir.Model.ResourceReference(); Parse(result.ExposureAlternative as Hl7.Fhir.Model.ResourceReference, reader, outcome, locationPath + ".exposureAlternative", cancellationToken); // 360 break; case "outcome": result.Outcome = new Hl7.Fhir.Model.ResourceReference(); Parse(result.Outcome as Hl7.Fhir.Model.ResourceReference, reader, outcome, locationPath + ".outcome", cancellationToken); // 370 break; case "sampleSize": result.SampleSize = new Hl7.Fhir.Model.EffectEvidenceSynthesis.SampleSizeComponent(); Parse(result.SampleSize as Hl7.Fhir.Model.EffectEvidenceSynthesis.SampleSizeComponent, reader, outcome, locationPath + ".sampleSize", cancellationToken); // 380 break; case "resultsByExposure": var newItem_resultsByExposure = new Hl7.Fhir.Model.EffectEvidenceSynthesis.ResultsByExposureComponent(); Parse(newItem_resultsByExposure, reader, outcome, locationPath + ".resultsByExposure["+result.ResultsByExposure.Count+"]", cancellationToken); // 390 result.ResultsByExposure.Add(newItem_resultsByExposure); break; case "effectEstimate": var newItem_effectEstimate = new Hl7.Fhir.Model.EffectEvidenceSynthesis.EffectEstimateComponent(); Parse(newItem_effectEstimate, reader, outcome, locationPath + ".effectEstimate["+result.EffectEstimate.Count+"]", cancellationToken); // 400 result.EffectEstimate.Add(newItem_effectEstimate); break; case "certainty": var newItem_certainty = new Hl7.Fhir.Model.EffectEvidenceSynthesis.CertaintyComponent(); Parse(newItem_certainty, reader, outcome, locationPath + ".certainty["+result.Certainty.Count+"]", cancellationToken); // 410 result.Certainty.Add(newItem_certainty); break; default: // Property not found // System.Diagnostics.Trace.WriteLine($\"Unexpected token found {reader.Name}\"); HandlePropertyNotFound(reader, outcome, locationPath + "." + reader.Name); // reader.ReadInnerXml(); break; } } else if (reader.NodeType == XmlNodeType.EndElement || reader.IsStartElement() && reader.IsEmptyElement) { break; } } } private async System.Threading.Tasks.Task ParseAsync(EffectEvidenceSynthesis result, XmlReader reader, OperationOutcome outcome, string locationPath, CancellationToken cancellationToken) { // skip ignored elements while (ShouldSkipNodeType(reader.NodeType)) if (!await reader.ReadAsync().ConfigureAwait(false)) return; if (reader.IsEmptyElement) return; // otherwise proceed to read all the other nodes while (await reader.ReadAsync().ConfigureAwait(false)) { if (cancellationToken.IsCancellationRequested) return; if (reader.IsStartElement()) { switch (reader.Name) { case "id": result.IdElement = new Hl7.Fhir.Model.Id(); await ParseAsync(result.IdElement as Hl7.Fhir.Model.Id, reader, outcome, locationPath + ".id", cancellationToken); // 10 break; case "meta": result.Meta = new Hl7.Fhir.Model.Meta(); await ParseAsync(result.Meta as Hl7.Fhir.Model.Meta, reader, outcome, locationPath + ".meta", cancellationToken); // 20 break; case "implicitRules": result.ImplicitRulesElement = new Hl7.Fhir.Model.FhirUri(); await ParseAsync(result.ImplicitRulesElement as Hl7.Fhir.Model.FhirUri, reader, outcome, locationPath + ".implicitRules", cancellationToken); // 30 break; case "language": result.LanguageElement = new Hl7.Fhir.Model.Code(); await ParseAsync(result.LanguageElement as Hl7.Fhir.Model.Code, reader, outcome, locationPath + ".language", cancellationToken); // 40 break; case "text": result.Text = new Hl7.Fhir.Model.Narrative(); await ParseAsync(result.Text as Hl7.Fhir.Model.Narrative, reader, outcome, locationPath + ".text", cancellationToken); // 50 break; case "contained": // FirstChildOf(reader); // 60 var ContainedResource = await ParseAsync(reader, outcome, locationPath + ".contained["+result.Contained.Count+"]", cancellationToken); if (ContainedResource != null) result.Contained.Add(ContainedResource); if (!reader.Read()) return; break; case "extension": var newItem_extension = new Hl7.Fhir.Model.Extension(); await ParseAsync(newItem_extension, reader, outcome, locationPath + ".extension["+result.Extension.Count+"]", cancellationToken); // 70 result.Extension.Add(newItem_extension); break; case "modifierExtension": var newItem_modifierExtension = new Hl7.Fhir.Model.Extension(); await ParseAsync(newItem_modifierExtension, reader, outcome, locationPath + ".modifierExtension["+result.ModifierExtension.Count+"]", cancellationToken); // 80 result.ModifierExtension.Add(newItem_modifierExtension); break; case "url": result.UrlElement = new Hl7.Fhir.Model.FhirUri(); await ParseAsync(result.UrlElement as Hl7.Fhir.Model.FhirUri, reader, outcome, locationPath + ".url", cancellationToken); // 90 break; case "identifier": var newItem_identifier = new Hl7.Fhir.Model.Identifier(); await ParseAsync(newItem_identifier, reader, outcome, locationPath + ".identifier["+result.Identifier.Count+"]", cancellationToken); // 100 result.Identifier.Add(newItem_identifier); break; case "version": result.VersionElement = new Hl7.Fhir.Model.FhirString(); await ParseAsync(result.VersionElement as Hl7.Fhir.Model.FhirString, reader, outcome, locationPath + ".version", cancellationToken); // 110 break; case "name": result.NameElement = new Hl7.Fhir.Model.FhirString(); await ParseAsync(result.NameElement as Hl7.Fhir.Model.FhirString, reader, outcome, locationPath + ".name", cancellationToken); // 120 break; case "title": result.TitleElement = new Hl7.Fhir.Model.FhirString(); await ParseAsync(result.TitleElement as Hl7.Fhir.Model.FhirString, reader, outcome, locationPath + ".title", cancellationToken); // 130 break; case "status": result.StatusElement = new Hl7.Fhir.Model.Code<Hl7.Fhir.Model.PublicationStatus>(); await ParseAsync(result.StatusElement as Hl7.Fhir.Model.Code<Hl7.Fhir.Model.PublicationStatus>, reader, outcome, locationPath + ".status", cancellationToken); // 140 break; case "date": result.DateElement = new Hl7.Fhir.Model.FhirDateTime(); await ParseAsync(result.DateElement as Hl7.Fhir.Model.FhirDateTime, reader, outcome, locationPath + ".date", cancellationToken); // 150 break; case "publisher": result.PublisherElement = new Hl7.Fhir.Model.FhirString(); await ParseAsync(result.PublisherElement as Hl7.Fhir.Model.FhirString, reader, outcome, locationPath + ".publisher", cancellationToken); // 160 break; case "contact": var newItem_contact = new Hl7.Fhir.Model.ContactDetail(); await ParseAsync(newItem_contact, reader, outcome, locationPath + ".contact["+result.Contact.Count+"]", cancellationToken); // 170 result.Contact.Add(newItem_contact); break; case "description": result.Description = new Hl7.Fhir.Model.Markdown(); await ParseAsync(result.Description as Hl7.Fhir.Model.Markdown, reader, outcome, locationPath + ".description", cancellationToken); // 180 break; case "note": var newItem_note = new Hl7.Fhir.Model.Annotation(); await ParseAsync(newItem_note, reader, outcome, locationPath + ".note["+result.Note.Count+"]", cancellationToken); // 190 result.Note.Add(newItem_note); break; case "useContext": var newItem_useContext = new Hl7.Fhir.Model.UsageContext(); await ParseAsync(newItem_useContext, reader, outcome, locationPath + ".useContext["+result.UseContext.Count+"]", cancellationToken); // 200 result.UseContext.Add(newItem_useContext); break; case "jurisdiction": var newItem_jurisdiction = new Hl7.Fhir.Model.CodeableConcept(); await ParseAsync(newItem_jurisdiction, reader, outcome, locationPath + ".jurisdiction["+result.Jurisdiction.Count+"]", cancellationToken); // 210 result.Jurisdiction.Add(newItem_jurisdiction); break; case "copyright": result.Copyright = new Hl7.Fhir.Model.Markdown(); await ParseAsync(result.Copyright as Hl7.Fhir.Model.Markdown, reader, outcome, locationPath + ".copyright", cancellationToken); // 220 break; case "approvalDate": result.ApprovalDateElement = new Hl7.Fhir.Model.Date(); await ParseAsync(result.ApprovalDateElement as Hl7.Fhir.Model.Date, reader, outcome, locationPath + ".approvalDate", cancellationToken); // 230 break; case "lastReviewDate": result.LastReviewDateElement = new Hl7.Fhir.Model.Date(); await ParseAsync(result.LastReviewDateElement as Hl7.Fhir.Model.Date, reader, outcome, locationPath + ".lastReviewDate", cancellationToken); // 240 break; case "effectivePeriod": result.EffectivePeriod = new Hl7.Fhir.Model.Period(); await ParseAsync(result.EffectivePeriod as Hl7.Fhir.Model.Period, reader, outcome, locationPath + ".effectivePeriod", cancellationToken); // 250 break; case "topic": var newItem_topic = new Hl7.Fhir.Model.CodeableConcept(); await ParseAsync(newItem_topic, reader, outcome, locationPath + ".topic["+result.Topic.Count+"]", cancellationToken); // 260 result.Topic.Add(newItem_topic); break; case "author": var newItem_author = new Hl7.Fhir.Model.ContactDetail(); await ParseAsync(newItem_author, reader, outcome, locationPath + ".author["+result.Author.Count+"]", cancellationToken); // 270 result.Author.Add(newItem_author); break; case "editor": var newItem_editor = new Hl7.Fhir.Model.ContactDetail(); await ParseAsync(newItem_editor, reader, outcome, locationPath + ".editor["+result.Editor.Count+"]", cancellationToken); // 280 result.Editor.Add(newItem_editor); break; case "reviewer": var newItem_reviewer = new Hl7.Fhir.Model.ContactDetail(); await ParseAsync(newItem_reviewer, reader, outcome, locationPath + ".reviewer["+result.Reviewer.Count+"]", cancellationToken); // 290 result.Reviewer.Add(newItem_reviewer); break; case "endorser": var newItem_endorser = new Hl7.Fhir.Model.ContactDetail(); await ParseAsync(newItem_endorser, reader, outcome, locationPath + ".endorser["+result.Endorser.Count+"]", cancellationToken); // 300 result.Endorser.Add(newItem_endorser); break; case "relatedArtifact": var newItem_relatedArtifact = new Hl7.Fhir.Model.RelatedArtifact(); await ParseAsync(newItem_relatedArtifact, reader, outcome, locationPath + ".relatedArtifact["+result.RelatedArtifact.Count+"]", cancellationToken); // 310 result.RelatedArtifact.Add(newItem_relatedArtifact); break; case "synthesisType": result.SynthesisType = new Hl7.Fhir.Model.CodeableConcept(); await ParseAsync(result.SynthesisType as Hl7.Fhir.Model.CodeableConcept, reader, outcome, locationPath + ".synthesisType", cancellationToken); // 320 break; case "studyType": result.StudyType = new Hl7.Fhir.Model.CodeableConcept(); await ParseAsync(result.StudyType as Hl7.Fhir.Model.CodeableConcept, reader, outcome, locationPath + ".studyType", cancellationToken); // 330 break; case "population": result.Population = new Hl7.Fhir.Model.ResourceReference(); await ParseAsync(result.Population as Hl7.Fhir.Model.ResourceReference, reader, outcome, locationPath + ".population", cancellationToken); // 340 break; case "exposure": result.Exposure = new Hl7.Fhir.Model.ResourceReference(); await ParseAsync(result.Exposure as Hl7.Fhir.Model.ResourceReference, reader, outcome, locationPath + ".exposure", cancellationToken); // 350 break; case "exposureAlternative": result.ExposureAlternative = new Hl7.Fhir.Model.ResourceReference(); await ParseAsync(result.ExposureAlternative as Hl7.Fhir.Model.ResourceReference, reader, outcome, locationPath + ".exposureAlternative", cancellationToken); // 360 break; case "outcome": result.Outcome = new Hl7.Fhir.Model.ResourceReference(); await ParseAsync(result.Outcome as Hl7.Fhir.Model.ResourceReference, reader, outcome, locationPath + ".outcome", cancellationToken); // 370 break; case "sampleSize": result.SampleSize = new Hl7.Fhir.Model.EffectEvidenceSynthesis.SampleSizeComponent(); await ParseAsync(result.SampleSize as Hl7.Fhir.Model.EffectEvidenceSynthesis.SampleSizeComponent, reader, outcome, locationPath + ".sampleSize", cancellationToken); // 380 break; case "resultsByExposure": var newItem_resultsByExposure = new Hl7.Fhir.Model.EffectEvidenceSynthesis.ResultsByExposureComponent(); await ParseAsync(newItem_resultsByExposure, reader, outcome, locationPath + ".resultsByExposure["+result.ResultsByExposure.Count+"]", cancellationToken); // 390 result.ResultsByExposure.Add(newItem_resultsByExposure); break; case "effectEstimate": var newItem_effectEstimate = new Hl7.Fhir.Model.EffectEvidenceSynthesis.EffectEstimateComponent(); await ParseAsync(newItem_effectEstimate, reader, outcome, locationPath + ".effectEstimate["+result.EffectEstimate.Count+"]", cancellationToken); // 400 result.EffectEstimate.Add(newItem_effectEstimate); break; case "certainty": var newItem_certainty = new Hl7.Fhir.Model.EffectEvidenceSynthesis.CertaintyComponent(); await ParseAsync(newItem_certainty, reader, outcome, locationPath + ".certainty["+result.Certainty.Count+"]", cancellationToken); // 410 result.Certainty.Add(newItem_certainty); break; default: // Property not found await HandlePropertyNotFoundAsync(reader, outcome, locationPath + "." + reader.Name); break; } } else if (reader.NodeType == XmlNodeType.EndElement || reader.IsStartElement() && reader.IsEmptyElement) { break; } } } } }
54.343681
188
0.691338
[ "BSD-3-Clause" ]
brianpos/fhir-net-web-api
src/Hl7.Fhir.Custom.Serializers/Generated/FhirCustomXmlReader.EffectEvidenceSynthesis.cs
24,511
C#
#if USE_UNI_LUA using LuaAPI = UniLua.Lua; using RealStatePtr = UniLua.ILuaState; using LuaCSFunction = UniLua.CSharpFunctionDelegate; #else using LuaAPI = XLua.LuaDLL.Lua; using RealStatePtr = System.IntPtr; using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; #endif using XLua; using System.Collections.Generic; namespace XLua.CSObjectWrap { using Utils = XLua.Utils; public class XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapPathfindingStartEndModifierExactnessWrapWrapWrapWrapWrap { public static void __Register(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); System.Type type = typeof(XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapPathfindingStartEndModifierExactnessWrapWrapWrapWrap); Utils.BeginObjectRegister(type, L, translator, 0, 0, 0, 0); Utils.EndObjectRegister(type, L, translator, null, null, null, null, null); Utils.BeginClassRegister(type, L, __CreateInstance, 2, 0, 0); Utils.RegisterFunc(L, Utils.CLS_IDX, "__Register", _m___Register_xlua_st_); Utils.EndClassRegister(type, L, translator); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int __CreateInstance(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); if(LuaAPI.lua_gettop(L) == 1) { XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapPathfindingStartEndModifierExactnessWrapWrapWrapWrap gen_ret = new XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapPathfindingStartEndModifierExactnessWrapWrapWrapWrap(); translator.Push(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return LuaAPI.luaL_error(L, "invalid arguments to XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapPathfindingStartEndModifierExactnessWrapWrapWrapWrap constructor!"); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m___Register_xlua_st_(RealStatePtr L) { try { { System.IntPtr _L = LuaAPI.lua_touserdata(L, 1); XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapPathfindingStartEndModifierExactnessWrapWrapWrapWrap.__Register( _L ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } } }
27.772727
259
0.623241
[ "MIT" ]
zxsean/DCET
Unity/Assets/Model/XLua/Gen/XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapPathfindingStartEndModifierExactnessWrapWrapWrapWrapWrap.cs
3,057
C#
using System; namespace TournamentAssistantShared.Models.Packets { [Serializable] public class Command { public enum CommandTypes { Heartbeat, ReturnToMenu, ScreenOverlay_ShowPng, ScreenOverlay_ShowGreen, DelayTest_Finish } public CommandTypes CommandType { get; set; } } }
19.25
53
0.587013
[ "MIT" ]
Arimodu/TournamentAssistant
TournamentAssistantShared/Models/Packets/Command.cs
387
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Collections.Generic; using System.Text.Json; using Azure.Core; using Azure.ResourceManager.Compute.Models; using Azure.ResourceManager.Models; using Azure.ResourceManager.Resources.Models; namespace Azure.ResourceManager.Compute { public partial class VirtualMachineData : IUtf8JsonSerializable { void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) { writer.WriteStartObject(); if (Optional.IsDefined(Plan)) { writer.WritePropertyName("plan"); writer.WriteObjectValue(Plan); } if (Optional.IsDefined(Identity)) { writer.WritePropertyName("identity"); JsonSerializer.Serialize(writer, Identity); } if (Optional.IsCollectionDefined(Zones)) { writer.WritePropertyName("zones"); writer.WriteStartArray(); foreach (var item in Zones) { writer.WriteStringValue(item); } writer.WriteEndArray(); } if (Optional.IsDefined(ExtendedLocation)) { writer.WritePropertyName("extendedLocation"); writer.WriteObjectValue(ExtendedLocation); } writer.WritePropertyName("tags"); writer.WriteStartObject(); foreach (var item in Tags) { writer.WritePropertyName(item.Key); writer.WriteStringValue(item.Value); } writer.WriteEndObject(); writer.WritePropertyName("location"); writer.WriteStringValue(Location); writer.WritePropertyName("properties"); writer.WriteStartObject(); if (Optional.IsDefined(HardwareProfile)) { writer.WritePropertyName("hardwareProfile"); writer.WriteObjectValue(HardwareProfile); } if (Optional.IsDefined(StorageProfile)) { writer.WritePropertyName("storageProfile"); writer.WriteObjectValue(StorageProfile); } if (Optional.IsDefined(AdditionalCapabilities)) { writer.WritePropertyName("additionalCapabilities"); writer.WriteObjectValue(AdditionalCapabilities); } if (Optional.IsDefined(OSProfile)) { writer.WritePropertyName("osProfile"); writer.WriteObjectValue(OSProfile); } if (Optional.IsDefined(NetworkProfile)) { writer.WritePropertyName("networkProfile"); writer.WriteObjectValue(NetworkProfile); } if (Optional.IsDefined(SecurityProfile)) { writer.WritePropertyName("securityProfile"); writer.WriteObjectValue(SecurityProfile); } if (Optional.IsDefined(DiagnosticsProfile)) { writer.WritePropertyName("diagnosticsProfile"); writer.WriteObjectValue(DiagnosticsProfile); } if (Optional.IsDefined(AvailabilitySet)) { writer.WritePropertyName("availabilitySet"); JsonSerializer.Serialize(writer, AvailabilitySet); } if (Optional.IsDefined(VirtualMachineScaleSet)) { writer.WritePropertyName("virtualMachineScaleSet"); JsonSerializer.Serialize(writer, VirtualMachineScaleSet); } if (Optional.IsDefined(ProximityPlacementGroup)) { writer.WritePropertyName("proximityPlacementGroup"); JsonSerializer.Serialize(writer, ProximityPlacementGroup); } if (Optional.IsDefined(Priority)) { writer.WritePropertyName("priority"); writer.WriteStringValue(Priority.Value.ToString()); } if (Optional.IsDefined(EvictionPolicy)) { writer.WritePropertyName("evictionPolicy"); writer.WriteStringValue(EvictionPolicy.Value.ToString()); } if (Optional.IsDefined(BillingProfile)) { writer.WritePropertyName("billingProfile"); writer.WriteObjectValue(BillingProfile); } if (Optional.IsDefined(Host)) { writer.WritePropertyName("host"); JsonSerializer.Serialize(writer, Host); } if (Optional.IsDefined(HostGroup)) { writer.WritePropertyName("hostGroup"); JsonSerializer.Serialize(writer, HostGroup); } if (Optional.IsDefined(LicenseType)) { writer.WritePropertyName("licenseType"); writer.WriteStringValue(LicenseType); } if (Optional.IsDefined(ExtensionsTimeBudget)) { writer.WritePropertyName("extensionsTimeBudget"); writer.WriteStringValue(ExtensionsTimeBudget); } if (Optional.IsDefined(PlatformFaultDomain)) { writer.WritePropertyName("platformFaultDomain"); writer.WriteNumberValue(PlatformFaultDomain.Value); } if (Optional.IsDefined(ScheduledEventsProfile)) { writer.WritePropertyName("scheduledEventsProfile"); writer.WriteObjectValue(ScheduledEventsProfile); } if (Optional.IsDefined(UserData)) { writer.WritePropertyName("userData"); writer.WriteStringValue(UserData); } if (Optional.IsDefined(CapacityReservation)) { writer.WritePropertyName("capacityReservation"); writer.WriteObjectValue(CapacityReservation); } if (Optional.IsDefined(ApplicationProfile)) { writer.WritePropertyName("applicationProfile"); writer.WriteObjectValue(ApplicationProfile); } writer.WriteEndObject(); writer.WriteEndObject(); } internal static VirtualMachineData DeserializeVirtualMachineData(JsonElement element) { Optional<ComputePlan> plan = default; Optional<IReadOnlyList<VirtualMachineExtensionData>> resources = default; Optional<ManagedServiceIdentity> identity = default; Optional<IList<string>> zones = default; Optional<Models.ExtendedLocation> extendedLocation = default; IDictionary<string, string> tags = default; AzureLocation location = default; ResourceIdentifier id = default; string name = default; ResourceType type = default; SystemData systemData = default; Optional<HardwareProfile> hardwareProfile = default; Optional<StorageProfile> storageProfile = default; Optional<AdditionalCapabilities> additionalCapabilities = default; Optional<OSProfile> osProfile = default; Optional<NetworkProfile> networkProfile = default; Optional<SecurityProfile> securityProfile = default; Optional<DiagnosticsProfile> diagnosticsProfile = default; Optional<WritableSubResource> availabilitySet = default; Optional<WritableSubResource> virtualMachineScaleSet = default; Optional<WritableSubResource> proximityPlacementGroup = default; Optional<VirtualMachinePriorityTypes> priority = default; Optional<VirtualMachineEvictionPolicyTypes> evictionPolicy = default; Optional<BillingProfile> billingProfile = default; Optional<WritableSubResource> host = default; Optional<WritableSubResource> hostGroup = default; Optional<string> provisioningState = default; Optional<VirtualMachineInstanceView> instanceView = default; Optional<string> licenseType = default; Optional<string> vmId = default; Optional<string> extensionsTimeBudget = default; Optional<int> platformFaultDomain = default; Optional<ScheduledEventsProfile> scheduledEventsProfile = default; Optional<string> userData = default; Optional<CapacityReservationProfile> capacityReservation = default; Optional<ApplicationProfile> applicationProfile = default; Optional<DateTimeOffset> timeCreated = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("plan")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } plan = ComputePlan.DeserializeComputePlan(property.Value); continue; } if (property.NameEquals("resources")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } List<VirtualMachineExtensionData> array = new List<VirtualMachineExtensionData>(); foreach (var item in property.Value.EnumerateArray()) { array.Add(VirtualMachineExtensionData.DeserializeVirtualMachineExtensionData(item)); } resources = array; continue; } if (property.NameEquals("identity")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } identity = JsonSerializer.Deserialize<ManagedServiceIdentity>(property.Value.ToString()); continue; } if (property.NameEquals("zones")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } List<string> array = new List<string>(); foreach (var item in property.Value.EnumerateArray()) { array.Add(item.GetString()); } zones = array; continue; } if (property.NameEquals("extendedLocation")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } extendedLocation = Models.ExtendedLocation.DeserializeExtendedLocation(property.Value); continue; } if (property.NameEquals("tags")) { Dictionary<string, string> dictionary = new Dictionary<string, string>(); foreach (var property0 in property.Value.EnumerateObject()) { dictionary.Add(property0.Name, property0.Value.GetString()); } tags = dictionary; continue; } if (property.NameEquals("location")) { location = new AzureLocation(property.Value.GetString()); continue; } if (property.NameEquals("id")) { id = new ResourceIdentifier(property.Value.GetString()); continue; } if (property.NameEquals("name")) { name = property.Value.GetString(); continue; } if (property.NameEquals("type")) { type = new ResourceType(property.Value.GetString()); continue; } if (property.NameEquals("systemData")) { systemData = JsonSerializer.Deserialize<SystemData>(property.Value.ToString()); continue; } if (property.NameEquals("properties")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } foreach (var property0 in property.Value.EnumerateObject()) { if (property0.NameEquals("hardwareProfile")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } hardwareProfile = HardwareProfile.DeserializeHardwareProfile(property0.Value); continue; } if (property0.NameEquals("storageProfile")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } storageProfile = StorageProfile.DeserializeStorageProfile(property0.Value); continue; } if (property0.NameEquals("additionalCapabilities")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } additionalCapabilities = AdditionalCapabilities.DeserializeAdditionalCapabilities(property0.Value); continue; } if (property0.NameEquals("osProfile")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } osProfile = OSProfile.DeserializeOSProfile(property0.Value); continue; } if (property0.NameEquals("networkProfile")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } networkProfile = NetworkProfile.DeserializeNetworkProfile(property0.Value); continue; } if (property0.NameEquals("securityProfile")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } securityProfile = SecurityProfile.DeserializeSecurityProfile(property0.Value); continue; } if (property0.NameEquals("diagnosticsProfile")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } diagnosticsProfile = DiagnosticsProfile.DeserializeDiagnosticsProfile(property0.Value); continue; } if (property0.NameEquals("availabilitySet")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } availabilitySet = JsonSerializer.Deserialize<WritableSubResource>(property0.Value.ToString()); continue; } if (property0.NameEquals("virtualMachineScaleSet")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } virtualMachineScaleSet = JsonSerializer.Deserialize<WritableSubResource>(property0.Value.ToString()); continue; } if (property0.NameEquals("proximityPlacementGroup")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } proximityPlacementGroup = JsonSerializer.Deserialize<WritableSubResource>(property0.Value.ToString()); continue; } if (property0.NameEquals("priority")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } priority = new VirtualMachinePriorityTypes(property0.Value.GetString()); continue; } if (property0.NameEquals("evictionPolicy")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } evictionPolicy = new VirtualMachineEvictionPolicyTypes(property0.Value.GetString()); continue; } if (property0.NameEquals("billingProfile")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } billingProfile = BillingProfile.DeserializeBillingProfile(property0.Value); continue; } if (property0.NameEquals("host")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } host = JsonSerializer.Deserialize<WritableSubResource>(property0.Value.ToString()); continue; } if (property0.NameEquals("hostGroup")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } hostGroup = JsonSerializer.Deserialize<WritableSubResource>(property0.Value.ToString()); continue; } if (property0.NameEquals("provisioningState")) { provisioningState = property0.Value.GetString(); continue; } if (property0.NameEquals("instanceView")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } instanceView = VirtualMachineInstanceView.DeserializeVirtualMachineInstanceView(property0.Value); continue; } if (property0.NameEquals("licenseType")) { licenseType = property0.Value.GetString(); continue; } if (property0.NameEquals("vmId")) { vmId = property0.Value.GetString(); continue; } if (property0.NameEquals("extensionsTimeBudget")) { extensionsTimeBudget = property0.Value.GetString(); continue; } if (property0.NameEquals("platformFaultDomain")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } platformFaultDomain = property0.Value.GetInt32(); continue; } if (property0.NameEquals("scheduledEventsProfile")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } scheduledEventsProfile = ScheduledEventsProfile.DeserializeScheduledEventsProfile(property0.Value); continue; } if (property0.NameEquals("userData")) { userData = property0.Value.GetString(); continue; } if (property0.NameEquals("capacityReservation")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } capacityReservation = CapacityReservationProfile.DeserializeCapacityReservationProfile(property0.Value); continue; } if (property0.NameEquals("applicationProfile")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } applicationProfile = ApplicationProfile.DeserializeApplicationProfile(property0.Value); continue; } if (property0.NameEquals("timeCreated")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } timeCreated = property0.Value.GetDateTimeOffset("O"); continue; } } continue; } } return new VirtualMachineData(id, name, type, systemData, tags, location, plan.Value, Optional.ToList(resources), identity, Optional.ToList(zones), extendedLocation.Value, hardwareProfile.Value, storageProfile.Value, additionalCapabilities.Value, osProfile.Value, networkProfile.Value, securityProfile.Value, diagnosticsProfile.Value, availabilitySet, virtualMachineScaleSet, proximityPlacementGroup, Optional.ToNullable(priority), Optional.ToNullable(evictionPolicy), billingProfile.Value, host, hostGroup, provisioningState.Value, instanceView.Value, licenseType.Value, vmId.Value, extensionsTimeBudget.Value, Optional.ToNullable(platformFaultDomain), scheduledEventsProfile.Value, userData.Value, capacityReservation.Value, applicationProfile.Value, Optional.ToNullable(timeCreated)); } } }
47.382562
799
0.473995
[ "MIT" ]
v-kaifazhang/azure-sdk-for-net
sdk/compute/Azure.ResourceManager.Compute/src/Generated/Models/VirtualMachineData.Serialization.cs
26,629
C#
// https://docs.microsoft.com/en-us/visualstudio/modeling/t4-include-directive?view=vs-2017 // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.IO; using System.Runtime.CompilerServices; using Microsoft.Bot.Solutions.Dialogs; namespace AutomotiveSkill.Dialogs.VehicleSettings.Resources { /// <summary> /// Contains bot responses. /// </summary> public static class VehicleSettingsResponses { private static readonly ResponseManager _responseManager; static VehicleSettingsResponses() { var dir = Path.GetDirectoryName(typeof(VehicleSettingsResponses).Assembly.Location); var resDir = Path.Combine(dir, @"Dialogs\VehicleSettings\Resources"); _responseManager = new ResponseManager(resDir, "VehicleSettingsResponses"); } // Generated accessors public static BotResponse VehicleSettingsMissingSettingName => GetBotResponse(); public static BotResponse VehicleSettingsSettingNameSelection => GetBotResponse(); public static BotResponse VehicleSettingsMissingSettingValue => GetBotResponse(); public static BotResponse VehicleSettingsSettingValueSelection => GetBotResponse(); public static BotResponse VehicleSettingsSettingValueSelectionPre => GetBotResponse(); public static BotResponse VehicleSettingsSettingValueSelectionPost => GetBotResponse(); public static BotResponse VehicleSettingsSettingChangeConfirmation => GetBotResponse(); public static BotResponse VehicleSettingsSettingChangeConfirmationWithCategory => GetBotResponse(); public static BotResponse VehicleSettingsSettingChangeConfirmationDenied => GetBotResponse(); public static BotResponse VehicleSettingsSettingChangeNoOpValue => GetBotResponse(); public static BotResponse VehicleSettingsSettingChangeNoOpAmount => GetBotResponse(); public static BotResponse VehicleSettingsSettingChangeUnsupported => GetBotResponse(); public static BotResponse VehicleSettingsChangingRelativeAmount => GetBotResponse(); public static BotResponse VehicleSettingsChangingAmount => GetBotResponse(); public static BotResponse VehicleSettingsChangingValue => GetBotResponse(); public static BotResponse VehicleSettingsChangingValueKnown => GetBotResponse(); public static BotResponse VehicleSettingsCheckingStatus => GetBotResponse(); public static BotResponse VehicleSettingsCheckingStatusValueSuccess => GetBotResponse(); public static BotResponse VehicleSettingsCheckingStatusAmountSuccess => GetBotResponse(); public static BotResponse VehicleSettingsCheckingStatusUnsupported => GetBotResponse(); public static BotResponse VehicleSettingsOutOfDomain => GetBotResponse(); private static BotResponse GetBotResponse([CallerMemberName] string propertyName = null) { return _responseManager.GetBotResponse(propertyName); } } }
42.109589
107
0.758621
[ "MIT" ]
SVemulapalli/AI
solutions/Virtual-Assistant/src/csharp/skills/automotiveskill/Dialogs/VehicleSettings/Resources/VehicleSettingsResponses.cs
3,076
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Discord { /// <summary> /// Represents a generic guild user. /// </summary> public interface IGuildUser : IUser, IVoiceState { /// <summary> /// Gets when this user joined the guild. /// </summary> /// <returns> /// A <see cref="DateTimeOffset"/> representing the time of which the user has joined the guild; /// <c>null</c> when it cannot be obtained. /// </returns> DateTimeOffset? JoinedAt { get; } /// <summary> /// Gets the nickname for this user. /// </summary> /// <returns> /// A string representing the nickname of the user; <c>null</c> if none is set. /// </returns> string Nickname { get; } /// <summary> /// Gets the guild-level permissions for this user. /// </summary> /// <returns> /// A <see cref="Discord.GuildPermissions"/> structure for this user, representing what /// permissions this user has in the guild. /// </returns> GuildPermissions GuildPermissions { get; } /// <summary> /// Gets the guild for this user. /// </summary> /// <returns> /// A guild object that this user belongs to. /// </returns> IGuild Guild { get; } /// <summary> /// Gets the ID of the guild for this user. /// </summary> /// <returns> /// An <see cref="ulong"/> representing the snowflake identifier of the guild that this user belongs to. /// </returns> ulong GuildId { get; } /// <summary> /// Gets the date and time for when this user's guild boost began. /// </summary> /// <returns> /// A <see cref="DateTimeOffset"/> for when the user began boosting this guild; <c>null</c> if they are not boosting the guild. /// </returns> DateTimeOffset? PremiumSince { get; } /// <summary> /// Gets a collection of IDs for the roles that this user currently possesses in the guild. /// </summary> /// <remarks> /// This property returns a read-only collection of the identifiers of the roles that this user possesses. /// For WebSocket users, a Roles property can be found in place of this property. Due to the REST /// implementation, only a collection of identifiers can be retrieved instead of the full role objects. /// </remarks> /// <returns> /// A read-only collection of <see cref="ulong"/>, each representing a snowflake identifier for a role that /// this user possesses. /// </returns> IReadOnlyCollection<ulong> RoleIds { get; } /// <summary> /// Whether the user has passed the guild's Membership Screening requirements. /// </summary> bool? IsPending { get; } /// <summary> /// Gets the level permissions granted to this user to a given channel. /// </summary> /// <example> /// <para>The following example checks if the current user has the ability to send a message with attachment in /// this channel; if so, uploads a file via <see cref="IMessageChannel.SendFileAsync(string, string, bool, Embed, RequestOptions, bool, AllowedMentions, MessageReference)"/>.</para> /// <code language="cs"> /// if (currentUser?.GetPermissions(targetChannel)?.AttachFiles) /// await targetChannel.SendFileAsync("fortnite.png"); /// </code> /// </example> /// <param name="channel">The channel to get the permission from.</param> /// <returns> /// A <see cref="Discord.ChannelPermissions"/> structure representing the permissions that a user has in the /// specified channel. /// </returns> ChannelPermissions GetPermissions(IGuildChannel channel); /// <summary> /// Kicks this user from this guild. /// </summary> /// <param name="reason">The reason for the kick which will be recorded in the audit log.</param> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// A task that represents the asynchronous kick operation. /// </returns> Task KickAsync(string reason = null, RequestOptions options = null); /// <summary> /// Modifies this user's properties in this guild. /// </summary> /// <remarks> /// This method modifies the current guild user with the specified properties. To see an example of this /// method and what properties are available, please refer to <see cref="GuildUserProperties"/>. /// </remarks> /// <param name="func">The delegate containing the properties to modify the user with.</param> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// A task that represents the asynchronous modification operation. /// </returns> Task ModifyAsync(Action<GuildUserProperties> func, RequestOptions options = null); /// <summary> /// Adds the specified role to this user in the guild. /// </summary> /// <param name="roleId">The role to be added to the user.</param> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// A task that represents the asynchronous role addition operation. /// </returns> Task AddRoleAsync(ulong roleId, RequestOptions options = null); /// <summary> /// Adds the specified role to this user in the guild. /// </summary> /// <param name="role">The role to be added to the user.</param> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// A task that represents the asynchronous role addition operation. /// </returns> Task AddRoleAsync(IRole role, RequestOptions options = null); /// <summary> /// Adds the specified <paramref name="roleIds"/> to this user in the guild. /// </summary> /// <param name="roleIds">The roles to be added to the user.</param> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// A task that represents the asynchronous role addition operation. /// </returns> Task AddRolesAsync(IEnumerable<ulong> roleIds, RequestOptions options = null); /// <summary> /// Adds the specified <paramref name="roles"/> to this user in the guild. /// </summary> /// <param name="roles">The roles to be added to the user.</param> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// A task that represents the asynchronous role addition operation. /// </returns> Task AddRolesAsync(IEnumerable<IRole> roles, RequestOptions options = null); /// <summary> /// Removes the specified <paramref name="roleId"/> from this user in the guild. /// </summary> /// <param name="roleId">The role to be removed from the user.</param> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// A task that represents the asynchronous role removal operation. /// </returns> Task RemoveRoleAsync(ulong roleId, RequestOptions options = null); /// <summary> /// Removes the specified <paramref name="role"/> from this user in the guild. /// </summary> /// <param name="role">The role to be removed from the user.</param> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// A task that represents the asynchronous role removal operation. /// </returns> Task RemoveRoleAsync(IRole role, RequestOptions options = null); /// <summary> /// Removes the specified <paramref name="roleIds"/> from this user in the guild. /// </summary> /// <param name="roleIds">The roles to be removed from the user.</param> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// A task that represents the asynchronous role removal operation. /// </returns> Task RemoveRolesAsync(IEnumerable<ulong> roleIds, RequestOptions options = null); /// <summary> /// Removes the specified <paramref name="roles"/> from this user in the guild. /// </summary> /// <param name="roles">The roles to be removed from the user.</param> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// A task that represents the asynchronous role removal operation. /// </returns> Task RemoveRolesAsync(IEnumerable<IRole> roles, RequestOptions options = null); } }
49.557895
193
0.587404
[ "MIT" ]
230Daniel/Discord.Net
src/Discord.Net.Core/Entities/Users/IGuildUser.cs
9,416
C#
// ------------------------------------------------------------------------------ // <auto-generated> // Generated by avrogen.exe, version 0.9.0.0 // Changes to this file may cause incorrect behavior and will be lost if code // is regenerated // </auto-generated> // ------------------------------------------------------------------------------ namespace Energistics.Etp.v12.Protocol.Store { using System; using System.Collections.Generic; using System.Text; public class GetObject { private string _uri; public string Uri { get { return this._uri; } set { this._uri = value; } } } }
21.2
81
0.488994
[ "Apache-2.0" ]
welly87/energistics-tp
Energistics.ETP.Messages/Energistics/Etp/v12/Protocol/Store/GetObject.cs
636
C#
using System.Management.Automation; using UiPath.PowerShell.Models; using UiPath.PowerShell.Util; using UiPath.Web.Client20194; namespace UiPath.PowerShell.Cmdlets { /// <summary> /// <para type="synopsis">Shows the valid time zone names recognized by the Orchestrator.</para> /// </summary> [Cmdlet(VerbsCommon.Get, Nouns.TimeZones)] public class GetTimeZones : AuthenticatedCmdlet { protected override void ProcessRecord() { var timeZones = HandleHttpOperationException(() => Api.Settings.GetTimezones()); foreach(var tz in timeZones.Items) { WriteObject(Timezone.FromDto(tz)); } } } }
29.416667
100
0.645892
[ "MIT" ]
UiPath/orchestrator-powershell
UiPath.PowerShell/Cmdlets/GetTimeZones.cs
708
C#
//------------------------------------------------------------------------------ // <auto-generated> // このコードはツールによって生成されました。 // ランタイム バージョン:4.0.30319.34209 // // このファイルへの変更は、以下の状況下で不正な動作の原因になったり、 // コードが再生成されるときに損失したりします。 // </auto-generated> //------------------------------------------------------------------------------ namespace MsgPack.Serialization.GeneratedSerializers.MapBased { [System.CodeDom.Compiler.GeneratedCodeAttribute("MsgPack.Serialization.CodeDomSerializers.CodeDomSerializerBuilder", "0.6.0.0")] [System.Diagnostics.DebuggerNonUserCodeAttribute()] public class MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple8AllStaticGetOnlyPropertyAndConstructorSerializer : MsgPack.Serialization.MessagePackSerializer<MsgPack.Serialization.PolymorphicMemberTypeKnownType_Tuple_Tuple8AllStaticGetOnlyPropertyAndConstructor> { private MsgPack.Serialization.MessagePackSerializer<string> _serializer0; private MsgPack.Serialization.MessagePackSerializer<System.Tuple<string, string, string, string, string, string, string, System.Tuple<string>>> _serializer1; public MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple8AllStaticGetOnlyPropertyAndConstructorSerializer(MsgPack.Serialization.SerializationContext context) : base(context) { MsgPack.Serialization.PolymorphismSchema schema0 = default(MsgPack.Serialization.PolymorphismSchema); MsgPack.Serialization.PolymorphismSchema[] tupleItemsSchema0 = default(MsgPack.Serialization.PolymorphismSchema[]); tupleItemsSchema0 = new MsgPack.Serialization.PolymorphismSchema[8]; MsgPack.Serialization.PolymorphismSchema tupleItemSchema0 = default(MsgPack.Serialization.PolymorphismSchema); tupleItemSchema0 = null; tupleItemsSchema0[0] = tupleItemSchema0; MsgPack.Serialization.PolymorphismSchema tupleItemSchema1 = default(MsgPack.Serialization.PolymorphismSchema); tupleItemSchema1 = null; tupleItemsSchema0[1] = tupleItemSchema1; MsgPack.Serialization.PolymorphismSchema tupleItemSchema2 = default(MsgPack.Serialization.PolymorphismSchema); tupleItemSchema2 = null; tupleItemsSchema0[2] = tupleItemSchema2; MsgPack.Serialization.PolymorphismSchema tupleItemSchema3 = default(MsgPack.Serialization.PolymorphismSchema); tupleItemSchema3 = null; tupleItemsSchema0[3] = tupleItemSchema3; MsgPack.Serialization.PolymorphismSchema tupleItemSchema4 = default(MsgPack.Serialization.PolymorphismSchema); tupleItemSchema4 = null; tupleItemsSchema0[4] = tupleItemSchema4; MsgPack.Serialization.PolymorphismSchema tupleItemSchema5 = default(MsgPack.Serialization.PolymorphismSchema); tupleItemSchema5 = null; tupleItemsSchema0[5] = tupleItemSchema5; MsgPack.Serialization.PolymorphismSchema tupleItemSchema6 = default(MsgPack.Serialization.PolymorphismSchema); tupleItemSchema6 = null; tupleItemsSchema0[6] = tupleItemSchema6; MsgPack.Serialization.PolymorphismSchema tupleItemSchema7 = default(MsgPack.Serialization.PolymorphismSchema); tupleItemSchema7 = null; tupleItemsSchema0[7] = tupleItemSchema7; schema0 = MsgPack.Serialization.PolymorphismSchema.ForPolymorphicTuple(typeof(System.Tuple<string, string, string, string, string, string, string, System.Tuple<string>>), tupleItemsSchema0); this._serializer0 = context.GetSerializer<string>(schema0); MsgPack.Serialization.PolymorphismSchema schema1 = default(MsgPack.Serialization.PolymorphismSchema); MsgPack.Serialization.PolymorphismSchema[] tupleItemsSchema1 = default(MsgPack.Serialization.PolymorphismSchema[]); tupleItemsSchema1 = new MsgPack.Serialization.PolymorphismSchema[8]; MsgPack.Serialization.PolymorphismSchema tupleItemSchema8 = default(MsgPack.Serialization.PolymorphismSchema); tupleItemSchema8 = null; tupleItemsSchema1[0] = tupleItemSchema8; MsgPack.Serialization.PolymorphismSchema tupleItemSchema9 = default(MsgPack.Serialization.PolymorphismSchema); tupleItemSchema9 = null; tupleItemsSchema1[1] = tupleItemSchema9; MsgPack.Serialization.PolymorphismSchema tupleItemSchema10 = default(MsgPack.Serialization.PolymorphismSchema); tupleItemSchema10 = null; tupleItemsSchema1[2] = tupleItemSchema10; MsgPack.Serialization.PolymorphismSchema tupleItemSchema11 = default(MsgPack.Serialization.PolymorphismSchema); tupleItemSchema11 = null; tupleItemsSchema1[3] = tupleItemSchema11; MsgPack.Serialization.PolymorphismSchema tupleItemSchema12 = default(MsgPack.Serialization.PolymorphismSchema); tupleItemSchema12 = null; tupleItemsSchema1[4] = tupleItemSchema12; MsgPack.Serialization.PolymorphismSchema tupleItemSchema13 = default(MsgPack.Serialization.PolymorphismSchema); tupleItemSchema13 = null; tupleItemsSchema1[5] = tupleItemSchema13; MsgPack.Serialization.PolymorphismSchema tupleItemSchema14 = default(MsgPack.Serialization.PolymorphismSchema); tupleItemSchema14 = null; tupleItemsSchema1[6] = tupleItemSchema14; MsgPack.Serialization.PolymorphismSchema tupleItemSchema15 = default(MsgPack.Serialization.PolymorphismSchema); tupleItemSchema15 = null; tupleItemsSchema1[7] = tupleItemSchema15; schema1 = MsgPack.Serialization.PolymorphismSchema.ForPolymorphicTuple(typeof(System.Tuple<string, string, string, string, string, string, string, System.Tuple<string>>), tupleItemsSchema1); this._serializer1 = context.GetSerializer<System.Tuple<string, string, string, string, string, string, string, System.Tuple<string>>>(schema1); } protected internal override void PackToCore(MsgPack.Packer packer, MsgPack.Serialization.PolymorphicMemberTypeKnownType_Tuple_Tuple8AllStaticGetOnlyPropertyAndConstructor objectTree) { packer.PackMapHeader(1); this._serializer0.PackTo(packer, "Tuple8AllStatic"); this._serializer1.PackTo(packer, objectTree.Tuple8AllStatic); } protected internal override MsgPack.Serialization.PolymorphicMemberTypeKnownType_Tuple_Tuple8AllStaticGetOnlyPropertyAndConstructor UnpackFromCore(MsgPack.Unpacker unpacker) { MsgPack.Serialization.PolymorphicMemberTypeKnownType_Tuple_Tuple8AllStaticGetOnlyPropertyAndConstructor result = default(MsgPack.Serialization.PolymorphicMemberTypeKnownType_Tuple_Tuple8AllStaticGetOnlyPropertyAndConstructor); if (unpacker.IsArrayHeader) { int unpacked = default(int); int itemsCount = default(int); itemsCount = MsgPack.Serialization.UnpackHelpers.GetItemsCount(unpacker); System.Tuple<string, string, string, string, string, string, string, System.Tuple<string>> ctorArg0 = default(System.Tuple<string, string, string, string, string, string, string, System.Tuple<string>>); ctorArg0 = null; System.Tuple<string, string, string, string, string, string, string, System.Tuple<string>> nullable = default(System.Tuple<string, string, string, string, string, string, string, System.Tuple<string>>); if ((unpacked < itemsCount)) { if ((unpacker.Read() == false)) { throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(0); } if (((unpacker.IsArrayHeader == false) && (unpacker.IsMapHeader == false))) { nullable = this._serializer1.UnpackFrom(unpacker); } else { MsgPack.Unpacker disposable = default(MsgPack.Unpacker); disposable = unpacker.ReadSubtree(); try { nullable = this._serializer1.UnpackFrom(disposable); } finally { if (((disposable == null) == false)) { disposable.Dispose(); } } } } if (((nullable == null) == false)) { ctorArg0 = nullable; } unpacked = (unpacked + 1); result = new MsgPack.Serialization.PolymorphicMemberTypeKnownType_Tuple_Tuple8AllStaticGetOnlyPropertyAndConstructor(ctorArg0); } else { int itemsCount0 = default(int); itemsCount0 = MsgPack.Serialization.UnpackHelpers.GetItemsCount(unpacker); System.Tuple<string, string, string, string, string, string, string, System.Tuple<string>> ctorArg00 = default(System.Tuple<string, string, string, string, string, string, string, System.Tuple<string>>); ctorArg00 = null; for (int i = 0; (i < itemsCount0); i = (i + 1)) { string key = default(string); string nullable0 = default(string); nullable0 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, typeof(MsgPack.Serialization.PolymorphicMemberTypeKnownType_Tuple_Tuple8AllStaticGetOnlyPropertyAndConstructor), "MemberName"); if (((nullable0 == null) == false)) { key = nullable0; } else { throw MsgPack.Serialization.SerializationExceptions.NewNullIsProhibited("MemberName"); } if ((key == "Tuple8AllStatic")) { System.Tuple<string, string, string, string, string, string, string, System.Tuple<string>> nullable1 = default(System.Tuple<string, string, string, string, string, string, string, System.Tuple<string>>); if ((unpacker.Read() == false)) { throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); } if (((unpacker.IsArrayHeader == false) && (unpacker.IsMapHeader == false))) { nullable1 = this._serializer1.UnpackFrom(unpacker); } else { MsgPack.Unpacker disposable0 = default(MsgPack.Unpacker); disposable0 = unpacker.ReadSubtree(); try { nullable1 = this._serializer1.UnpackFrom(disposable0); } finally { if (((disposable0 == null) == false)) { disposable0.Dispose(); } } } if (((nullable1 == null) == false)) { ctorArg00 = nullable1; } } else { unpacker.Skip(); } } result = new MsgPack.Serialization.PolymorphicMemberTypeKnownType_Tuple_Tuple8AllStaticGetOnlyPropertyAndConstructor(ctorArg00); } return result; } private static T @__Conditional<T>(bool condition, T whenTrue, T whenFalse) { if (condition) { return whenTrue; } else { return whenFalse; } } } }
64.057592
283
0.614303
[ "Apache-2.0" ]
sosan/msgpack-cli
test/MsgPack.UnitTest/gen/map/MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple8AllStaticGetOnlyPropertyAndConstructorSerializer.cs
12,409
C#
using System; using Placeholder.Plugins.DataSync.Daemons; using Placeholder.Primary.Daemons; using Zero.Foundation; using Zero.Foundation.Daemons; namespace Placeholder.Plugins.DataSync.Integration { public static class WebHookProcessor { /// <summary> /// Not aspect wrapped /// </summary> public static string ProcessSyncWebHook(IFoundation foundation, string secretkey, string hookType, string tenant) { string result = ""; if (secretkey == "codeable") { IDaemonManager daemonManager = foundation.GetDaemonManager(); switch (hookType) { case "sync": case "failed": daemonManager.StartDaemon(string.Format(DataSynchronizeDaemon.DAEMON_NAME_TENANT_FORMAT, tenant, Agents.AGENT_DEFAULT)); daemonManager.StartDaemon(string.Format(DataSynchronizeDaemon.DAEMON_NAME_TENANT_FORMAT, tenant, Agents.AGENT_STATS)); result = "Queued Normal Sync"; break; default: break; } } return result; } /// <summary> /// Not aspect wrapped /// </summary> public static string ProcessAgitateWebHook(IFoundation foundation, string secretkey, string daemonName) { string result = ""; if (secretkey == "codeable") { IDaemonManager daemonManager = foundation.GetDaemonManager(); if (null != daemonManager.GetRegisteredDaemonTask(daemonName)) { daemonManager.StartDaemon(daemonName); result = "Agitated"; } } return result; } } }
34.236364
144
0.545406
[ "MIT" ]
wmansfield/stencil.v2
server/SourceCode/Placeholder.Plugins.DataSync/Integration/WebHookProcessor.cs
1,883
C#
using System; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.UI; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using WebappAuthN.Data; [assembly: HostingStartup(typeof(WebappAuthN.Areas.Identity.IdentityHostingStartup))] namespace WebappAuthN.Areas.Identity { public class IdentityHostingStartup : IHostingStartup { public void Configure(IWebHostBuilder builder) { builder.ConfigureServices((context, services) => { }); } } }
30
85
0.755556
[ "MIT" ]
LeonB87/RazorpageTemplate
WebappAuthN/Areas/Identity/IdentityHostingStartup.cs
632
C#
// // Copyright (c) 2009-2012 Krueger Systems, Inc. // // 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. // #if WINDOWS_PHONE && !USE_WP8_NATIVE_SQLITE #define USE_CSHARP_SQLITE #endif using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Collections.Generic; using System.Reflection; using System.Linq; using System.Linq.Expressions; using System.Threading; #if USE_CSHARP_SQLITE using Sqlite3 = Community.CsharpSqlite.Sqlite3; using Sqlite3DatabaseHandle = Community.CsharpSqlite.Sqlite3.sqlite3; using Sqlite3Statement = Community.CsharpSqlite.Sqlite3.Vdbe; #elif USE_WP8_NATIVE_SQLITE using Sqlite3 = Sqlite.Sqlite3; using Sqlite3DatabaseHandle = Sqlite.Database; using Sqlite3Statement = Sqlite.Statement; #else using Sqlite3DatabaseHandle = System.IntPtr; using Sqlite3Statement = System.IntPtr; #endif namespace SQLite { public class SQLiteException : Exception { public SQLite3.Result Result { get; private set; } protected SQLiteException(SQLite3.Result r, string message) : base(message) { Result = r; } public static SQLiteException New(SQLite3.Result r, string message) { return new SQLiteException(r, message); } } public class NotNullConstraintViolationException : SQLiteException { public IEnumerable<TableMapping.Column> Columns { get; protected set; } protected NotNullConstraintViolationException(SQLite3.Result r, string message) : this(r, message, null, null) { } protected NotNullConstraintViolationException(SQLite3.Result r, string message, TableMapping mapping, object obj) : base(r, message) { if (mapping != null && obj != null) { this.Columns = from c in mapping.Columns where c.IsNullable == false && c.GetValue(obj) == null select c; } } public static new NotNullConstraintViolationException New(SQLite3.Result r, string message) { return new NotNullConstraintViolationException(r, message); } public static NotNullConstraintViolationException New(SQLite3.Result r, string message, TableMapping mapping, object obj) { return new NotNullConstraintViolationException(r, message, mapping, obj); } public static NotNullConstraintViolationException New(SQLiteException exception, TableMapping mapping, object obj) { return new NotNullConstraintViolationException(exception.Result, exception.Message, mapping, obj); } } [Flags] public enum SQLiteOpenFlags { ReadOnly = 1, ReadWrite = 2, Create = 4, NoMutex = 0x8000, FullMutex = 0x10000, SharedCache = 0x20000, PrivateCache = 0x40000, ProtectionComplete = 0x00100000, ProtectionCompleteUnlessOpen = 0x00200000, ProtectionCompleteUntilFirstUserAuthentication = 0x00300000, ProtectionNone = 0x00400000 } [Flags] public enum CreateFlags { None = 0, ImplicitPK = 1, // create a primary key for field called 'Id' (Orm.ImplicitPkName) ImplicitIndex = 2, // create an index for fields ending in 'Id' (Orm.ImplicitIndexSuffix) AllImplicit = 3, // do both above AutoIncPK = 4 // force PK field to be auto inc } /// <summary> /// Represents an open connection to a SQLite database. /// </summary> public partial class SQLiteConnection : IDisposable { private bool _open; private TimeSpan _busyTimeout; private Dictionary<string, TableMapping> _mappings = null; private Dictionary<string, TableMapping> _tables = null; private System.Diagnostics.Stopwatch _sw; private long _elapsedMilliseconds = 0; private int _transactionDepth = 0; private Random _rand = new Random(); public Sqlite3DatabaseHandle Handle { get; private set; } internal static readonly Sqlite3DatabaseHandle NullHandle = default(Sqlite3DatabaseHandle); public string DatabasePath { get; private set; } // Dictionary of synchronization objects. // // To prevent database disruption, a database file must be accessed *synchronously*. // For the purpose we create synchronous objects for each database file and store in the // static dictionary to share it among all connections. // The key of the dictionary is database file path and its value is an object to be used // by lock() statement. // // Use case: // - database file lock is done implicitly and automatically. // - To prepend deadlock, application may lock a database file explicity by either way: // - RunInTransaction(Action) locks the database during the transaction (for insert/update) // - RunInDatabaseLock(Action) similarly locks the database but no transaction (for query) private static Dictionary<string, object> syncObjects = new Dictionary<string, object>(); public bool TimeExecution { get; set; } #region debug tracing public bool Trace { get; set; } public delegate void TraceHandler(string message); public event TraceHandler TraceEvent; internal void InvokeTrace(string message) { if (TraceEvent != null) { TraceEvent(message); } } #endregion public bool StoreDateTimeAsTicks { get; private set; } /// <summary> /// Constructs a new SQLiteConnection and opens a SQLite database specified by databasePath. /// </summary> /// <param name="databasePath"> /// Specifies the path to the database file. /// </param> /// <param name="storeDateTimeAsTicks"> /// Specifies whether to store DateTime properties as ticks (true) or strings (false). You /// absolutely do want to store them as Ticks in all new projects. The default of false is /// only here for backwards compatibility. There is a *significant* speed advantage, with no /// down sides, when setting storeDateTimeAsTicks = true. /// </param> public SQLiteConnection(string databasePath, bool storeDateTimeAsTicks = false) : this(databasePath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create, storeDateTimeAsTicks) { } /// <summary> /// Constructs a new SQLiteConnection and opens a SQLite database specified by databasePath. /// </summary> /// <param name="databasePath"> /// Specifies the path to the database file. /// </param> /// <param name="storeDateTimeAsTicks"> /// Specifies whether to store DateTime properties as ticks (true) or strings (false). You /// absolutely do want to store them as Ticks in all new projects. The default of false is /// only here for backwards compatibility. There is a *significant* speed advantage, with no /// down sides, when setting storeDateTimeAsTicks = true. /// </param> public SQLiteConnection(string databasePath, SQLiteOpenFlags openFlags, bool storeDateTimeAsTicks = false) { if (string.IsNullOrEmpty(databasePath)) throw new ArgumentException("Must be specified", "databasePath"); DatabasePath = databasePath; mayCreateSyncObject(databasePath); #if NETFX_CORE SQLite3.SetDirectory(/*temp directory type*/2, Windows.Storage.ApplicationData.Current.TemporaryFolder.Path); #endif Sqlite3DatabaseHandle handle; #if SILVERLIGHT || USE_CSHARP_SQLITE var r = SQLite3.Open (databasePath, out handle, (int)openFlags, IntPtr.Zero); #else // open using the byte[] // in the case where the path may include Unicode // force open to using UTF-8 using sqlite3_open_v2 var databasePathAsBytes = GetNullTerminatedUtf8(DatabasePath); var r = SQLite3.Open(databasePathAsBytes, out handle, (int)openFlags, IntPtr.Zero); #endif Handle = handle; if (r != SQLite3.Result.OK) { throw SQLiteException.New(r, String.Format("Could not open database file: {0} ({1})", DatabasePath, r)); } _open = true; StoreDateTimeAsTicks = storeDateTimeAsTicks; BusyTimeout = TimeSpan.FromSeconds(0.1); } static SQLiteConnection() { if (_preserveDuringLinkMagic) { var ti = new ColumnInfo(); ti.Name = "magic"; } } void mayCreateSyncObject(string databasePath) { if (!syncObjects.ContainsKey(databasePath)) { syncObjects[databasePath] = new object(); } } /// <summary> /// Gets the synchronous object, to be lock the database file for updating. /// </summary> /// <value>The sync object.</value> public object SyncObject { get { return syncObjects[DatabasePath]; } } public void EnableLoadExtension(int onoff) { SQLite3.Result r = SQLite3.EnableLoadExtension(Handle, onoff); if (r != SQLite3.Result.OK) { string msg = SQLite3.GetErrmsg(Handle); throw SQLiteException.New(r, msg); } } static byte[] GetNullTerminatedUtf8(string s) { var utf8Length = System.Text.Encoding.UTF8.GetByteCount(s); var bytes = new byte[utf8Length + 1]; utf8Length = System.Text.Encoding.UTF8.GetBytes(s, 0, s.Length, bytes, 0); return bytes; } /// <summary> /// Used to list some code that we want the MonoTouch linker /// to see, but that we never want to actually execute. /// </summary> #pragma warning disable 649 static bool _preserveDuringLinkMagic; #pragma warning restore 649 /// <summary> /// Sets a busy handler to sleep the specified amount of time when a table is locked. /// The handler will sleep multiple times until a total time of <see cref="BusyTimeout"/> has accumulated. /// </summary> public TimeSpan BusyTimeout { get { return _busyTimeout; } set { _busyTimeout = value; if (Handle != NullHandle) { SQLite3.BusyTimeout(Handle, (int)_busyTimeout.TotalMilliseconds); } } } /// <summary> /// Returns the mappings from types to tables that the connection /// currently understands. /// </summary> public IEnumerable<TableMapping> TableMappings { get { return _tables != null ? _tables.Values : Enumerable.Empty<TableMapping>(); } } /// <summary> /// Retrieves the mapping that is automatically generated for the given type. /// </summary> /// <param name="type"> /// The type whose mapping to the database is returned. /// </param> /// <param name="createFlags"> /// Optional flags allowing implicit PK and indexes based on naming conventions /// </param> /// <returns> /// The mapping represents the schema of the columns of the database and contains /// methods to set and get properties of objects. /// </returns> public TableMapping GetMapping(Type type, CreateFlags createFlags = CreateFlags.None) { if (_mappings == null) { _mappings = new Dictionary<string, TableMapping>(); } TableMapping map; if (!_mappings.TryGetValue(type.FullName, out map)) { map = new TableMapping(type, createFlags); _mappings[type.FullName] = map; } return map; } /// <summary> /// Retrieves the mapping that is automatically generated for the given type. /// </summary> /// <returns> /// The mapping represents the schema of the columns of the database and contains /// methods to set and get properties of objects. /// </returns> public TableMapping GetMapping<T>() { return GetMapping(typeof(T)); } private struct IndexedColumn { public int Order; public string ColumnName; } private struct IndexInfo { public string IndexName; public string TableName; public bool Unique; public List<IndexedColumn> Columns; } /// <summary> /// Executes a "drop table" on the database. This is non-recoverable. /// </summary> public int DropTable<T>() { var map = GetMapping(typeof(T)); var query = string.Format("drop table if exists \"{0}\"", map.TableName); return Execute(query); } /// <summary> /// Executes a "create table if not exists" on the database. It also /// creates any specified indexes on the columns of the table. It uses /// a schema automatically generated from the specified type. You can /// later access this schema by calling GetMapping. /// </summary> /// <returns> /// The number of entries added to the database schema. /// </returns> public int CreateTable<T>(CreateFlags createFlags = CreateFlags.None) { return CreateTable(typeof(T), createFlags); } /// <summary> /// Executes a "create table if not exists" on the database. It also /// creates any specified indexes on the columns of the table. It uses /// a schema automatically generated from the specified type. You can /// later access this schema by calling GetMapping. /// </summary> /// <param name="ty">Type to reflect to a database table.</param> /// <param name="createFlags">Optional flags allowing implicit PK and indexes based on naming conventions.</param> /// <returns> /// The number of entries added to the database schema. /// </returns> public int CreateTable(Type ty, CreateFlags createFlags = CreateFlags.None) { if (_tables == null) { _tables = new Dictionary<string, TableMapping>(); } TableMapping map; if (!_tables.TryGetValue(ty.FullName, out map)) { map = GetMapping(ty, createFlags); _tables.Add(ty.FullName, map); } var query = "create table if not exists \"" + map.TableName + "\"(\n"; var decls = map.Columns.Select(p => Orm.SqlDecl(p, StoreDateTimeAsTicks)); var decl = string.Join(",\n", decls.ToArray()); query += decl; query += ")"; var count = Execute(query); if (count == 0) { //Possible bug: This always seems to return 0? // Table already exists, migrate it MigrateTable(map); } var indexes = new Dictionary<string, IndexInfo>(); foreach (var c in map.Columns) { foreach (var i in c.Indices) { var iname = i.Name ?? map.TableName + "_" + c.Name; IndexInfo iinfo; if (!indexes.TryGetValue(iname, out iinfo)) { iinfo = new IndexInfo { IndexName = iname, TableName = map.TableName, Unique = i.Unique, Columns = new List<IndexedColumn>() }; indexes.Add(iname, iinfo); } if (i.Unique != iinfo.Unique) throw new Exception("All the columns in an index must have the same value for their Unique property"); iinfo.Columns.Add(new IndexedColumn { Order = i.Order, ColumnName = c.Name }); } } foreach (var indexName in indexes.Keys) { var index = indexes[indexName]; string[] columnNames = new string[index.Columns.Count]; if (index.Columns.Count == 1) { columnNames[0] = index.Columns[0].ColumnName; } else { index.Columns.Sort((lhs, rhs) => { return lhs.Order - rhs.Order; }); for (int i = 0, end = index.Columns.Count; i < end; ++i) { columnNames[i] = index.Columns[i].ColumnName; } } count += CreateIndex(indexName, index.TableName, columnNames, index.Unique); } return count; } /// <summary> /// Creates an index for the specified table and columns. /// </summary> /// <param name="indexName">Name of the index to create</param> /// <param name="tableName">Name of the database table</param> /// <param name="columnNames">An array of column names to index</param> /// <param name="unique">Whether the index should be unique</param> public int CreateIndex(string indexName, string tableName, string[] columnNames, bool unique = false) { const string sqlFormat = "create {2} index if not exists \"{3}\" on \"{0}\"(\"{1}\")"; var sql = String.Format(sqlFormat, tableName, string.Join("\", \"", columnNames), unique ? "unique" : "", indexName); return Execute(sql); } /// <summary> /// Creates an index for the specified table and column. /// </summary> /// <param name="indexName">Name of the index to create</param> /// <param name="tableName">Name of the database table</param> /// <param name="columnName">Name of the column to index</param> /// <param name="unique">Whether the index should be unique</param> public int CreateIndex(string indexName, string tableName, string columnName, bool unique = false) { return CreateIndex(indexName, tableName, new string[] { columnName }, unique); } /// <summary> /// Creates an index for the specified table and column. /// </summary> /// <param name="tableName">Name of the database table</param> /// <param name="columnName">Name of the column to index</param> /// <param name="unique">Whether the index should be unique</param> public int CreateIndex(string tableName, string columnName, bool unique = false) { return CreateIndex(tableName + "_" + columnName, tableName, columnName, unique); } /// <summary> /// Creates an index for the specified table and columns. /// </summary> /// <param name="tableName">Name of the database table</param> /// <param name="columnNames">An array of column names to index</param> /// <param name="unique">Whether the index should be unique</param> public int CreateIndex(string tableName, string[] columnNames, bool unique = false) { return CreateIndex(tableName + "_" + string.Join("_", columnNames), tableName, columnNames, unique); } /// <summary> /// Creates an index for the specified object property. /// e.g. CreateIndex<Client>(c => c.Name); /// </summary> /// <typeparam name="T">Type to reflect to a database table.</typeparam> /// <param name="property">Property to index</param> /// <param name="unique">Whether the index should be unique</param> public void CreateIndex<T>(Expression<Func<T, object>> property, bool unique = false) { MemberExpression mx; if (property.Body.NodeType == ExpressionType.Convert) { mx = ((UnaryExpression)property.Body).Operand as MemberExpression; } else { mx = (property.Body as MemberExpression); } var propertyInfo = mx.Member as PropertyInfo; if (propertyInfo == null) { throw new ArgumentException("The lambda expression 'property' should point to a valid Property"); } var propName = propertyInfo.Name; var map = GetMapping<T>(); var colName = map.FindColumnWithPropertyName(propName).Name; CreateIndex(map.TableName, colName, unique); } public class ColumnInfo { // public int cid { get; set; } [Column("name")] public string Name { get; set; } // [Column ("type")] // public string ColumnType { get; set; } public int notnull { get; set; } // public string dflt_value { get; set; } // public int pk { get; set; } public override string ToString() { return Name; } } public List<ColumnInfo> GetTableInfo(string tableName) { var query = "pragma table_info(\"" + tableName + "\")"; return Query<ColumnInfo>(query); } void MigrateTable(TableMapping map) { var existingCols = GetTableInfo(map.TableName); var toBeAdded = new List<TableMapping.Column>(); foreach (var p in map.Columns) { var found = false; foreach (var c in existingCols) { found = (string.Compare(p.Name, c.Name, StringComparison.OrdinalIgnoreCase) == 0); if (found) break; } if (!found) { toBeAdded.Add(p); } } foreach (var p in toBeAdded) { var addCol = "alter table \"" + map.TableName + "\" add column " + Orm.SqlDecl(p, StoreDateTimeAsTicks); Execute(addCol); } } /// <summary> /// Creates a new SQLiteCommand. Can be overridden to provide a sub-class. /// </summary> /// <seealso cref="SQLiteCommand.OnInstanceCreated"/> protected virtual SQLiteCommand NewCommand() { return new SQLiteCommand(this); } /// <summary> /// Creates a new SQLiteCommand given the command text with arguments. Place a '?' /// in the command text for each of the arguments. /// </summary> /// <param name="cmdText"> /// The fully escaped SQL. /// </param> /// <param name="args"> /// Arguments to substitute for the occurences of '?' in the command text. /// </param> /// <returns> /// A <see cref="SQLiteCommand"/> /// </returns> public SQLiteCommand CreateCommand(string cmdText, params object[] ps) { if (!_open) throw SQLiteException.New(SQLite3.Result.Error, "Cannot create commands from unopened database"); var cmd = NewCommand(); cmd.CommandText = cmdText; foreach (var o in ps) { cmd.Bind(o); } return cmd; } /// <summary> /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?' /// in the command text for each of the arguments and then executes that command. /// Use this method instead of Query when you don't expect rows back. Such cases include /// INSERTs, UPDATEs, and DELETEs. /// You can set the Trace or TimeExecution properties of the connection /// to profile execution. /// </summary> /// <param name="query"> /// The fully escaped SQL. /// </param> /// <param name="args"> /// Arguments to substitute for the occurences of '?' in the query. /// </param> /// <returns> /// The number of rows modified in the database as a result of this execution. /// </returns> public int Execute(string query, params object[] args) { var cmd = CreateCommand(query, args); if (TimeExecution) { if (_sw == null) { _sw = new Stopwatch(); } _sw.Reset(); _sw.Start(); } var r = cmd.ExecuteNonQuery(); if (TimeExecution) { _sw.Stop(); _elapsedMilliseconds += _sw.ElapsedMilliseconds; Debug.WriteLine(string.Format("Finished in {0} ms ({1:0.0} s total)", _sw.ElapsedMilliseconds, _elapsedMilliseconds / 1000.0)); } return r; } public T ExecuteScalar<T>(string query, params object[] args) { var cmd = CreateCommand(query, args); if (TimeExecution) { if (_sw == null) { _sw = new Stopwatch(); } _sw.Reset(); _sw.Start(); } var r = cmd.ExecuteScalar<T>(); if (TimeExecution) { _sw.Stop(); _elapsedMilliseconds += _sw.ElapsedMilliseconds; Debug.WriteLine(string.Format("Finished in {0} ms ({1:0.0} s total)", _sw.ElapsedMilliseconds, _elapsedMilliseconds / 1000.0)); } return r; } /// <summary> /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?' /// in the command text for each of the arguments and then executes that command. /// It returns each row of the result using the mapping automatically generated for /// the given type. /// </summary> /// <param name="query"> /// The fully escaped SQL. /// </param> /// <param name="args"> /// Arguments to substitute for the occurences of '?' in the query. /// </param> /// <returns> /// An enumerable with one result for each row returned by the query. /// </returns> public List<T> Query<T>(string query, params object[] args) where T : new() { var cmd = CreateCommand(query, args); return cmd.ExecuteQuery<T>(); } /// <summary> /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?' /// in the command text for each of the arguments and then executes that command. /// It returns each row of the result using the mapping automatically generated for /// the given type. /// </summary> /// <param name="query"> /// The fully escaped SQL. /// </param> /// <param name="args"> /// Arguments to substitute for the occurences of '?' in the query. /// </param> /// <returns> /// An enumerable with one result for each row returned by the query. /// The enumerator will call sqlite3_step on each call to MoveNext, so the database /// connection must remain open for the lifetime of the enumerator. /// </returns> public IEnumerable<T> DeferredQuery<T>(string query, params object[] args) where T : new() { var cmd = CreateCommand(query, args); return cmd.ExecuteDeferredQuery<T>(); } /// <summary> /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?' /// in the command text for each of the arguments and then executes that command. /// It returns each row of the result using the specified mapping. This function is /// only used by libraries in order to query the database via introspection. It is /// normally not used. /// </summary> /// <param name="map"> /// A <see cref="TableMapping"/> to use to convert the resulting rows /// into objects. /// </param> /// <param name="query"> /// The fully escaped SQL. /// </param> /// <param name="args"> /// Arguments to substitute for the occurences of '?' in the query. /// </param> /// <returns> /// An enumerable with one result for each row returned by the query. /// </returns> public List<object> Query(TableMapping map, string query, params object[] args) { var cmd = CreateCommand(query, args); return cmd.ExecuteQuery<object>(map); } /// <summary> /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?' /// in the command text for each of the arguments and then executes that command. /// It returns each row of the result using the specified mapping. This function is /// only used by libraries in order to query the database via introspection. It is /// normally not used. /// </summary> /// <param name="map"> /// A <see cref="TableMapping"/> to use to convert the resulting rows /// into objects. /// </param> /// <param name="query"> /// The fully escaped SQL. /// </param> /// <param name="args"> /// Arguments to substitute for the occurences of '?' in the query. /// </param> /// <returns> /// An enumerable with one result for each row returned by the query. /// The enumerator will call sqlite3_step on each call to MoveNext, so the database /// connection must remain open for the lifetime of the enumerator. /// </returns> public IEnumerable<object> DeferredQuery(TableMapping map, string query, params object[] args) { var cmd = CreateCommand(query, args); return cmd.ExecuteDeferredQuery<object>(map); } /// <summary> /// Returns a queryable interface to the table represented by the given type. /// </summary> /// <returns> /// A queryable object that is able to translate Where, OrderBy, and Take /// queries into native SQL. /// </returns> public TableQuery<T> Table<T>() where T : new() { return new TableQuery<T>(this); } /// <summary> /// Attempts to retrieve an object with the given primary key from the table /// associated with the specified type. Use of this method requires that /// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute). /// </summary> /// <param name="pk"> /// The primary key. /// </param> /// <returns> /// The object with the given primary key. Throws a not found exception /// if the object is not found. /// </returns> public T Get<T>(object pk) where T : new() { var map = GetMapping(typeof(T)); return Query<T>(map.GetByPrimaryKeySql, pk).First(); } /// <summary> /// Attempts to retrieve the first object that matches the predicate from the table /// associated with the specified type. /// </summary> /// <param name="predicate"> /// A predicate for which object to find. /// </param> /// <returns> /// The object that matches the given predicate. Throws a not found exception /// if the object is not found. /// </returns> public T Get<T>(Expression<Func<T, bool>> predicate) where T : new() { return Table<T>().Where(predicate).First(); } /// <summary> /// Attempts to retrieve an object with the given primary key from the table /// associated with the specified type. Use of this method requires that /// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute). /// </summary> /// <param name="pk"> /// The primary key. /// </param> /// <returns> /// The object with the given primary key or null /// if the object is not found. /// </returns> public T Find<T>(object pk) where T : new() { var map = GetMapping(typeof(T)); return Query<T>(map.GetByPrimaryKeySql, pk).FirstOrDefault(); } /// <summary> /// Attempts to retrieve an object with the given primary key from the table /// associated with the specified type. Use of this method requires that /// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute). /// </summary> /// <param name="pk"> /// The primary key. /// </param> /// <param name="map"> /// The TableMapping used to identify the object type. /// </param> /// <returns> /// The object with the given primary key or null /// if the object is not found. /// </returns> public object Find(object pk, TableMapping map) { return Query(map, map.GetByPrimaryKeySql, pk).FirstOrDefault(); } /// <summary> /// Attempts to retrieve the first object that matches the predicate from the table /// associated with the specified type. /// </summary> /// <param name="predicate"> /// A predicate for which object to find. /// </param> /// <returns> /// The object that matches the given predicate or null /// if the object is not found. /// </returns> public T Find<T>(Expression<Func<T, bool>> predicate) where T : new() { return Table<T>().Where(predicate).FirstOrDefault(); } /// <summary> /// Whether <see cref="BeginTransaction"/> has been called and the database is waiting for a <see cref="Commit"/>. /// </summary> public bool IsInTransaction { get { return _transactionDepth > 0; } } /// <summary> /// Begins a new transaction. Call <see cref="Commit"/> to end the transaction. /// </summary> /// <example cref="System.InvalidOperationException">Throws if a transaction has already begun.</example> public void BeginTransaction() { // The BEGIN command only works if the transaction stack is empty, // or in other words if there are no pending transactions. // If the transaction stack is not empty when the BEGIN command is invoked, // then the command fails with an error. // Rather than crash with an error, we will just ignore calls to BeginTransaction // that would result in an error. if (Interlocked.CompareExchange(ref _transactionDepth, 1, 0) == 0) { try { Execute("begin transaction"); } catch (Exception ex) { var sqlExp = ex as SQLiteException; if (sqlExp != null) { // It is recommended that applications respond to the errors listed below // by explicitly issuing a ROLLBACK command. // TODO: This rollback failsafe should be localized to all throw sites. switch (sqlExp.Result) { case SQLite3.Result.IOError: case SQLite3.Result.Full: case SQLite3.Result.Busy: case SQLite3.Result.NoMem: case SQLite3.Result.Interrupt: RollbackTo(null, true); break; } } else { // Call decrement and not VolatileWrite in case we've already // created a transaction point in SaveTransactionPoint since the catch. Interlocked.Decrement(ref _transactionDepth); } throw; } } else { // Calling BeginTransaction on an already open transaction is invalid throw new InvalidOperationException("Cannot begin a transaction while already in a transaction."); } } /// <summary> /// Creates a savepoint in the database at the current point in the transaction timeline. /// Begins a new transaction if one is not in progress. /// /// Call <see cref="RollbackTo"/> to undo transactions since the returned savepoint. /// Call <see cref="Release"/> to commit transactions after the savepoint returned here. /// Call <see cref="Commit"/> to end the transaction, committing all changes. /// </summary> /// <returns>A string naming the savepoint.</returns> public string SaveTransactionPoint() { int depth = Interlocked.Increment(ref _transactionDepth) - 1; string retVal = "S" + _rand.Next(short.MaxValue) + "D" + depth; try { Execute("savepoint " + retVal); } catch (Exception ex) { var sqlExp = ex as SQLiteException; if (sqlExp != null) { // It is recommended that applications respond to the errors listed below // by explicitly issuing a ROLLBACK command. // TODO: This rollback failsafe should be localized to all throw sites. switch (sqlExp.Result) { case SQLite3.Result.IOError: case SQLite3.Result.Full: case SQLite3.Result.Busy: case SQLite3.Result.NoMem: case SQLite3.Result.Interrupt: RollbackTo(null, true); break; } } else { Interlocked.Decrement(ref _transactionDepth); } throw; } return retVal; } /// <summary> /// Rolls back the transaction that was begun by <see cref="BeginTransaction"/> or <see cref="SaveTransactionPoint"/>. /// </summary> public void Rollback() { RollbackTo(null, false); } /// <summary> /// Rolls back the savepoint created by <see cref="BeginTransaction"/> or SaveTransactionPoint. /// </summary> /// <param name="savepoint">The name of the savepoint to roll back to, as returned by <see cref="SaveTransactionPoint"/>. If savepoint is null or empty, this method is equivalent to a call to <see cref="Rollback"/></param> public void RollbackTo(string savepoint) { RollbackTo(savepoint, false); } /// <summary> /// Rolls back the transaction that was begun by <see cref="BeginTransaction"/>. /// </summary> /// <param name="noThrow">true to avoid throwing exceptions, false otherwise</param> void RollbackTo(string savepoint, bool noThrow) { // Rolling back without a TO clause rolls backs all transactions // and leaves the transaction stack empty. try { if (String.IsNullOrEmpty(savepoint)) { if (Interlocked.Exchange(ref _transactionDepth, 0) > 0) { Execute("rollback"); } } else { DoSavePointExecute(savepoint, "rollback to "); } } catch (SQLiteException) { if (!noThrow) throw; } // No need to rollback if there are no transactions open. } /// <summary> /// Releases a savepoint returned from <see cref="SaveTransactionPoint"/>. Releasing a savepoint /// makes changes since that savepoint permanent if the savepoint began the transaction, /// or otherwise the changes are permanent pending a call to <see cref="Commit"/>. /// /// The RELEASE command is like a COMMIT for a SAVEPOINT. /// </summary> /// <param name="savepoint">The name of the savepoint to release. The string should be the result of a call to <see cref="SaveTransactionPoint"/></param> public void Release(string savepoint) { DoSavePointExecute(savepoint, "release "); } void DoSavePointExecute(string savepoint, string cmd) { // Validate the savepoint int firstLen = savepoint.IndexOf('D'); if (firstLen >= 2 && savepoint.Length > firstLen + 1) { int depth; if (Int32.TryParse(savepoint.Substring(firstLen + 1), out depth)) { // TODO: Mild race here, but inescapable without locking almost everywhere. if (0 <= depth && depth < _transactionDepth) { #if NETFX_CORE Volatile.Write (ref _transactionDepth, depth); #elif SILVERLIGHT _transactionDepth = depth; #else Thread.VolatileWrite(ref _transactionDepth, depth); #endif Execute(cmd + savepoint); return; } } } throw new ArgumentException("savePoint is not valid, and should be the result of a call to SaveTransactionPoint.", "savePoint"); } /// <summary> /// Commits the transaction that was begun by <see cref="BeginTransaction"/>. /// </summary> public void Commit() { if (Interlocked.Exchange(ref _transactionDepth, 0) != 0) { Execute("commit"); } // Do nothing on a commit with no open transaction } /// <summary> /// Executes <param name="action"> within a (possibly nested) transaction by wrapping it in a SAVEPOINT. If an /// exception occurs the whole transaction is rolled back, not just the current savepoint. The exception /// is rethrown. /// </summary> /// <param name="action"> /// The <see cref="Action"/> to perform within a transaction. <param name="action"> can contain any number /// of operations on the connection but should never call <see cref="BeginTransaction"/> or /// <see cref="Commit"/>. /// </param> public void RunInTransaction(Action action) { try { lock (syncObjects[DatabasePath]) { var savePoint = SaveTransactionPoint(); action(); Release(savePoint); } } catch (Exception) { Rollback(); throw; } } /// <summary> /// Executes <param name="action"> while blocking other threads to access the same database. /// </summary> /// <param name="action"> /// The <see cref="Action"/> to perform within a lock. /// </param> public void RunInDatabaseLock(Action action) { lock (syncObjects[DatabasePath]) { action(); } } /// <summary> /// Inserts all specified objects. /// </summary> /// <param name="objects"> /// An <see cref="IEnumerable"/> of the objects to insert. /// </param> /// <returns> /// The number of rows added to the table. /// </returns> public int InsertAll(System.Collections.IEnumerable objects) { var c = 0; RunInTransaction(() => { foreach (var r in objects) { c += Insert(r); } }); return c; } /// <summary> /// Inserts all specified objects. /// </summary> /// <param name="objects"> /// An <see cref="IEnumerable"/> of the objects to insert. /// </param> /// <param name="extra"> /// Literal SQL code that gets placed into the command. INSERT {extra} INTO ... /// </param> /// <returns> /// The number of rows added to the table. /// </returns> public int InsertAll(System.Collections.IEnumerable objects, string extra) { var c = 0; RunInTransaction(() => { foreach (var r in objects) { c += Insert(r, extra); } }); return c; } /// <summary> /// Inserts all specified objects. /// </summary> /// <param name="objects"> /// An <see cref="IEnumerable"/> of the objects to insert. /// </param> /// <param name="objType"> /// The type of object to insert. /// </param> /// <returns> /// The number of rows added to the table. /// </returns> public int InsertAll(System.Collections.IEnumerable objects, Type objType) { var c = 0; RunInTransaction(() => { foreach (var r in objects) { c += Insert(r, objType); } }); return c; } /// <summary> /// Inserts the given object and retrieves its /// auto incremented primary key if it has one. /// </summary> /// <param name="obj"> /// The object to insert. /// </param> /// <returns> /// The number of rows added to the table. /// </returns> public int Insert(object obj) { if (obj == null) { return 0; } return Insert(obj, "", obj.GetType()); } /// <summary> /// Inserts the given object and retrieves its /// auto incremented primary key if it has one. /// If a UNIQUE constraint violation occurs with /// some pre-existing object, this function deletes /// the old object. /// </summary> /// <param name="obj"> /// The object to insert. /// </param> /// <returns> /// The number of rows modified. /// </returns> public int InsertOrReplace(object obj) { if (obj == null) { return 0; } return Insert(obj, "OR REPLACE", obj.GetType()); } /// <summary> /// Inserts the given object and retrieves its /// auto incremented primary key if it has one. /// </summary> /// <param name="obj"> /// The object to insert. /// </param> /// <param name="objType"> /// The type of object to insert. /// </param> /// <returns> /// The number of rows added to the table. /// </returns> public int Insert(object obj, Type objType) { return Insert(obj, "", objType); } /// <summary> /// Inserts the given object and retrieves its /// auto incremented primary key if it has one. /// If a UNIQUE constraint violation occurs with /// some pre-existing object, this function deletes /// the old object. /// </summary> /// <param name="obj"> /// The object to insert. /// </param> /// <param name="objType"> /// The type of object to insert. /// </param> /// <returns> /// The number of rows modified. /// </returns> public int InsertOrReplace(object obj, Type objType) { return Insert(obj, "OR REPLACE", objType); } /// <summary> /// Inserts the given object and retrieves its /// auto incremented primary key if it has one. /// </summary> /// <param name="obj"> /// The object to insert. /// </param> /// <param name="extra"> /// Literal SQL code that gets placed into the command. INSERT {extra} INTO ... /// </param> /// <returns> /// The number of rows added to the table. /// </returns> public int Insert(object obj, string extra) { if (obj == null) { return 0; } return Insert(obj, extra, obj.GetType()); } /// <summary> /// Inserts the given object and retrieves its /// auto incremented primary key if it has one. /// </summary> /// <param name="obj"> /// The object to insert. /// </param> /// <param name="extra"> /// Literal SQL code that gets placed into the command. INSERT {extra} INTO ... /// </param> /// <param name="objType"> /// The type of object to insert. /// </param> /// <returns> /// The number of rows added to the table. /// </returns> public int Insert(object obj, string extra, Type objType) { if (obj == null || objType == null) { return 0; } var map = GetMapping(objType); #if NETFX_CORE if (map.PK != null && map.PK.IsAutoGuid) { // no GetProperty so search our way up the inheritance chain till we find it PropertyInfo prop; while (objType != null) { var info = objType.GetTypeInfo(); prop = info.GetDeclaredProperty(map.PK.PropertyName); if (prop != null) { if (prop.GetValue(obj, null).Equals(Guid.Empty)) { prop.SetValue(obj, Guid.NewGuid(), null); } break; } objType = info.BaseType; } } #else if (map.PK != null && map.PK.IsAutoGuid) { var prop = objType.GetProperty(map.PK.PropertyName); if (prop != null) { //if (prop.GetValue(obj, null).Equals(Guid.Empty)) { if (prop.GetGetMethod().Invoke(obj, null).Equals(Guid.Empty)) { prop.SetValue(obj, Guid.NewGuid(), null); } } } #endif var replacing = string.Compare(extra, "OR REPLACE", StringComparison.OrdinalIgnoreCase) == 0; var cols = replacing ? map.InsertOrReplaceColumns : map.InsertColumns; var vals = new object[cols.Length]; for (var i = 0; i < vals.Length; i++) { vals[i] = cols[i].GetValue(obj); } var insertCmd = map.GetInsertCommand(this, extra); int count; try { count = insertCmd.ExecuteNonQuery(vals); } catch (SQLiteException ex) { if (SQLite3.ExtendedErrCode(this.Handle) == SQLite3.ExtendedResult.ConstraintNotNull) { throw NotNullConstraintViolationException.New(ex.Result, ex.Message, map, obj); } throw; } if (map.HasAutoIncPK) { var id = SQLite3.LastInsertRowid(Handle); map.SetAutoIncPK(obj, id); } return count; } /// <summary> /// Updates all of the columns of a table using the specified object /// except for its primary key. /// The object is required to have a primary key. /// </summary> /// <param name="obj"> /// The object to update. It must have a primary key designated using the PrimaryKeyAttribute. /// </param> /// <returns> /// The number of rows updated. /// </returns> public int Update(object obj) { if (obj == null) { return 0; } return Update(obj, obj.GetType()); } /// <summary> /// Updates all of the columns of a table using the specified object /// except for its primary key. /// The object is required to have a primary key. /// </summary> /// <param name="obj"> /// The object to update. It must have a primary key designated using the PrimaryKeyAttribute. /// </param> /// <param name="objType"> /// The type of object to insert. /// </param> /// <returns> /// The number of rows updated. /// </returns> public int Update(object obj, Type objType) { int rowsAffected = 0; if (obj == null || objType == null) { return 0; } var map = GetMapping(objType); var pk = map.PK; if (pk == null) { throw new NotSupportedException("Cannot update " + map.TableName + ": it has no PK"); } var cols = from p in map.Columns where p != pk select p; var vals = from c in cols select c.GetValue(obj); var ps = new List<object>(vals); ps.Add(pk.GetValue(obj)); var q = string.Format("update \"{0}\" set {1} where {2} = ? ", map.TableName, string.Join(",", (from c in cols select "\"" + c.Name + "\" = ? ").ToArray()), pk.Name); try { rowsAffected = Execute(q, ps.ToArray()); } catch (SQLiteException ex) { if (ex.Result == SQLite3.Result.Constraint && SQLite3.ExtendedErrCode(this.Handle) == SQLite3.ExtendedResult.ConstraintNotNull) { throw NotNullConstraintViolationException.New(ex, map, obj); } throw ex; } return rowsAffected; } /// <summary> /// Updates all specified objects. /// </summary> /// <param name="objects"> /// An <see cref="IEnumerable"/> of the objects to insert. /// </param> /// <returns> /// The number of rows modified. /// </returns> public int UpdateAll(System.Collections.IEnumerable objects) { var c = 0; RunInTransaction(() => { foreach (var r in objects) { c += Update(r); } }); return c; } /// <summary> /// Deletes the given object from the database using its primary key. /// </summary> /// <param name="objectToDelete"> /// The object to delete. It must have a primary key designated using the PrimaryKeyAttribute. /// </param> /// <returns> /// The number of rows deleted. /// </returns> public int Delete(object objectToDelete) { var map = GetMapping(objectToDelete.GetType()); var pk = map.PK; if (pk == null) { throw new NotSupportedException("Cannot delete " + map.TableName + ": it has no PK"); } var q = string.Format("delete from \"{0}\" where \"{1}\" = ?", map.TableName, pk.Name); return Execute(q, pk.GetValue(objectToDelete)); } /// <summary> /// Deletes the object with the specified primary key. /// </summary> /// <param name="primaryKey"> /// The primary key of the object to delete. /// </param> /// <returns> /// The number of objects deleted. /// </returns> /// <typeparam name='T'> /// The type of object. /// </typeparam> public int Delete<T>(object primaryKey) { var map = GetMapping(typeof(T)); var pk = map.PK; if (pk == null) { throw new NotSupportedException("Cannot delete " + map.TableName + ": it has no PK"); } var q = string.Format("delete from \"{0}\" where \"{1}\" = ?", map.TableName, pk.Name); return Execute(q, primaryKey); } /// <summary> /// Deletes all the objects from the specified table. /// WARNING WARNING: Let me repeat. It deletes ALL the objects from the /// specified table. Do you really want to do that? /// </summary> /// <returns> /// The number of objects deleted. /// </returns> /// <typeparam name='T'> /// The type of objects to delete. /// </typeparam> public int DeleteAll<T>() { var map = GetMapping(typeof(T)); var query = string.Format("delete from \"{0}\"", map.TableName); return Execute(query); } ~SQLiteConnection() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { Close(); } public void Close() { if (_open && Handle != NullHandle) { try { if (_mappings != null) { foreach (var sqlInsertCommand in _mappings.Values) { sqlInsertCommand.Dispose(); } } var r = SQLite3.Close(Handle); if (r != SQLite3.Result.OK) { string msg = SQLite3.GetErrmsg(Handle); throw SQLiteException.New(r, msg); } } finally { Handle = NullHandle; _open = false; } } } } /// <summary> /// Represents a parsed connection string. /// </summary> class SQLiteConnectionString { public string ConnectionString { get; private set; } public string DatabasePath { get; private set; } public bool StoreDateTimeAsTicks { get; private set; } #if NETFX_CORE static readonly string MetroStyleDataPath = Windows.Storage.ApplicationData.Current.LocalFolder.Path; #endif public SQLiteConnectionString(string databasePath, bool storeDateTimeAsTicks) { ConnectionString = databasePath; StoreDateTimeAsTicks = storeDateTimeAsTicks; #if NETFX_CORE DatabasePath = System.IO.Path.Combine (MetroStyleDataPath, databasePath); #else DatabasePath = databasePath; #endif } } [AttributeUsage(AttributeTargets.Class)] public class TableAttribute : Attribute { public string Name { get; set; } public TableAttribute(string name) { Name = name; } } [AttributeUsage(AttributeTargets.Property)] public class ColumnAttribute : Attribute { public string Name { get; set; } public ColumnAttribute(string name) { Name = name; } } [AttributeUsage(AttributeTargets.Property)] public class PrimaryKeyAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property)] public class AutoIncrementAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property)] public class IndexedAttribute : Attribute { public string Name { get; set; } public int Order { get; set; } public virtual bool Unique { get; set; } public IndexedAttribute() { } public IndexedAttribute(string name, int order) { Name = name; Order = order; } } [AttributeUsage(AttributeTargets.Property)] public class IgnoreAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property)] public class UniqueAttribute : IndexedAttribute { public override bool Unique { get { return true; } set { /* throw? */ } } } [AttributeUsage(AttributeTargets.Property)] public class MaxLengthAttribute : Attribute { public int Value { get; private set; } public MaxLengthAttribute(int length) { Value = length; } } [AttributeUsage(AttributeTargets.Property)] public class CollationAttribute : Attribute { public string Value { get; private set; } public CollationAttribute(string collation) { Value = collation; } } [AttributeUsage(AttributeTargets.Property)] public class NotNullAttribute : Attribute { } public class TableMapping { public Type MappedType { get; private set; } public string TableName { get; private set; } public Column[] Columns { get; private set; } public Column PK { get; private set; } public string GetByPrimaryKeySql { get; private set; } Column _autoPk; Column[] _insertColumns; Column[] _insertOrReplaceColumns; public TableMapping(Type type, CreateFlags createFlags = CreateFlags.None) { MappedType = type; #if NETFX_CORE var tableAttr = (TableAttribute)System.Reflection.CustomAttributeExtensions .GetCustomAttribute(type.GetTypeInfo(), typeof(TableAttribute), true); #else var tableAttr = (TableAttribute)type.GetCustomAttributes(typeof(TableAttribute), true).FirstOrDefault(); #endif TableName = tableAttr != null ? tableAttr.Name : MappedType.Name; #if !NETFX_CORE var props = MappedType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty); #else var props = from p in MappedType.GetRuntimeProperties() where ((p.GetMethod != null && p.GetMethod.IsPublic) || (p.SetMethod != null && p.SetMethod.IsPublic) || (p.GetMethod != null && p.GetMethod.IsStatic) || (p.SetMethod != null && p.SetMethod.IsStatic)) select p; #endif var cols = new List<Column>(); foreach (var p in props) { #if !NETFX_CORE var ignore = p.GetCustomAttributes(typeof(IgnoreAttribute), true).Length > 0; #else var ignore = p.GetCustomAttributes (typeof(IgnoreAttribute), true).Count() > 0; #endif if (p.CanWrite && !ignore) { cols.Add(new Column(p, createFlags)); } } Columns = cols.ToArray(); foreach (var c in Columns) { if (c.IsAutoInc && c.IsPK) { _autoPk = c; } if (c.IsPK) { PK = c; } } HasAutoIncPK = _autoPk != null; if (PK != null) { GetByPrimaryKeySql = string.Format("select * from \"{0}\" where \"{1}\" = ?", TableName, PK.Name); } else { // People should not be calling Get/Find without a PK GetByPrimaryKeySql = string.Format("select * from \"{0}\" limit 1", TableName); } } public bool HasAutoIncPK { get; private set; } public void SetAutoIncPK(object obj, long id) { if (_autoPk != null) { _autoPk.SetValue(obj, Convert.ChangeType(id, _autoPk.ColumnType, null)); } } public Column[] InsertColumns { get { if (_insertColumns == null) { _insertColumns = Columns.Where(c => !c.IsAutoInc).ToArray(); } return _insertColumns; } } public Column[] InsertOrReplaceColumns { get { if (_insertOrReplaceColumns == null) { _insertOrReplaceColumns = Columns.ToArray(); } return _insertOrReplaceColumns; } } public Column FindColumnWithPropertyName(string propertyName) { var exact = Columns.FirstOrDefault(c => c.PropertyName == propertyName); return exact; } public Column FindColumn(string columnName) { var exact = Columns.FirstOrDefault(c => c.Name == columnName); return exact; } PreparedSqlLiteInsertCommand _insertCommand; string _insertCommandExtra; public PreparedSqlLiteInsertCommand GetInsertCommand(SQLiteConnection conn, string extra) { if (_insertCommand == null) { _insertCommand = CreateInsertCommand(conn, extra); _insertCommandExtra = extra; } else if (_insertCommandExtra != extra) { _insertCommand.Dispose(); _insertCommand = CreateInsertCommand(conn, extra); _insertCommandExtra = extra; } return _insertCommand; } PreparedSqlLiteInsertCommand CreateInsertCommand(SQLiteConnection conn, string extra) { var cols = InsertColumns; string insertSql; if (!cols.Any() && Columns.Count() == 1 && Columns[0].IsAutoInc) { insertSql = string.Format("insert {1} into \"{0}\" default values", TableName, extra); } else { var replacing = string.Compare(extra, "OR REPLACE", StringComparison.OrdinalIgnoreCase) == 0; if (replacing) { cols = InsertOrReplaceColumns; } insertSql = string.Format("insert {3} into \"{0}\"({1}) values ({2})", TableName, string.Join(",", (from c in cols select "\"" + c.Name + "\"").ToArray()), string.Join(",", (from c in cols select "?").ToArray()), extra); } var insertCommand = new PreparedSqlLiteInsertCommand(conn); insertCommand.CommandText = insertSql; return insertCommand; } protected internal void Dispose() { if (_insertCommand != null) { _insertCommand.Dispose(); _insertCommand = null; } } public class Column { PropertyInfo _prop; public string Name { get; private set; } public string PropertyName { get { return _prop.Name; } } public Type ColumnType { get; private set; } public string Collation { get; private set; } public bool IsAutoInc { get; private set; } public bool IsAutoGuid { get; private set; } public bool IsPK { get; private set; } public IEnumerable<IndexedAttribute> Indices { get; set; } public bool IsNullable { get; private set; } public int? MaxStringLength { get; private set; } public Column(PropertyInfo prop, CreateFlags createFlags = CreateFlags.None) { var colAttr = (ColumnAttribute)prop.GetCustomAttributes(typeof(ColumnAttribute), true).FirstOrDefault(); _prop = prop; Name = colAttr == null ? prop.Name : colAttr.Name; //If this type is Nullable<T> then Nullable.GetUnderlyingType returns the T, otherwise it returns null, so get the actual type instead ColumnType = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType; Collation = Orm.Collation(prop); IsPK = Orm.IsPK(prop) || (((createFlags & CreateFlags.ImplicitPK) == CreateFlags.ImplicitPK) && string.Compare(prop.Name, Orm.ImplicitPkName, StringComparison.OrdinalIgnoreCase) == 0); var isAuto = Orm.IsAutoInc(prop) || (IsPK && ((createFlags & CreateFlags.AutoIncPK) == CreateFlags.AutoIncPK)); IsAutoGuid = isAuto && ColumnType == typeof(Guid); IsAutoInc = isAuto && !IsAutoGuid; Indices = Orm.GetIndices(prop); if (!Indices.Any() && !IsPK && ((createFlags & CreateFlags.ImplicitIndex) == CreateFlags.ImplicitIndex) && Name.EndsWith(Orm.ImplicitIndexSuffix, StringComparison.OrdinalIgnoreCase) ) { Indices = new IndexedAttribute[] { new IndexedAttribute() }; } IsNullable = !(IsPK || Orm.IsMarkedNotNull(prop)); MaxStringLength = Orm.MaxStringLength(prop); } public void SetValue(object obj, object val) { _prop.SetValue(obj, val, null); } public object GetValue(object obj) { return _prop.GetGetMethod().Invoke(obj, null); } } } public static class Orm { public const int DefaultMaxStringLength = 140; public const string ImplicitPkName = "Id"; public const string ImplicitIndexSuffix = "Id"; public static string SqlDecl(TableMapping.Column p, bool storeDateTimeAsTicks) { string decl = "\"" + p.Name + "\" " + SqlType(p, storeDateTimeAsTicks) + " "; if (p.IsPK) { decl += "primary key "; } if (p.IsAutoInc) { decl += "autoincrement "; } if (!p.IsNullable) { decl += "not null "; } if (!string.IsNullOrEmpty(p.Collation)) { decl += "collate " + p.Collation + " "; } return decl; } public static string SqlType(TableMapping.Column p, bool storeDateTimeAsTicks) { var clrType = p.ColumnType; if (clrType == typeof(Boolean) || clrType == typeof(Byte) || clrType == typeof(UInt16) || clrType == typeof(SByte) || clrType == typeof(Int16) || clrType == typeof(Int32)) { return "integer"; } else if (clrType == typeof(UInt32) || clrType == typeof(Int64)) { return "bigint"; } else if (clrType == typeof(Single) || clrType == typeof(Double) || clrType == typeof(Decimal)) { return "float"; } else if (clrType == typeof(String)) { int? len = p.MaxStringLength; if (len.HasValue) return "varchar(" + len.Value + ")"; return "varchar"; } else if (clrType == typeof(TimeSpan)) { return "bigint"; } else if (clrType == typeof(DateTime)) { return storeDateTimeAsTicks ? "bigint" : "datetime"; } else if (clrType == typeof(DateTimeOffset)) { return "bigint"; #if !NETFX_CORE } else if (clrType.IsEnum) { #else } else if (clrType.GetTypeInfo().IsEnum) { #endif return "integer"; } else if (clrType == typeof(byte[])) { return "blob"; } else if (clrType == typeof(Guid)) { return "varchar(36)"; } else { throw new NotSupportedException("Don't know about " + clrType); } } public static bool IsPK(MemberInfo p) { var attrs = p.GetCustomAttributes(typeof(PrimaryKeyAttribute), true); #if !NETFX_CORE return attrs.Length > 0; #else return attrs.Count() > 0; #endif } public static string Collation(MemberInfo p) { var attrs = p.GetCustomAttributes(typeof(CollationAttribute), true); #if !NETFX_CORE if (attrs.Length > 0) { return ((CollationAttribute)attrs[0]).Value; #else if (attrs.Count() > 0) { return ((CollationAttribute)attrs.First()).Value; #endif } else { return string.Empty; } } public static bool IsAutoInc(MemberInfo p) { var attrs = p.GetCustomAttributes(typeof(AutoIncrementAttribute), true); #if !NETFX_CORE return attrs.Length > 0; #else return attrs.Count() > 0; #endif } public static IEnumerable<IndexedAttribute> GetIndices(MemberInfo p) { var attrs = p.GetCustomAttributes(typeof(IndexedAttribute), true); return attrs.Cast<IndexedAttribute>(); } public static int? MaxStringLength(PropertyInfo p) { var attrs = p.GetCustomAttributes(typeof(MaxLengthAttribute), true); #if !NETFX_CORE if (attrs.Length > 0) return ((MaxLengthAttribute)attrs[0]).Value; #else if (attrs.Count() > 0) return ((MaxLengthAttribute)attrs.First()).Value; #endif return null; } public static bool IsMarkedNotNull(MemberInfo p) { var attrs = p.GetCustomAttributes(typeof(NotNullAttribute), true); #if !NETFX_CORE return attrs.Length > 0; #else return attrs.Count() > 0; #endif } } public partial class SQLiteCommand { SQLiteConnection _conn; private List<Binding> _bindings; public string CommandText { get; set; } internal SQLiteCommand(SQLiteConnection conn) { _conn = conn; _bindings = new List<Binding>(); CommandText = ""; } public int ExecuteNonQuery() { if (_conn.Trace) { _conn.InvokeTrace("Executing: " + this); } var r = SQLite3.Result.OK; lock (_conn.SyncObject) { var stmt = Prepare(); r = SQLite3.Step(stmt); Finalize(stmt); } if (r == SQLite3.Result.Done) { int rowsAffected = SQLite3.Changes(_conn.Handle); return rowsAffected; } else if (r == SQLite3.Result.Error) { string msg = SQLite3.GetErrmsg(_conn.Handle); throw SQLiteException.New(r, msg); } else if (r == SQLite3.Result.Constraint) { if (SQLite3.ExtendedErrCode(_conn.Handle) == SQLite3.ExtendedResult.ConstraintNotNull) { throw NotNullConstraintViolationException.New(r, SQLite3.GetErrmsg(_conn.Handle)); } } throw SQLiteException.New(r, r.ToString()); } public IEnumerable<T> ExecuteDeferredQuery<T>() { return ExecuteDeferredQuery<T>(_conn.GetMapping(typeof(T))); } public List<T> ExecuteQuery<T>() { return ExecuteDeferredQuery<T>(_conn.GetMapping(typeof(T))).ToList(); } public List<T> ExecuteQuery<T>(TableMapping map) { return ExecuteDeferredQuery<T>(map).ToList(); } /// <summary> /// Invoked every time an instance is loaded from the database. /// </summary> /// <param name='obj'> /// The newly created object. /// </param> /// <remarks> /// This can be overridden in combination with the <see cref="SQLiteConnection.NewCommand"/> /// method to hook into the life-cycle of objects. /// /// Type safety is not possible because MonoTouch does not support virtual generic methods. /// </remarks> protected virtual void OnInstanceCreated(object obj) { // Can be overridden. } public IEnumerable<T> ExecuteDeferredQuery<T>(TableMapping map) { if (_conn.Trace) { _conn.InvokeTrace("Executing Query: " + this); } lock (_conn.SyncObject) { var stmt = Prepare(); try { var cols = new TableMapping.Column[SQLite3.ColumnCount(stmt)]; for (int i = 0; i < cols.Length; i++) { var name = SQLite3.ColumnName16(stmt, i); cols[i] = map.FindColumn(name); } while (SQLite3.Step(stmt) == SQLite3.Result.Row) { var obj = Activator.CreateInstance(map.MappedType); for (int i = 0; i < cols.Length; i++) { if (cols[i] == null) continue; var colType = SQLite3.ColumnType(stmt, i); var val = ReadCol(stmt, i, colType, cols[i].ColumnType); cols[i].SetValue(obj, val); } OnInstanceCreated(obj); yield return (T)obj; } } finally { SQLite3.Finalize(stmt); } } } public T ExecuteScalar<T>() { if (_conn.Trace) { _conn.InvokeTrace("Executing Query: " + this); } T val = default(T); lock (_conn.SyncObject) { var stmt = Prepare(); try { var r = SQLite3.Step(stmt); if (r == SQLite3.Result.Row) { var colType = SQLite3.ColumnType(stmt, 0); val = (T)ReadCol(stmt, 0, colType, typeof(T)); } else if (r == SQLite3.Result.Done) { } else { throw SQLiteException.New(r, SQLite3.GetErrmsg(_conn.Handle)); } } finally { Finalize(stmt); } } return val; } public void Bind(string name, object val) { _bindings.Add(new Binding { Name = name, Value = val }); } public void Bind(object val) { Bind(null, val); } public override string ToString() { var parts = new string[1 + _bindings.Count]; parts[0] = CommandText; var i = 1; foreach (var b in _bindings) { parts[i] = string.Format(" {0}: {1}", i - 1, b.Value); i++; } return string.Join(Environment.NewLine, parts); } Sqlite3Statement Prepare() { var stmt = SQLite3.Prepare2(_conn.Handle, CommandText); BindAll(stmt); return stmt; } void Finalize(Sqlite3Statement stmt) { SQLite3.Finalize(stmt); } void BindAll(Sqlite3Statement stmt) { int nextIdx = 1; foreach (var b in _bindings) { if (b.Name != null) { b.Index = SQLite3.BindParameterIndex(stmt, b.Name); } else { b.Index = nextIdx++; } BindParameter(stmt, b.Index, b.Value, _conn.StoreDateTimeAsTicks); } } internal static IntPtr NegativePointer = new IntPtr(-1); internal static void BindParameter(Sqlite3Statement stmt, int index, object value, bool storeDateTimeAsTicks) { if (value == null) { SQLite3.BindNull(stmt, index); } else { if (value is Int32) { SQLite3.BindInt(stmt, index, (int)value); } else if (value is String) { SQLite3.BindText(stmt, index, (string)value, -1, NegativePointer); } else if (value is Byte || value is UInt16 || value is SByte || value is Int16) { SQLite3.BindInt(stmt, index, Convert.ToInt32(value)); } else if (value is Boolean) { SQLite3.BindInt(stmt, index, (bool)value ? 1 : 0); } else if (value is UInt32 || value is Int64) { SQLite3.BindInt64(stmt, index, Convert.ToInt64(value)); } else if (value is Single || value is Double || value is Decimal) { SQLite3.BindDouble(stmt, index, Convert.ToDouble(value)); } else if (value is TimeSpan) { SQLite3.BindInt64(stmt, index, ((TimeSpan)value).Ticks); } else if (value is DateTime) { if (storeDateTimeAsTicks) { SQLite3.BindInt64(stmt, index, ((DateTime)value).Ticks); } else { SQLite3.BindText(stmt, index, ((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss"), -1, NegativePointer); } } else if (value is DateTimeOffset) { SQLite3.BindInt64(stmt, index, ((DateTimeOffset)value).UtcTicks); #if !NETFX_CORE } else if (value.GetType().IsEnum) { #else } else if (value.GetType().GetTypeInfo().IsEnum) { #endif SQLite3.BindInt(stmt, index, Convert.ToInt32(value)); } else if (value is byte[]) { SQLite3.BindBlob(stmt, index, (byte[])value, ((byte[])value).Length, NegativePointer); } else if (value is Guid) { SQLite3.BindText(stmt, index, ((Guid)value).ToString(), 72, NegativePointer); } else { throw new NotSupportedException("Cannot store type: " + value.GetType()); } } } class Binding { public string Name { get; set; } public object Value { get; set; } public int Index { get; set; } } object ReadCol(Sqlite3Statement stmt, int index, SQLite3.ColType type, Type clrType) { if (type == SQLite3.ColType.Null) { return null; } else { if (clrType == typeof(String)) { return SQLite3.ColumnString(stmt, index); } else if (clrType == typeof(Int32)) { return (int)SQLite3.ColumnInt(stmt, index); } else if (clrType == typeof(Boolean)) { return SQLite3.ColumnInt(stmt, index) == 1; } else if (clrType == typeof(double)) { return SQLite3.ColumnDouble(stmt, index); } else if (clrType == typeof(float)) { return (float)SQLite3.ColumnDouble(stmt, index); } else if (clrType == typeof(TimeSpan)) { return new TimeSpan(SQLite3.ColumnInt64(stmt, index)); } else if (clrType == typeof(DateTime)) { if (_conn.StoreDateTimeAsTicks) { return new DateTime(SQLite3.ColumnInt64(stmt, index)); } else { var text = SQLite3.ColumnString(stmt, index); return DateTime.Parse(text); } } else if (clrType == typeof(DateTimeOffset)) { return new DateTimeOffset(SQLite3.ColumnInt64(stmt, index), TimeSpan.Zero); #if !NETFX_CORE } else if (clrType.IsEnum) { #else } else if (clrType.GetTypeInfo().IsEnum) { #endif return SQLite3.ColumnInt(stmt, index); } else if (clrType == typeof(Int64)) { return SQLite3.ColumnInt64(stmt, index); } else if (clrType == typeof(UInt32)) { return (uint)SQLite3.ColumnInt64(stmt, index); } else if (clrType == typeof(decimal)) { return (decimal)SQLite3.ColumnDouble(stmt, index); } else if (clrType == typeof(Byte)) { return (byte)SQLite3.ColumnInt(stmt, index); } else if (clrType == typeof(UInt16)) { return (ushort)SQLite3.ColumnInt(stmt, index); } else if (clrType == typeof(Int16)) { return (short)SQLite3.ColumnInt(stmt, index); } else if (clrType == typeof(sbyte)) { return (sbyte)SQLite3.ColumnInt(stmt, index); } else if (clrType == typeof(byte[])) { return SQLite3.ColumnByteArray(stmt, index); } else if (clrType == typeof(Guid)) { var text = SQLite3.ColumnString(stmt, index); return new Guid(text); } else { throw new NotSupportedException("Don't know how to read " + clrType); } } } } /// <summary> /// Since the insert never changed, we only need to prepare once. /// </summary> public class PreparedSqlLiteInsertCommand : IDisposable { public bool Initialized { get; set; } protected SQLiteConnection Connection { get; set; } public string CommandText { get; set; } protected Sqlite3Statement Statement { get; set; } internal static readonly Sqlite3Statement NullStatement = default(Sqlite3Statement); internal PreparedSqlLiteInsertCommand(SQLiteConnection conn) { Connection = conn; } public int ExecuteNonQuery(object[] source) { if (Connection.Trace) { Connection.InvokeTrace("Executing: " + CommandText); } var r = SQLite3.Result.OK; if (!Initialized) { Statement = Prepare(); Initialized = true; } //bind the values. if (source != null) { for (int i = 0; i < source.Length; i++) { SQLiteCommand.BindParameter(Statement, i + 1, source[i], Connection.StoreDateTimeAsTicks); } } r = SQLite3.Step(Statement); if (r == SQLite3.Result.Done) { int rowsAffected = SQLite3.Changes(Connection.Handle); SQLite3.Reset(Statement); return rowsAffected; } else if (r == SQLite3.Result.Error) { string msg = SQLite3.GetErrmsg(Connection.Handle); SQLite3.Reset(Statement); throw SQLiteException.New(r, msg); } else if (r == SQLite3.Result.Constraint && SQLite3.ExtendedErrCode(Connection.Handle) == SQLite3.ExtendedResult.ConstraintNotNull) { SQLite3.Reset(Statement); throw NotNullConstraintViolationException.New(r, SQLite3.GetErrmsg(Connection.Handle)); } else { SQLite3.Reset(Statement); throw SQLiteException.New(r, r.ToString()); } } protected virtual Sqlite3Statement Prepare() { var stmt = SQLite3.Prepare2(Connection.Handle, CommandText); return stmt; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if (Statement != NullStatement) { try { SQLite3.Finalize(Statement); } finally { Statement = NullStatement; Connection = null; } } } ~PreparedSqlLiteInsertCommand() { Dispose(false); } } public abstract class BaseTableQuery { protected class Ordering { public string ColumnName { get; set; } public bool Ascending { get; set; } } } public class TableQuery<T> : BaseTableQuery, IEnumerable<T> { public SQLiteConnection Connection { get; private set; } public TableMapping Table { get; private set; } Expression _where; List<Ordering> _orderBys; int? _limit; int? _offset; BaseTableQuery _joinInner; Expression _joinInnerKeySelector; BaseTableQuery _joinOuter; Expression _joinOuterKeySelector; Expression _joinSelector; Expression _selector; TableQuery(SQLiteConnection conn, TableMapping table) { Connection = conn; Table = table; } public TableQuery(SQLiteConnection conn) { Connection = conn; Table = Connection.GetMapping(typeof(T)); } public TableQuery<U> Clone<U>() { var q = new TableQuery<U>(Connection, Table); q._where = _where; q._deferred = _deferred; if (_orderBys != null) { q._orderBys = new List<Ordering>(_orderBys); } q._limit = _limit; q._offset = _offset; q._joinInner = _joinInner; q._joinInnerKeySelector = _joinInnerKeySelector; q._joinOuter = _joinOuter; q._joinOuterKeySelector = _joinOuterKeySelector; q._joinSelector = _joinSelector; q._selector = _selector; return q; } public TableQuery<T> Where(Expression<Func<T, bool>> predExpr) { if (predExpr.NodeType == ExpressionType.Lambda) { var lambda = (LambdaExpression)predExpr; var pred = lambda.Body; var q = Clone<T>(); q.AddWhere(pred); return q; } else { throw new NotSupportedException("Must be a predicate"); } } public TableQuery<T> Take(int n) { var q = Clone<T>(); q._limit = n; return q; } public TableQuery<T> Skip(int n) { var q = Clone<T>(); q._offset = n; return q; } public T ElementAt(int index) { return Skip(index).Take(1).First(); } bool _deferred; public TableQuery<T> Deferred() { var q = Clone<T>(); q._deferred = true; return q; } public TableQuery<T> OrderBy<U>(Expression<Func<T, U>> orderExpr) { return AddOrderBy<U>(orderExpr, true); } public TableQuery<T> OrderByDescending<U>(Expression<Func<T, U>> orderExpr) { return AddOrderBy<U>(orderExpr, false); } public TableQuery<T> ThenBy<U>(Expression<Func<T, U>> orderExpr) { return AddOrderBy<U>(orderExpr, true); } public TableQuery<T> ThenByDescending<U>(Expression<Func<T, U>> orderExpr) { return AddOrderBy<U>(orderExpr, false); } private TableQuery<T> AddOrderBy<U>(Expression<Func<T, U>> orderExpr, bool asc) { if (orderExpr.NodeType == ExpressionType.Lambda) { var lambda = (LambdaExpression)orderExpr; MemberExpression mem = null; var unary = lambda.Body as UnaryExpression; if (unary != null && unary.NodeType == ExpressionType.Convert) { mem = unary.Operand as MemberExpression; } else { mem = lambda.Body as MemberExpression; } if (mem != null && (mem.Expression.NodeType == ExpressionType.Parameter)) { var q = Clone<T>(); if (q._orderBys == null) { q._orderBys = new List<Ordering>(); } q._orderBys.Add(new Ordering { ColumnName = Table.FindColumnWithPropertyName(mem.Member.Name).Name, Ascending = asc }); return q; } else { throw new NotSupportedException("Order By does not support: " + orderExpr); } } else { throw new NotSupportedException("Must be a predicate"); } } private void AddWhere(Expression pred) { if (_where == null) { _where = pred; } else { _where = Expression.AndAlso(_where, pred); } } public TableQuery<TResult> Join<TInner, TKey, TResult>( TableQuery<TInner> inner, Expression<Func<T, TKey>> outerKeySelector, Expression<Func<TInner, TKey>> innerKeySelector, Expression<Func<T, TInner, TResult>> resultSelector) { var q = new TableQuery<TResult>(Connection, Connection.GetMapping(typeof(TResult))) { _joinOuter = this, _joinOuterKeySelector = outerKeySelector, _joinInner = inner, _joinInnerKeySelector = innerKeySelector, _joinSelector = resultSelector, }; return q; } public TableQuery<TResult> Select<TResult>(Expression<Func<T, TResult>> selector) { var q = Clone<TResult>(); q._selector = selector; return q; } private SQLiteCommand GenerateCommand(string selectionList) { if (_joinInner != null && _joinOuter != null) { throw new NotSupportedException("Joins are not supported."); } else { var cmdText = "select " + selectionList + " from \"" + Table.TableName + "\""; var args = new List<object>(); if (_where != null) { var w = CompileExpr(_where, args); cmdText += " where " + w.CommandText; } if ((_orderBys != null) && (_orderBys.Count > 0)) { var t = string.Join(", ", _orderBys.Select(o => "\"" + o.ColumnName + "\"" + (o.Ascending ? "" : " desc")).ToArray()); cmdText += " order by " + t; } if (_limit.HasValue) { cmdText += " limit " + _limit.Value; } if (_offset.HasValue) { if (!_limit.HasValue) { cmdText += " limit -1 "; } cmdText += " offset " + _offset.Value; } return Connection.CreateCommand(cmdText, args.ToArray()); } } class CompileResult { public string CommandText { get; set; } public object Value { get; set; } } private CompileResult CompileExpr(Expression expr, List<object> queryArgs) { if (expr == null) { throw new NotSupportedException("Expression is NULL"); } else if (expr is BinaryExpression) { var bin = (BinaryExpression)expr; var leftr = CompileExpr(bin.Left, queryArgs); var rightr = CompileExpr(bin.Right, queryArgs); //If either side is a parameter and is null, then handle the other side specially (for "is null"/"is not null") string text; if (leftr.CommandText == "?" && leftr.Value == null) text = CompileNullBinaryExpression(bin, rightr); else if (rightr.CommandText == "?" && rightr.Value == null) text = CompileNullBinaryExpression(bin, leftr); else text = "(" + leftr.CommandText + " " + GetSqlName(bin) + " " + rightr.CommandText + ")"; return new CompileResult { CommandText = text }; } else if (expr.NodeType == ExpressionType.Call) { var call = (MethodCallExpression)expr; var args = new CompileResult[call.Arguments.Count]; var obj = call.Object != null ? CompileExpr(call.Object, queryArgs) : null; for (var i = 0; i < args.Length; i++) { args[i] = CompileExpr(call.Arguments[i], queryArgs); } var sqlCall = ""; if (call.Method.Name == "Like" && args.Length == 2) { sqlCall = "(" + args[0].CommandText + " like " + args[1].CommandText + ")"; } else if (call.Method.Name == "Contains" && args.Length == 2) { sqlCall = "(" + args[1].CommandText + " in " + args[0].CommandText + ")"; } else if (call.Method.Name == "Contains" && args.Length == 1) { if (call.Object != null && call.Object.Type == typeof(string)) { sqlCall = "(" + obj.CommandText + " like ('%' || " + args[0].CommandText + " || '%'))"; } else { sqlCall = "(" + args[0].CommandText + " in " + obj.CommandText + ")"; } } else if (call.Method.Name == "StartsWith" && args.Length == 1) { sqlCall = "(" + obj.CommandText + " like (" + args[0].CommandText + " || '%'))"; } else if (call.Method.Name == "EndsWith" && args.Length == 1) { sqlCall = "(" + obj.CommandText + " like ('%' || " + args[0].CommandText + "))"; } else if (call.Method.Name == "Equals" && args.Length == 1) { sqlCall = "(" + obj.CommandText + " = (" + args[0].CommandText + "))"; } else if (call.Method.Name == "ToLower") { sqlCall = "(lower(" + obj.CommandText + "))"; } else if (call.Method.Name == "ToUpper") { sqlCall = "(upper(" + obj.CommandText + "))"; } else { sqlCall = call.Method.Name.ToLower() + "(" + string.Join(",", args.Select(a => a.CommandText).ToArray()) + ")"; } return new CompileResult { CommandText = sqlCall }; } else if (expr.NodeType == ExpressionType.Constant) { var c = (ConstantExpression)expr; queryArgs.Add(c.Value); return new CompileResult { CommandText = "?", Value = c.Value }; } else if (expr.NodeType == ExpressionType.Convert) { var u = (UnaryExpression)expr; var ty = u.Type; var valr = CompileExpr(u.Operand, queryArgs); return new CompileResult { CommandText = valr.CommandText, Value = valr.Value != null ? ConvertTo(valr.Value, ty) : null }; } else if (expr.NodeType == ExpressionType.MemberAccess) { var mem = (MemberExpression)expr; if (mem.Expression != null && mem.Expression.NodeType == ExpressionType.Parameter) { // // This is a column of our table, output just the column name // Need to translate it if that column name is mapped // var columnName = Table.FindColumnWithPropertyName(mem.Member.Name).Name; return new CompileResult { CommandText = "\"" + columnName + "\"" }; } else { object obj = null; if (mem.Expression != null) { var r = CompileExpr(mem.Expression, queryArgs); if (r.Value == null) { throw new NotSupportedException("Member access failed to compile expression"); } if (r.CommandText == "?") { queryArgs.RemoveAt(queryArgs.Count - 1); } obj = r.Value; } // // Get the member value // object val = null; #if !NETFX_CORE if (mem.Member.MemberType == MemberTypes.Property) { #else if (mem.Member is PropertyInfo) { #endif var m = (PropertyInfo)mem.Member; //val = m.GetValue (obj, null); val = m.GetGetMethod().Invoke(obj, null); #if !NETFX_CORE } else if (mem.Member.MemberType == MemberTypes.Field) { #else } else if (mem.Member is FieldInfo) { #endif #if SILVERLIGHT val = Expression.Lambda (expr).Compile ().DynamicInvoke (); #else var m = (FieldInfo)mem.Member; val = m.GetValue(obj); #endif } else { #if !NETFX_CORE throw new NotSupportedException("MemberExpr: " + mem.Member.MemberType); #else throw new NotSupportedException ("MemberExpr: " + mem.Member.DeclaringType); #endif } // // Work special magic for enumerables // if (val != null && val is System.Collections.IEnumerable && !(val is string) && !(val is System.Collections.Generic.IEnumerable<byte>)) { var sb = new System.Text.StringBuilder(); sb.Append("("); var head = ""; foreach (var a in (System.Collections.IEnumerable)val) { queryArgs.Add(a); sb.Append(head); sb.Append("?"); head = ","; } sb.Append(")"); return new CompileResult { CommandText = sb.ToString(), Value = val }; } else { queryArgs.Add(val); return new CompileResult { CommandText = "?", Value = val }; } } } throw new NotSupportedException("Cannot compile: " + expr.NodeType.ToString()); } static object ConvertTo(object obj, Type t) { Type nut = Nullable.GetUnderlyingType(t); if (nut != null) { if (obj == null) return null; return Convert.ChangeType(obj, nut); } else { return Convert.ChangeType(obj, t); } } /// <summary> /// Compiles a BinaryExpression where one of the parameters is null. /// </summary> /// <param name="parameter">The non-null parameter</param> private string CompileNullBinaryExpression(BinaryExpression expression, CompileResult parameter) { if (expression.NodeType == ExpressionType.Equal) return "(" + parameter.CommandText + " is ?)"; else if (expression.NodeType == ExpressionType.NotEqual) return "(" + parameter.CommandText + " is not ?)"; else throw new NotSupportedException("Cannot compile Null-BinaryExpression with type " + expression.NodeType.ToString()); } string GetSqlName(Expression expr) { var n = expr.NodeType; if (n == ExpressionType.GreaterThan) return ">"; else if (n == ExpressionType.GreaterThanOrEqual) { return ">="; } else if (n == ExpressionType.LessThan) { return "<"; } else if (n == ExpressionType.LessThanOrEqual) { return "<="; } else if (n == ExpressionType.And) { return "&"; } else if (n == ExpressionType.AndAlso) { return "and"; } else if (n == ExpressionType.Or) { return "|"; } else if (n == ExpressionType.OrElse) { return "or"; } else if (n == ExpressionType.Equal) { return "="; } else if (n == ExpressionType.NotEqual) { return "!="; } else { throw new NotSupportedException("Cannot get SQL for: " + n); } } public int Count() { return GenerateCommand("count(*)").ExecuteScalar<int>(); } public int Count(Expression<Func<T, bool>> predExpr) { return Where(predExpr).Count(); } public IEnumerator<T> GetEnumerator() { if (!_deferred) return GenerateCommand("*").ExecuteQuery<T>().GetEnumerator(); return GenerateCommand("*").ExecuteDeferredQuery<T>().GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } public T First() { var query = Take(1); return query.ToList<T>().First(); } public T FirstOrDefault() { var query = Take(1); return query.ToList<T>().FirstOrDefault(); } } public static class SQLite3 { public enum Result : int { OK = 0, Error = 1, Internal = 2, Perm = 3, Abort = 4, Busy = 5, Locked = 6, NoMem = 7, ReadOnly = 8, Interrupt = 9, IOError = 10, Corrupt = 11, NotFound = 12, Full = 13, CannotOpen = 14, LockErr = 15, Empty = 16, SchemaChngd = 17, TooBig = 18, Constraint = 19, Mismatch = 20, Misuse = 21, NotImplementedLFS = 22, AccessDenied = 23, Format = 24, Range = 25, NonDBFile = 26, Notice = 27, Warning = 28, Row = 100, Done = 101 } public enum ExtendedResult : int { IOErrorRead = (Result.IOError | (1 << 8)), IOErrorShortRead = (Result.IOError | (2 << 8)), IOErrorWrite = (Result.IOError | (3 << 8)), IOErrorFsync = (Result.IOError | (4 << 8)), IOErrorDirFSync = (Result.IOError | (5 << 8)), IOErrorTruncate = (Result.IOError | (6 << 8)), IOErrorFStat = (Result.IOError | (7 << 8)), IOErrorUnlock = (Result.IOError | (8 << 8)), IOErrorRdlock = (Result.IOError | (9 << 8)), IOErrorDelete = (Result.IOError | (10 << 8)), IOErrorBlocked = (Result.IOError | (11 << 8)), IOErrorNoMem = (Result.IOError | (12 << 8)), IOErrorAccess = (Result.IOError | (13 << 8)), IOErrorCheckReservedLock = (Result.IOError | (14 << 8)), IOErrorLock = (Result.IOError | (15 << 8)), IOErrorClose = (Result.IOError | (16 << 8)), IOErrorDirClose = (Result.IOError | (17 << 8)), IOErrorSHMOpen = (Result.IOError | (18 << 8)), IOErrorSHMSize = (Result.IOError | (19 << 8)), IOErrorSHMLock = (Result.IOError | (20 << 8)), IOErrorSHMMap = (Result.IOError | (21 << 8)), IOErrorSeek = (Result.IOError | (22 << 8)), IOErrorDeleteNoEnt = (Result.IOError | (23 << 8)), IOErrorMMap = (Result.IOError | (24 << 8)), LockedSharedcache = (Result.Locked | (1 << 8)), BusyRecovery = (Result.Busy | (1 << 8)), CannottOpenNoTempDir = (Result.CannotOpen | (1 << 8)), CannotOpenIsDir = (Result.CannotOpen | (2 << 8)), CannotOpenFullPath = (Result.CannotOpen | (3 << 8)), CorruptVTab = (Result.Corrupt | (1 << 8)), ReadonlyRecovery = (Result.ReadOnly | (1 << 8)), ReadonlyCannotLock = (Result.ReadOnly | (2 << 8)), ReadonlyRollback = (Result.ReadOnly | (3 << 8)), AbortRollback = (Result.Abort | (2 << 8)), ConstraintCheck = (Result.Constraint | (1 << 8)), ConstraintCommitHook = (Result.Constraint | (2 << 8)), ConstraintForeignKey = (Result.Constraint | (3 << 8)), ConstraintFunction = (Result.Constraint | (4 << 8)), ConstraintNotNull = (Result.Constraint | (5 << 8)), ConstraintPrimaryKey = (Result.Constraint | (6 << 8)), ConstraintTrigger = (Result.Constraint | (7 << 8)), ConstraintUnique = (Result.Constraint | (8 << 8)), ConstraintVTab = (Result.Constraint | (9 << 8)), NoticeRecoverWAL = (Result.Notice | (1 << 8)), NoticeRecoverRollback = (Result.Notice | (2 << 8)) } public enum ConfigOption : int { SingleThread = 1, MultiThread = 2, Serialized = 3 } #if !USE_CSHARP_SQLITE && !USE_WP8_NATIVE_SQLITE [DllImport("sqlite3", EntryPoint = "sqlite3_open", CallingConvention = CallingConvention.Cdecl)] public static extern Result Open([MarshalAs(UnmanagedType.LPStr)] string filename, out IntPtr db); [DllImport("sqlite3", EntryPoint = "sqlite3_open_v2", CallingConvention = CallingConvention.Cdecl)] public static extern Result Open([MarshalAs(UnmanagedType.LPStr)] string filename, out IntPtr db, int flags, IntPtr zvfs); [DllImport("sqlite3", EntryPoint = "sqlite3_open_v2", CallingConvention = CallingConvention.Cdecl)] public static extern Result Open(byte[] filename, out IntPtr db, int flags, IntPtr zvfs); [DllImport("sqlite3", EntryPoint = "sqlite3_open16", CallingConvention = CallingConvention.Cdecl)] public static extern Result Open16([MarshalAs(UnmanagedType.LPWStr)] string filename, out IntPtr db); [DllImport("sqlite3", EntryPoint = "sqlite3_enable_load_extension", CallingConvention = CallingConvention.Cdecl)] public static extern Result EnableLoadExtension(IntPtr db, int onoff); [DllImport("sqlite3", EntryPoint = "sqlite3_close", CallingConvention = CallingConvention.Cdecl)] public static extern Result Close(IntPtr db); [DllImport("sqlite3", EntryPoint = "sqlite3_initialize", CallingConvention = CallingConvention.Cdecl)] public static extern Result Initialize(); [DllImport("sqlite3", EntryPoint = "sqlite3_shutdown", CallingConvention = CallingConvention.Cdecl)] public static extern Result Shutdown(); [DllImport("sqlite3", EntryPoint = "sqlite3_config", CallingConvention = CallingConvention.Cdecl)] public static extern Result Config(ConfigOption option); [DllImport("sqlite3", EntryPoint = "sqlite3_win32_set_directory", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)] public static extern int SetDirectory(uint directoryType, string directoryPath); [DllImport("sqlite3", EntryPoint = "sqlite3_busy_timeout", CallingConvention = CallingConvention.Cdecl)] public static extern Result BusyTimeout(IntPtr db, int milliseconds); [DllImport("sqlite3", EntryPoint = "sqlite3_changes", CallingConvention = CallingConvention.Cdecl)] public static extern int Changes(IntPtr db); [DllImport("sqlite3", EntryPoint = "sqlite3_prepare_v2", CallingConvention = CallingConvention.Cdecl)] public static extern Result Prepare2(IntPtr db, [MarshalAs(UnmanagedType.LPStr)] string sql, int numBytes, out IntPtr stmt, IntPtr pzTail); #if NETFX_CORE [DllImport ("sqlite3", EntryPoint = "sqlite3_prepare_v2", CallingConvention = CallingConvention.Cdecl)] public static extern Result Prepare2 (IntPtr db, byte[] queryBytes, int numBytes, out IntPtr stmt, IntPtr pzTail); #endif public static IntPtr Prepare2(IntPtr db, string query) { IntPtr stmt; #if NETFX_CORE byte[] queryBytes = System.Text.UTF8Encoding.UTF8.GetBytes (query); var r = Prepare2 (db, queryBytes, queryBytes.Length, out stmt, IntPtr.Zero); #else var r = Prepare2(db, query, System.Text.UTF8Encoding.UTF8.GetByteCount(query), out stmt, IntPtr.Zero); #endif if (r != Result.OK) { throw SQLiteException.New(r, GetErrmsg(db)); } return stmt; } [DllImport("sqlite3", EntryPoint = "sqlite3_step", CallingConvention = CallingConvention.Cdecl)] public static extern Result Step(IntPtr stmt); [DllImport("sqlite3", EntryPoint = "sqlite3_reset", CallingConvention = CallingConvention.Cdecl)] public static extern Result Reset(IntPtr stmt); [DllImport("sqlite3", EntryPoint = "sqlite3_finalize", CallingConvention = CallingConvention.Cdecl)] public static extern Result Finalize(IntPtr stmt); [DllImport("sqlite3", EntryPoint = "sqlite3_last_insert_rowid", CallingConvention = CallingConvention.Cdecl)] public static extern long LastInsertRowid(IntPtr db); [DllImport("sqlite3", EntryPoint = "sqlite3_errmsg16", CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr Errmsg(IntPtr db); public static string GetErrmsg(IntPtr db) { return Marshal.PtrToStringUni(Errmsg(db)); } [DllImport("sqlite3", EntryPoint = "sqlite3_bind_parameter_index", CallingConvention = CallingConvention.Cdecl)] public static extern int BindParameterIndex(IntPtr stmt, [MarshalAs(UnmanagedType.LPStr)] string name); [DllImport("sqlite3", EntryPoint = "sqlite3_bind_null", CallingConvention = CallingConvention.Cdecl)] public static extern int BindNull(IntPtr stmt, int index); [DllImport("sqlite3", EntryPoint = "sqlite3_bind_int", CallingConvention = CallingConvention.Cdecl)] public static extern int BindInt(IntPtr stmt, int index, int val); [DllImport("sqlite3", EntryPoint = "sqlite3_bind_int64", CallingConvention = CallingConvention.Cdecl)] public static extern int BindInt64(IntPtr stmt, int index, long val); [DllImport("sqlite3", EntryPoint = "sqlite3_bind_double", CallingConvention = CallingConvention.Cdecl)] public static extern int BindDouble(IntPtr stmt, int index, double val); [DllImport("sqlite3", EntryPoint = "sqlite3_bind_text16", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)] public static extern int BindText(IntPtr stmt, int index, [MarshalAs(UnmanagedType.LPWStr)] string val, int n, IntPtr free); [DllImport("sqlite3", EntryPoint = "sqlite3_bind_blob", CallingConvention = CallingConvention.Cdecl)] public static extern int BindBlob(IntPtr stmt, int index, byte[] val, int n, IntPtr free); [DllImport("sqlite3", EntryPoint = "sqlite3_column_count", CallingConvention = CallingConvention.Cdecl)] public static extern int ColumnCount(IntPtr stmt); [DllImport("sqlite3", EntryPoint = "sqlite3_column_name", CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr ColumnName(IntPtr stmt, int index); [DllImport("sqlite3", EntryPoint = "sqlite3_column_name16", CallingConvention = CallingConvention.Cdecl)] static extern IntPtr ColumnName16Internal(IntPtr stmt, int index); public static string ColumnName16(IntPtr stmt, int index) { return Marshal.PtrToStringUni(ColumnName16Internal(stmt, index)); } [DllImport("sqlite3", EntryPoint = "sqlite3_column_type", CallingConvention = CallingConvention.Cdecl)] public static extern ColType ColumnType(IntPtr stmt, int index); [DllImport("sqlite3", EntryPoint = "sqlite3_column_int", CallingConvention = CallingConvention.Cdecl)] public static extern int ColumnInt(IntPtr stmt, int index); [DllImport("sqlite3", EntryPoint = "sqlite3_column_int64", CallingConvention = CallingConvention.Cdecl)] public static extern long ColumnInt64(IntPtr stmt, int index); [DllImport("sqlite3", EntryPoint = "sqlite3_column_double", CallingConvention = CallingConvention.Cdecl)] public static extern double ColumnDouble(IntPtr stmt, int index); [DllImport("sqlite3", EntryPoint = "sqlite3_column_text", CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr ColumnText(IntPtr stmt, int index); [DllImport("sqlite3", EntryPoint = "sqlite3_column_text16", CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr ColumnText16(IntPtr stmt, int index); [DllImport("sqlite3", EntryPoint = "sqlite3_column_blob", CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr ColumnBlob(IntPtr stmt, int index); [DllImport("sqlite3", EntryPoint = "sqlite3_column_bytes", CallingConvention = CallingConvention.Cdecl)] public static extern int ColumnBytes(IntPtr stmt, int index); public static string ColumnString(IntPtr stmt, int index) { return Marshal.PtrToStringUni(SQLite3.ColumnText16(stmt, index)); } public static byte[] ColumnByteArray(IntPtr stmt, int index) { int length = ColumnBytes(stmt, index); var result = new byte[length]; if (length > 0) Marshal.Copy(ColumnBlob(stmt, index), result, 0, length); return result; } [DllImport("sqlite3", EntryPoint = "sqlite3_extended_errcode", CallingConvention = CallingConvention.Cdecl)] public static extern ExtendedResult ExtendedErrCode(IntPtr db); [DllImport("sqlite3", EntryPoint = "sqlite3_libversion_number", CallingConvention = CallingConvention.Cdecl)] public static extern int LibVersionNumber(); #else public static Result Open(string filename, out Sqlite3DatabaseHandle db) { return (Result) Sqlite3.sqlite3_open(filename, out db); } public static Result Open(string filename, out Sqlite3DatabaseHandle db, int flags, IntPtr zVfs) { #if USE_WP8_NATIVE_SQLITE return (Result)Sqlite3.sqlite3_open_v2(filename, out db, flags, ""); #else return (Result)Sqlite3.sqlite3_open_v2(filename, out db, flags, null); #endif } public static Result Close(Sqlite3DatabaseHandle db) { return (Result)Sqlite3.sqlite3_close(db); } public static Result BusyTimeout(Sqlite3DatabaseHandle db, int milliseconds) { return (Result)Sqlite3.sqlite3_busy_timeout(db, milliseconds); } public static int Changes(Sqlite3DatabaseHandle db) { return Sqlite3.sqlite3_changes(db); } public static Sqlite3Statement Prepare2(Sqlite3DatabaseHandle db, string query) { Sqlite3Statement stmt = default(Sqlite3Statement); #if USE_WP8_NATIVE_SQLITE var r = Sqlite3.sqlite3_prepare_v2(db, query, out stmt); #else stmt = new Sqlite3Statement(); var r = Sqlite3.sqlite3_prepare_v2(db, query, -1, ref stmt, 0); #endif if (r != 0) { throw SQLiteException.New((Result)r, GetErrmsg(db)); } return stmt; } public static Result Step(Sqlite3Statement stmt) { return (Result)Sqlite3.sqlite3_step(stmt); } public static Result Reset(Sqlite3Statement stmt) { return (Result)Sqlite3.sqlite3_reset(stmt); } public static Result Finalize(Sqlite3Statement stmt) { return (Result)Sqlite3.sqlite3_finalize(stmt); } public static long LastInsertRowid(Sqlite3DatabaseHandle db) { return Sqlite3.sqlite3_last_insert_rowid(db); } public static string GetErrmsg(Sqlite3DatabaseHandle db) { return Sqlite3.sqlite3_errmsg(db); } public static int BindParameterIndex(Sqlite3Statement stmt, string name) { return Sqlite3.sqlite3_bind_parameter_index(stmt, name); } public static int BindNull(Sqlite3Statement stmt, int index) { return Sqlite3.sqlite3_bind_null(stmt, index); } public static int BindInt(Sqlite3Statement stmt, int index, int val) { return Sqlite3.sqlite3_bind_int(stmt, index, val); } public static int BindInt64(Sqlite3Statement stmt, int index, long val) { return Sqlite3.sqlite3_bind_int64(stmt, index, val); } public static int BindDouble(Sqlite3Statement stmt, int index, double val) { return Sqlite3.sqlite3_bind_double(stmt, index, val); } public static int BindText(Sqlite3Statement stmt, int index, string val, int n, IntPtr free) { #if USE_WP8_NATIVE_SQLITE return Sqlite3.sqlite3_bind_text(stmt, index, val, n); #else return Sqlite3.sqlite3_bind_text(stmt, index, val, n, null); #endif } public static int BindBlob(Sqlite3Statement stmt, int index, byte[] val, int n, IntPtr free) { #if USE_WP8_NATIVE_SQLITE return Sqlite3.sqlite3_bind_blob(stmt, index, val, n); #else return Sqlite3.sqlite3_bind_blob(stmt, index, val, n, null); #endif } public static int ColumnCount(Sqlite3Statement stmt) { return Sqlite3.sqlite3_column_count(stmt); } public static string ColumnName(Sqlite3Statement stmt, int index) { return Sqlite3.sqlite3_column_name(stmt, index); } public static string ColumnName16(Sqlite3Statement stmt, int index) { return Sqlite3.sqlite3_column_name(stmt, index); } public static ColType ColumnType(Sqlite3Statement stmt, int index) { return (ColType)Sqlite3.sqlite3_column_type(stmt, index); } public static int ColumnInt(Sqlite3Statement stmt, int index) { return Sqlite3.sqlite3_column_int(stmt, index); } public static long ColumnInt64(Sqlite3Statement stmt, int index) { return Sqlite3.sqlite3_column_int64(stmt, index); } public static double ColumnDouble(Sqlite3Statement stmt, int index) { return Sqlite3.sqlite3_column_double(stmt, index); } public static string ColumnText(Sqlite3Statement stmt, int index) { return Sqlite3.sqlite3_column_text(stmt, index); } public static string ColumnText16(Sqlite3Statement stmt, int index) { return Sqlite3.sqlite3_column_text(stmt, index); } public static byte[] ColumnBlob(Sqlite3Statement stmt, int index) { return Sqlite3.sqlite3_column_blob(stmt, index); } public static int ColumnBytes(Sqlite3Statement stmt, int index) { return Sqlite3.sqlite3_column_bytes(stmt, index); } public static string ColumnString(Sqlite3Statement stmt, int index) { return Sqlite3.sqlite3_column_text(stmt, index); } public static byte[] ColumnByteArray(Sqlite3Statement stmt, int index) { return ColumnBlob(stmt, index); } public static Result EnableLoadExtension(Sqlite3DatabaseHandle db, int onoff) { return (Result)Sqlite3.sqlite3_enable_load_extension(db, onoff); } public static ExtendedResult ExtendedErrCode(Sqlite3DatabaseHandle db) { return (ExtendedResult)Sqlite3.sqlite3_extended_errcode(db); } #endif public enum ColType : int { Integer = 1, Float = 2, Text = 3, Blob = 4, Null = 5 } } }
37.517293
231
0.546539
[ "BSD-2-Clause" ]
Megapop/Norad-Eduapp4syria
Antura/EA4S_Antura_U3D/Assets/_app/_scripts/Database/SQLite/SQLite.cs
124,745
C#
// *********************************************************************** // Assembly : Noob.Core // Author : Administrator // Created : 2020-04-19 // // Last Modified By : Administrator // Last Modified On : 2020-04-19 // *********************************************************************** // <copyright file="UnitOfWorkInterceptor.cs" company="Noob.Core"> // Copyright (c) . All rights reserved. // </copyright> // <summary></summary> // *********************************************************************** using System; using System.Threading.Tasks; using JetBrains.Annotations; using Microsoft.Extensions.Options; using Noob.DependencyInjection; using Noob.DynamicProxy; namespace Noob.Uow { /// <summary> /// Class UnitOfWorkInterceptor. /// Implements the <see cref="Noob.DynamicProxy.Interceptor" /> /// Implements the <see cref="Noob.DependencyInjection.ITransientDependency" /> /// </summary> /// <seealso cref="Noob.DynamicProxy.Interceptor" /> /// <seealso cref="Noob.DependencyInjection.ITransientDependency" /> public class UnitOfWorkInterceptor :Interceptor, ITransientDependency { /// <summary> /// The unit of work manager /// </summary> private readonly IUnitOfWorkManager _unitOfWorkManager; /// <summary> /// The default options /// </summary> private readonly UnitOfWorkDefaultOptions _defaultOptions; /// <summary> /// Initializes a new instance of the <see cref="UnitOfWorkInterceptor"/> class. /// </summary> /// <param name="unitOfWorkManager">The unit of work manager.</param> /// <param name="options">The options.</param> public UnitOfWorkInterceptor(IUnitOfWorkManager unitOfWorkManager, IOptions<UnitOfWorkDefaultOptions> options) { _unitOfWorkManager = unitOfWorkManager; _defaultOptions = options.Value; } /// <summary> /// intercept as an asynchronous operation. /// </summary> /// <param name="invocation">The invocation.</param> /// <returns>Task.</returns> public override async Task InterceptAsync(IMethodInvocation invocation) { if (!UnitOfWorkHelper.IsUnitOfWorkMethod(invocation.Method, out var unitOfWorkAttribute)) { await invocation.ProceedAsync(); return; } using (var uow = _unitOfWorkManager.Begin(CreateOptions(invocation, unitOfWorkAttribute))) { await invocation.ProceedAsync(); await uow.CompleteAsync(); } } /// <summary> /// Creates the options. /// </summary> /// <param name="invocation">The invocation.</param> /// <param name="unitOfWorkAttribute">The unit of work attribute.</param> /// <returns>UnitOfWorkOptions.</returns> private UnitOfWorkOptions CreateOptions(IMethodInvocation invocation, [CanBeNull] UnitOfWorkAttribute unitOfWorkAttribute) { var options = new UnitOfWorkOptions(); unitOfWorkAttribute?.SetOptions(options); if (unitOfWorkAttribute?.IsTransactional == null) { options.IsTransactional = _defaultOptions.CalculateIsTransactional( autoValue: !invocation.Method.Name.StartsWith("Get", StringComparison.InvariantCultureIgnoreCase) ); } return options; } } }
37.557895
130
0.58352
[ "MIT" ]
noobwu/DncZeus
Noob.Core/Uow/UnitOfWorkInterceptor.cs
3,570
C#
#region Copyright notice and license // Copyright 2019 The gRPC Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using Grpc.Core; namespace Grpc.Tests.Shared { public class TestServerCallContext : ServerCallContext { public TestServerCallContext(DateTime deadline, CancellationToken cancellationToken) { DeadlineCore = deadline; CancellationTokenCore = cancellationToken; MethodCore = "TestMethod"; HostCore = "test"; PeerCore = "unknown"; RequestHeadersCore = Metadata.Empty; ResponseTrailersCore = Metadata.Empty; // TODO(JamesNK): Remove nullable override after Grpc.Core.Api update #pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. AuthContextCore = new AuthContext(null, new Dictionary<string, List<AuthProperty>>()); #pragma warning restore CS8625 // Cannot convert null literal to non-nullable reference type. } protected override string MethodCore { get; } protected override string HostCore { get; } protected override string PeerCore { get; } protected override DateTime DeadlineCore { get; } protected override Metadata RequestHeadersCore { get; } protected override CancellationToken CancellationTokenCore { get; } protected override Metadata ResponseTrailersCore { get; } protected override Status StatusCore { get; set; } // TODO(JamesNK): Remove nullable override after Grpc.Core.Api update #pragma warning disable CS8764 // Nullability of return type doesn't match overridden member (possibly because of nullability attributes). protected override WriteOptions? WriteOptionsCore { get; set; } #pragma warning restore CS8764 // Nullability of return type doesn't match overridden member (possibly because of nullability attributes). protected override AuthContext AuthContextCore { get; } protected override ContextPropagationToken CreatePropagationTokenCore(ContextPropagationOptions? options) { throw new NotImplementedException(); } protected override Task WriteResponseHeadersAsyncCore(Metadata responseHeaders) { throw new NotImplementedException(); } } }
44
138
0.712587
[ "Apache-2.0" ]
LaudateCorpus1/grpc-dotnet
test/Shared/TestServerCallContext.cs
2,862
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ExportFactoryImporter.cs" company="Kephas Software SRL"> // Copyright (c) Kephas Software SRL. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> // <summary> // Implements the export factory importer class. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Kephas.Composition.ExportFactoryImporters { using Kephas.Composition; /// <summary> /// Service importing an export factory with metadata. /// </summary> /// <typeparam name="TService">Type of the service.</typeparam> /// <typeparam name="TMetadata">Type of the metadata.</typeparam> public class ExportFactoryImporter<TService, TMetadata> : IExportFactoryImporter<TService, TMetadata> { /// <summary> /// Initializes a new instance of the <see cref="ExportFactoryImporter{TService,TMetadata}"/> class. /// </summary> /// <param name="exportFactory">The export factory.</param> public ExportFactoryImporter(IExportFactory<TService, TMetadata> exportFactory) { this.ExportFactory = exportFactory; } /// <summary> /// Gets the export factory. /// </summary> /// <value> /// The export factory. /// </value> public IExportFactory<TService, TMetadata> ExportFactory { get; } /// <summary> /// Gets the export factory. /// </summary> object IExportFactoryImporter.ExportFactory => this.ExportFactory; } /// <summary> /// Service importing an export factory. /// </summary> /// <typeparam name="TService">Type of the service.</typeparam> public class ExportFactoryImporter<TService> : IExportFactoryImporter<TService> { /// <summary> /// Initializes a new instance of the <see cref="ExportFactoryImporter{TService}"/> class. /// </summary> /// <param name="exportFactory">The export factory.</param> public ExportFactoryImporter(IExportFactory<TService> exportFactory) { this.ExportFactory = exportFactory; } /// <summary> /// Gets the export factory. /// </summary> /// <value> /// The export factory. /// </value> public IExportFactory<TService> ExportFactory { get; } /// <summary> /// Gets the export factory. /// </summary> object IExportFactoryImporter.ExportFactory => this.ExportFactory; } }
37.849315
120
0.568947
[ "MIT" ]
snakefoot/kephas
src/Kephas.Core/Composition/ExportFactoryImporters/ExportFactoryImporter.cs
2,765
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Azure.Core; namespace Azure.Messaging.EventHubs.Processor { /// <summary> /// Receives <see cref="EventData" /> as they are available for a partition, in the context of a consumer group, and routes /// them to a partition processor instance to be processed. /// </summary> /// /// <typeparam name="T">The type of partition processor used by this instance by default; the type must be derived from <see cref="BasePartitionProcessor" /> and must have a parameterless constructor.</typeparam> /// public class EventProcessor<T> where T : BasePartitionProcessor, new() { /// <summary>The seed to use for initializing random number generated for a given thread-specific instance.</summary> private static int s_randomSeed = Environment.TickCount; /// <summary>The random number generator to use for a specific thread.</summary> private static readonly ThreadLocal<Random> s_randomNumberGenerator = new ThreadLocal<Random>(() => new Random(Interlocked.Increment(ref s_randomSeed)), false); /// <summary>The primitive for synchronizing access during start and close operations.</summary> private readonly SemaphoreSlim _runningTaskSemaphore = new SemaphoreSlim(1, 1); /// <summary> /// The minimum amount of time to be elapsed between two load balancing verifications. /// </summary> /// protected virtual TimeSpan LoadBalanceUpdate => TimeSpan.FromSeconds(10); /// <summary> /// The minimum amount of time for an ownership to be considered expired without further updates. /// </summary> /// protected virtual TimeSpan OwnershipExpiration => TimeSpan.FromSeconds(30); /// <summary> /// A unique name used to identify this event processor. /// </summary> /// public virtual string Identifier { get; } /// <summary> /// The client used to interact with the Azure Event Hubs service. /// </summary> /// private EventHubClient InnerClient { get; } /// <summary> /// The name of the consumer group this event processor is associated with. Events will be /// read only in the context of this group. /// </summary> /// private string ConsumerGroup { get; } /// <summary> /// A factory used to create partition processors. /// </summary> /// private Func<PartitionContext, BasePartitionProcessor> PartitionProcessorFactory { get; } /// <summary> /// Interacts with the storage system with responsibility for creation of checkpoints and for ownership claim. /// </summary> /// private PartitionManager Manager { get; } /// <summary> /// The set of options to use for this event processor. /// </summary> /// private EventProcessorOptions Options { get; } /// <summary> /// A <see cref="CancellationTokenSource"/> instance to signal the request to cancel the current running task. /// </summary> /// private CancellationTokenSource RunningTaskTokenSource { get; set; } /// <summary> /// The set of partition pumps used by this event processor. Partition ids are used as keys. /// </summary> /// private ConcurrentDictionary<string, PartitionPump> PartitionPumps { get; } /// <summary> /// The set of partition ownership this event processor owns. Partition ids are used as keys. /// </summary> /// private Dictionary<string, PartitionOwnership> InstanceOwnership { get; set; } /// <summary> /// The running task responsible for performing partition load balancing between multiple <see cref="EventProcessor{T}" /> /// instances, as well as managing partition pumps and ownership. /// </summary> /// private Task RunningTask { get; set; } /// <summary> /// Initializes a new instance of the <see cref="EventProcessor{T}"/> class. /// </summary> /// /// <param name="consumerGroup">The name of the consumer group this event processor is associated with. Events are read in the context of this group.</param> /// <param name="eventHubClient">The client used to interact with the Azure Event Hubs service.</param> /// <param name="partitionManager">Interacts with the storage system with responsibility for creation of checkpoints and for ownership claim.</param> /// <param name="options">The set of options to use for this event processor.</param> /// /// <remarks> /// Ownership of the <paramref name="eventHubClient" /> is assumed to be responsibility of the caller; this /// processor will delegate operations to it, but will not perform any clean-up tasks, such as closing or /// disposing of the instance. /// </remarks> /// public EventProcessor(string consumerGroup, EventHubClient eventHubClient, PartitionManager partitionManager, EventProcessorOptions options = default) : this(consumerGroup, eventHubClient, partitionContext => new T(), partitionManager, options) { } /// <summary> /// Initializes a new instance of the <see cref="EventProcessor{T}"/> class. /// </summary> /// /// <param name="consumerGroup">The name of the consumer group this event processor is associated with. Events are read in the context of this group.</param> /// <param name="eventHubClient">The client used to interact with the Azure Event Hubs service.</param> /// <param name="partitionProcessorFactory">Creates a partition processor instance for the associated <see cref="PartitionContext" />.</param> /// <param name="partitionManager">Interacts with the storage system with responsibility for creation of checkpoints and for ownership claim.</param> /// <param name="options">The set of options to use for this event processor.</param> /// /// <remarks> /// Ownership of the <paramref name="eventHubClient" /> is assumed to be responsibility of the caller; this /// processor will delegate operations to it, but will not perform any clean-up tasks, such as closing or /// disposing of the instance. /// </remarks> /// public EventProcessor(string consumerGroup, EventHubClient eventHubClient, Func<PartitionContext, BasePartitionProcessor> partitionProcessorFactory, PartitionManager partitionManager, EventProcessorOptions options = default) { Argument.AssertNotNullOrEmpty(consumerGroup, nameof(consumerGroup)); Argument.AssertNotNull(eventHubClient, nameof(eventHubClient)); Argument.AssertNotNull(partitionProcessorFactory, nameof(partitionProcessorFactory)); Argument.AssertNotNull(partitionManager, nameof(partitionManager)); InnerClient = eventHubClient; ConsumerGroup = consumerGroup; PartitionProcessorFactory = partitionProcessorFactory; Manager = partitionManager; Options = options?.Clone() ?? new EventProcessorOptions(); Identifier = Guid.NewGuid().ToString(); PartitionPumps = new ConcurrentDictionary<string, PartitionPump>(); } /// <summary> /// Initializes a new instance of the <see cref="EventProcessor{T}"/> class. /// </summary> /// protected EventProcessor() { } /// <summary> /// Starts the event processor. In case it's already running, nothing happens. /// </summary> /// /// <returns>A task to be resolved on when the operation has completed.</returns> /// public virtual async Task StartAsync() { if (RunningTask == null) { await _runningTaskSemaphore.WaitAsync().ConfigureAwait(false); try { if (RunningTask == null) { // We expect the token source to be null, but we are playing safe. RunningTaskTokenSource?.Cancel(); RunningTaskTokenSource = new CancellationTokenSource(); // Initialize our empty ownership dictionary. InstanceOwnership = new Dictionary<string, PartitionOwnership>(); // Start the main running task. It is resposible for managing the partition pumps and for partition // load balancing among multiple event processor instances. RunningTask = RunAsync(RunningTaskTokenSource.Token); } } finally { _runningTaskSemaphore.Release(); } } } /// <summary> /// Stops the event processor. In case it isn't running, nothing happens. /// </summary> /// /// <returns>A task to be resolved on when the operation has completed.</returns> /// public virtual async Task StopAsync() { if (RunningTask != null) { await _runningTaskSemaphore.WaitAsync().ConfigureAwait(false); try { if (RunningTask != null) { // Cancel the current running task. RunningTaskTokenSource.Cancel(); RunningTaskTokenSource = null; // Now that a cancellation request has been issued, wait for the running task to finish. In case something // unexpected happened and it stopped working midway, this is the moment we expect to catch an exception. try { await RunningTask.ConfigureAwait(false); } catch (TaskCanceledException) { // The running task has an inner delay that is likely to throw a TaskCanceledException upon token cancellation. // The task might end up leaving its main loop gracefully by chance, so we won't necessarily reach this part of // the code. } catch (Exception) { // TODO: delegate the exception handling to an Exception Callback. } RunningTask = null; // Now that the task has finished, clean up what is left. Stop and remove every partition pump that is still // running and dispose of our ownership dictionary. InstanceOwnership = null; await Task.WhenAll(PartitionPumps.Keys .Select(partitionId => RemovePartitionPumpIfItExistsAsync(partitionId, PartitionProcessorCloseReason.Shutdown))) .ConfigureAwait(false); } } finally { _runningTaskSemaphore.Release(); } } } /// <summary> /// Performs load balancing between multiple <see cref="EventProcessor{T}" /> instances, claiming others' partitions to enforce /// a more equal distribution when necessary. It also manages its own partition pumps and ownership. /// </summary> /// /// <param name="cancellationToken">A <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param> /// /// <returns>A task to be resolved on when the operation has completed.</returns> /// private async Task RunAsync(CancellationToken cancellationToken) { while (!cancellationToken.IsCancellationRequested) { Stopwatch cycleDuration = Stopwatch.StartNew(); // Renew this instance's ownership so they don't expire. await RenewOwnershipAsync().ConfigureAwait(false); // From the storage service provided by the user, obtain a complete list of ownership, including expired ones. We may still need // their eTags to claim orphan partitions. var completeOwnershipList = (await Manager .ListOwnershipAsync(InnerClient.FullyQualifiedNamespace, InnerClient.EventHubName, ConsumerGroup) .ConfigureAwait(false)) .ToList(); // Filter the complete ownership list to obtain only the ones that are still active. The expiration time defaults to 30 seconds, // but it may be overriden by a derived class. IEnumerable<PartitionOwnership> activeOwnership = completeOwnershipList .Where(ownership => DateTimeOffset.UtcNow.Subtract(ownership.LastModifiedTime.Value) < OwnershipExpiration); // Dispose of all previous partition ownership instances and get a whole new dictionary. InstanceOwnership = activeOwnership .Where(ownership => ownership.OwnerIdentifier == Identifier) .ToDictionary(ownership => ownership.PartitionId); // Some previously owned partitions might have had their ownership expired or might have been stolen, so we need to stop // the pumps we don't need anymore. await Task.WhenAll(PartitionPumps.Keys .Except(InstanceOwnership.Keys) .Select(partitionId => RemovePartitionPumpIfItExistsAsync(partitionId, PartitionProcessorCloseReason.OwnershipLost))) .ConfigureAwait(false); // Now that we are left with pumps that should be running, check their status. If any has stopped, it means an // unexpected failure has happened, so try closing it and starting a new one. In case we don't have a pump that // should exist, create it. This might happen when pump creation has failed in a previous cycle. await Task.WhenAll(InstanceOwnership .Where(kvp => { if (PartitionPumps.TryGetValue(kvp.Key, out PartitionPump pump)) { return !pump.IsRunning; } return true; }) .Select(kvp => AddOrOverwritePartitionPumpAsync(kvp.Key, kvp.Value.SequenceNumber))) .ConfigureAwait(false); // Find an ownership to claim and try to claim it. The method will return null if this instance was not eligible to // increase its ownership list, if no claimable ownership could be found or if a claim attempt failed. PartitionOwnership claimedOwnership = await FindAndClaimOwnershipAsync(completeOwnershipList, activeOwnership).ConfigureAwait(false); if (claimedOwnership != null) { InstanceOwnership[claimedOwnership.PartitionId] = claimedOwnership; await AddOrOverwritePartitionPumpAsync(claimedOwnership.PartitionId, claimedOwnership.SequenceNumber).ConfigureAwait(false); } // Wait the remaining time, if any, to start the next cycle. The total time of a cycle defaults to 10 seconds, // but it may be overriden by a derived class. TimeSpan remainingTimeUntilNextCycle = LoadBalanceUpdate - cycleDuration.Elapsed; if (remainingTimeUntilNextCycle > TimeSpan.Zero) { // If a stop request has been issued, Task.Delay will throw a TaskCanceledException. This is expected and it // will be caught by the StopAsync method. await Task.Delay(remainingTimeUntilNextCycle, cancellationToken).ConfigureAwait(false); } } } /// <summary> /// Finds and tries to claim an ownership if this <see cref="EventProcessor{T}" /> instance is eligible to increase its ownership /// list. /// </summary> /// /// <param name="completeOwnershipEnumerable">A complete enumerable of ownership obtained from the stored service provided by the user.</param> /// <param name="activeOwnership">The set of ownership that are still active.</param> /// /// <returns>The claimed ownership. <c>null</c> if this instance is not eligible, if no claimable ownership was found or if the claim attempt failed.</returns> /// private async Task<PartitionOwnership> FindAndClaimOwnershipAsync(IEnumerable<PartitionOwnership> completeOwnershipEnumerable, IEnumerable<PartitionOwnership> activeOwnership) { // Get a complete list of the partition ids present in the Event Hub. This should be immutable for the time being, but // it may change in the future. var partitionIds = await InnerClient.GetPartitionIdsAsync().ConfigureAwait(false); // Create a partition distribution dictionary from the active ownership list we have, mapping an owner's identifier to the amount of // partitions it owns. When an event processor goes down and it has only expired ownership, it will not be taken into consideration // by others. var partitionDistribution = new Dictionary<string, int> { { Identifier, 0 } }; foreach (PartitionOwnership ownership in activeOwnership) { if (partitionDistribution.TryGetValue(ownership.OwnerIdentifier, out var value)) { partitionDistribution[ownership.OwnerIdentifier] = value + 1; } else { partitionDistribution[ownership.OwnerIdentifier] = 1; } } // The minimum owned partitions count is the minimum amount of partitions every event processor needs to own when the distribution // is balanced. If n = minimumOwnedPartitionsCount, a balanced distribution will only have processors that own n or n + 1 partitions // each. We can guarantee the partition distribution has at least one key, which corresponds to this event processor instance, even // if it owns no partitions. var minimumOwnedPartitionsCount = partitionIds.Length / partitionDistribution.Keys.Count; var ownedPartitionsCount = partitionDistribution[Identifier]; // There are two possible situations in which we may need to claim a partition ownership. // // The first one is when we are below the minimum amount of owned partitions. There's nothing more to check, as we need to claim more // partitions to enforce balancing. // // The second case is a bit tricky. Sometimes the claim must be performed by an event processor that already has reached the minimum // amount of ownership. This may happen, for instance, when we have 13 partitions and 3 processors, each of them owning 4 partitions. // The minimum amount of partitions per processor is, in fact, 4, but in this example we still have 1 orphan partition to claim. To // avoid overlooking this kind of situation, we may want to claim an ownership when we have exactly the minimum amount of ownership, // but we are making sure there are no better candidates among the other event processors. if (ownedPartitionsCount < minimumOwnedPartitionsCount || ownedPartitionsCount == minimumOwnedPartitionsCount && !partitionDistribution.Values.Any(partitions => partitions < minimumOwnedPartitionsCount)) { // Look for unclaimed partitions. If any, randomly pick one of them to claim. IEnumerable<string> unclaimedPartitions = partitionIds .Except(activeOwnership.Select(ownership => ownership.PartitionId)); if (unclaimedPartitions.Any()) { var index = s_randomNumberGenerator.Value.Next(unclaimedPartitions.Count()); return await ClaimOwnershipAsync(unclaimedPartitions.ElementAt(index), completeOwnershipEnumerable).ConfigureAwait(false); } // Only try to steal partitions if there are no unclaimed partitions left. At first, only processors that have exceeded the // maximum owned partition count should be targeted. var maximumOwnedPartitionsCount = minimumOwnedPartitionsCount + 1; IEnumerable<string> stealablePartitions = activeOwnership .Where(ownership => partitionDistribution[ownership.OwnerIdentifier] > maximumOwnedPartitionsCount) .Select(ownership => ownership.PartitionId); // Here's the important part. If there are no processors that have exceeded the maximum owned partition count allowed, we may // need to steal from the processors that have exactly the maximum amount. If this instance is below the minimum count, then // we have no choice as we need to enforce balancing. Otherwise, leave it as it is because the distribution wouldn't change. if (!stealablePartitions.Any() && ownedPartitionsCount < minimumOwnedPartitionsCount) { stealablePartitions = activeOwnership .Where(ownership => partitionDistribution[ownership.OwnerIdentifier] == maximumOwnedPartitionsCount) .Select(ownership => ownership.PartitionId); } // If any stealable partitions were found, randomly pick one of them to claim. if (stealablePartitions.Any()) { var index = s_randomNumberGenerator.Value.Next(stealablePartitions.Count()); return await ClaimOwnershipAsync(stealablePartitions.ElementAt(index), completeOwnershipEnumerable).ConfigureAwait(false); } } // No ownership was claimed. return null; } /// <summary> /// Creates and starts a new partition pump associated with the specified partition. Partition pumps that are overwritten by the creation /// of a new one are properly stopped. /// </summary> /// /// <param name="partitionId">The identifier of the Event Hub partition the partition pump will be associated with. Events will be read only from this partition.</param> /// <param name="initialSequenceNumber">The sequence number of the event within a partition where the partition pump should begin reading events.</param> /// /// <returns>A task to be resolved on when the operation has completed.</returns> /// private async Task AddOrOverwritePartitionPumpAsync(string partitionId, long? initialSequenceNumber) { // Remove and stop the existing partition pump if it exists. We are not specifying any close reason because partition // pumps only are overwritten in case of failure. In these cases, the close reason is delegated to the pump as it may // have more information about what caused the failure. await RemovePartitionPumpIfItExistsAsync(partitionId).ConfigureAwait(false); // Create and start the new partition pump and add it to the dictionary. var partitionContext = new PartitionContext(InnerClient.FullyQualifiedNamespace, InnerClient.EventHubName, ConsumerGroup, partitionId, Identifier, Manager); try { BasePartitionProcessor partitionProcessor = PartitionProcessorFactory(partitionContext); EventProcessorOptions options = Options.Clone(); // Ovewrite the initial event position in case a checkpoint exists. if (initialSequenceNumber.HasValue) { options.InitialEventPosition = EventPosition.FromSequenceNumber(initialSequenceNumber.Value); } var partitionPump = new PartitionPump(InnerClient, ConsumerGroup, partitionContext, partitionProcessor, options); await partitionPump.StartAsync().ConfigureAwait(false); PartitionPumps[partitionId] = partitionPump; } catch (Exception) { // If partition pump creation fails, we'll try again on the next time this method is called. This should happen // on the next load balancing loop as long as this instance still owns the partition. // TODO: delegate the exception handling to an Exception Callback. } } /// <summary> /// Stops an owned partition pump instance in case it exists. It is also removed from the pumps dictionary. /// </summary> /// /// <param name="partitionId">The identifier of the Event Hub partition the partition pump is associated with.</param> /// <param name="reason">The reason why the partition processor is being closed.</param> /// /// <returns>A task to be resolved on when the operation has completed.</returns> /// private async Task RemovePartitionPumpIfItExistsAsync(string partitionId, PartitionProcessorCloseReason? reason = null) { if (PartitionPumps.TryRemove(partitionId, out PartitionPump pump)) { try { await pump.StopAsync(reason).ConfigureAwait(false); } catch (Exception) { // TODO: delegate the exception handling to an Exception Callback. } } } /// <summary> /// Tries to claim ownership of the specified partition. /// </summary> /// /// <param name="partitionId">The identifier of the Event Hub partition the ownership is associated with.</param> /// <param name="completeOwnershipEnumerable">A complete enumerable of ownership obtained from the stored service provided by the user.</param> /// /// <returns>The claimed ownership. <c>null</c> if the claim attempt failed.</returns> /// private async Task<PartitionOwnership> ClaimOwnershipAsync(string partitionId, IEnumerable<PartitionOwnership> completeOwnershipEnumerable) { // We need the eTag from the most recent ownership of this partition, even if it's expired. We want to keep the offset and // the sequence number as well. PartitionOwnership oldOwnership = completeOwnershipEnumerable.FirstOrDefault(ownership => ownership.PartitionId == partitionId); var newOwnership = new PartitionOwnership ( InnerClient.FullyQualifiedNamespace, InnerClient.EventHubName, ConsumerGroup, Identifier, partitionId, oldOwnership?.Offset, oldOwnership?.SequenceNumber, DateTimeOffset.UtcNow, oldOwnership?.ETag ); // We are expecting an enumerable with a single element if the claim attempt succeeds. IEnumerable<PartitionOwnership> claimedOwnership = (await Manager .ClaimOwnershipAsync(new List<PartitionOwnership> { newOwnership }) .ConfigureAwait(false)); return claimedOwnership.FirstOrDefault(); } /// <summary> /// Renews this instance's ownership so they don't expire. /// </summary> /// /// <returns>A task to be resolved on when the operation has completed.</returns> /// private Task RenewOwnershipAsync() { IEnumerable<PartitionOwnership> ownershipToRenew = InstanceOwnership.Values .Select(ownership => new PartitionOwnership ( ownership.FullyQualifiedNamespace, ownership.EventHubName, ownership.ConsumerGroup, ownership.OwnerIdentifier, ownership.PartitionId, ownership.Offset, ownership.SequenceNumber, DateTimeOffset.UtcNow, ownership.ETag )); // We cannot rely on the ownership returned by ClaimOwnershipAsync to update our InstanceOwnership dictionary. // If the user issues a checkpoint update, the associated ownership will have its eTag updated as well, so we // will fail in claiming it here, but this instance still owns it. return Manager.ClaimOwnershipAsync(ownershipToRenew); } } }
49.875817
216
0.602608
[ "MIT" ]
LingyunSu/azure-sdk-for-net
sdk/eventhub/Azure.Messaging.EventHubs/src/Processor/EventProcessor.cs
30,526
C#
using System; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NBitcoin; using NBitcoin.Rules; using Stratis.Bitcoin.AsyncWork; using Stratis.Bitcoin.Base.Deployments; using Stratis.Bitcoin.BlockPulling; using Stratis.Bitcoin.Builder; using Stratis.Bitcoin.Builder.Feature; using Stratis.Bitcoin.Configuration; using Stratis.Bitcoin.Configuration.Settings; using Stratis.Bitcoin.Connection; using Stratis.Bitcoin.Consensus; using Stratis.Bitcoin.Consensus.Rules; using Stratis.Bitcoin.Consensus.Validators; using Stratis.Bitcoin.Controllers; using Stratis.Bitcoin.EventBus; using Stratis.Bitcoin.Interfaces; using Stratis.Bitcoin.P2P; using Stratis.Bitcoin.P2P.Peer; using Stratis.Bitcoin.P2P.Protocol.Behaviors; using Stratis.Bitcoin.P2P.Protocol.Payloads; using Stratis.Bitcoin.Signals; using Stratis.Bitcoin.Utilities; [assembly: InternalsVisibleTo("Stratis.Bitcoin.Tests")] [assembly: InternalsVisibleTo("Stratis.Bitcoin.Tests.Common")] [assembly: InternalsVisibleTo("Stratis.Bitcoin.IntegrationTests.Common")] [assembly: InternalsVisibleTo("Stratis.Bitcoin.Features.Consensus.Tests")] [assembly: InternalsVisibleTo("Stratis.Bitcoin.IntegrationTests")] namespace Stratis.Bitcoin.Base { /// <summary> /// Base node services, these are the services a node has to have. /// The ConnectionManager feature is also part of the base but may go in a feature of its own. /// The base features are the minimal components required to connect to peers and maintain the best chain. /// <para> /// The base node services for a node are: /// <list type="bullet"> /// <item>the ConcurrentChain to keep track of the best chain,</item> /// <item>the ConnectionManager to connect with the network,</item> /// <item>DatetimeProvider and Cancellation,</item> /// <item>CancellationProvider and Cancellation,</item> /// <item>DataFolder,</item> /// <item>ChainState.</item> /// </list> /// </para> /// </summary> public sealed class BaseFeature : FullNodeFeature { /// <summary>Global application life cycle control - triggers when application shuts down.</summary> private readonly INodeLifetime nodeLifetime; /// <summary>Information about node's chain.</summary> private readonly IChainState chainState; /// <summary>Access to the database of blocks.</summary> private readonly IChainRepository chainRepository; /// <summary>User defined node settings.</summary> private readonly NodeSettings nodeSettings; /// <summary>Locations of important folders and files on disk.</summary> private readonly DataFolder dataFolder; /// <summary>Thread safe chain of block headers from genesis.</summary> private readonly ChainIndexer chainIndexer; /// <summary>Manager of node's network connections.</summary> private readonly IConnectionManager connectionManager; /// <summary>Provider of time functions.</summary> private readonly IDateTimeProvider dateTimeProvider; /// <summary>Provider for creating and managing background async loop tasks.</summary> private readonly IAsyncProvider asyncProvider; /// <summary>Logger for the node.</summary> private readonly ILogger logger; /// <summary>Factory for creating loggers.</summary> private readonly ILoggerFactory loggerFactory; /// <summary>State of time synchronization feature that stores collected data samples.</summary> private readonly ITimeSyncBehaviorState timeSyncBehaviorState; /// <summary>Manager of node's network peers.</summary> private IPeerAddressManager peerAddressManager; /// <summary>Periodic task to save list of peers to disk.</summary> private IAsyncLoop flushAddressManagerLoop; /// <summary>Periodic task to save the chain to the database.</summary> private IAsyncLoop flushChainLoop; /// <summary>A handler that can manage the lifetime of network peers.</summary> private readonly IPeerBanning peerBanning; /// <summary>Provider of IBD state.</summary> private readonly IInitialBlockDownloadState initialBlockDownloadState; /// <inheritdoc cref="Network"/> private readonly Network network; private readonly INodeStats nodeStats; private readonly IProvenBlockHeaderStore provenBlockHeaderStore; private readonly IConsensusManager consensusManager; private readonly IConsensusRuleEngine consensusRules; private readonly IBlockPuller blockPuller; private readonly IBlockStore blockStore; private readonly ITipsManager tipsManager; private readonly IKeyValueRepository keyValueRepo; /// <inheritdoc cref="IFinalizedBlockInfoRepository"/> private readonly IFinalizedBlockInfoRepository finalizedBlockInfoRepository; /// <inheritdoc cref="IPartialValidator"/> private readonly IPartialValidator partialValidator; public BaseFeature(NodeSettings nodeSettings, DataFolder dataFolder, INodeLifetime nodeLifetime, ChainIndexer chainIndexer, IChainState chainState, IConnectionManager connectionManager, IChainRepository chainRepository, IFinalizedBlockInfoRepository finalizedBlockInfo, IDateTimeProvider dateTimeProvider, IAsyncProvider asyncProvider, ITimeSyncBehaviorState timeSyncBehaviorState, ILoggerFactory loggerFactory, IInitialBlockDownloadState initialBlockDownloadState, IPeerBanning peerBanning, IPeerAddressManager peerAddressManager, IConsensusManager consensusManager, IConsensusRuleEngine consensusRules, IPartialValidator partialValidator, IBlockPuller blockPuller, IBlockStore blockStore, Network network, ITipsManager tipsManager, IKeyValueRepository keyValueRepo, INodeStats nodeStats, IProvenBlockHeaderStore provenBlockHeaderStore = null) { this.chainState = Guard.NotNull(chainState, nameof(chainState)); this.chainRepository = Guard.NotNull(chainRepository, nameof(chainRepository)); this.finalizedBlockInfoRepository = Guard.NotNull(finalizedBlockInfo, nameof(finalizedBlockInfo)); this.nodeSettings = Guard.NotNull(nodeSettings, nameof(nodeSettings)); this.dataFolder = Guard.NotNull(dataFolder, nameof(dataFolder)); this.nodeLifetime = Guard.NotNull(nodeLifetime, nameof(nodeLifetime)); this.chainIndexer = Guard.NotNull(chainIndexer, nameof(chainIndexer)); this.connectionManager = Guard.NotNull(connectionManager, nameof(connectionManager)); this.consensusManager = consensusManager; this.consensusRules = consensusRules; this.blockPuller = blockPuller; this.blockStore = blockStore; this.network = network; this.nodeStats = nodeStats; this.provenBlockHeaderStore = provenBlockHeaderStore; this.partialValidator = partialValidator; this.peerBanning = Guard.NotNull(peerBanning, nameof(peerBanning)); this.tipsManager = Guard.NotNull(tipsManager, nameof(tipsManager)); this.keyValueRepo = Guard.NotNull(keyValueRepo, nameof(keyValueRepo)); this.peerAddressManager = Guard.NotNull(peerAddressManager, nameof(peerAddressManager)); this.peerAddressManager.PeerFilePath = this.dataFolder; this.initialBlockDownloadState = initialBlockDownloadState; this.dateTimeProvider = dateTimeProvider; this.asyncProvider = asyncProvider; this.timeSyncBehaviorState = timeSyncBehaviorState; this.loggerFactory = loggerFactory; this.logger = loggerFactory.CreateLogger(this.GetType().FullName); } /// <inheritdoc /> public override async Task InitializeAsync() { // TODO rewrite chain starting logic. Tips manager should be used. await this.StartChainAsync().ConfigureAwait(false); if (this.provenBlockHeaderStore != null) { // If we find at this point that proven header store is behind chain we can rewind chain (this will cause a ripple effect and rewind block store and consensus) // This problem should go away once we implement a component to keep all tips up to date // https://github.com/stratisproject/StratisBitcoinFullNode/issues/2503 ChainedHeader initializedAt = await this.provenBlockHeaderStore.InitializeAsync(this.chainIndexer.Tip); this.chainIndexer.Initialize(initializedAt); } NetworkPeerConnectionParameters connectionParameters = this.connectionManager.Parameters; connectionParameters.IsRelay = this.connectionManager.ConnectionSettings.RelayTxes; connectionParameters.TemplateBehaviors.Add(new PingPongBehavior()); connectionParameters.TemplateBehaviors.Add(new EnforcePeerVersionCheckBehavior(this.chainIndexer, this.nodeSettings, this.network, this.loggerFactory)); connectionParameters.TemplateBehaviors.Add(new ConsensusManagerBehavior(this.chainIndexer, this.initialBlockDownloadState, this.consensusManager, this.peerBanning, this.loggerFactory)); // TODO: Once a proper rate limiting strategy has been implemented, this check will be removed. if (!this.network.IsRegTest()) connectionParameters.TemplateBehaviors.Add(new RateLimitingBehavior(this.dateTimeProvider, this.loggerFactory, this.peerBanning)); connectionParameters.TemplateBehaviors.Add(new PeerBanningBehavior(this.loggerFactory, this.peerBanning, this.nodeSettings)); connectionParameters.TemplateBehaviors.Add(new BlockPullerBehavior(this.blockPuller, this.initialBlockDownloadState, this.dateTimeProvider, this.loggerFactory)); connectionParameters.TemplateBehaviors.Add(new ConnectionManagerBehavior(this.connectionManager, this.loggerFactory)); this.StartAddressManager(connectionParameters); if (this.connectionManager.ConnectionSettings.SyncTimeEnabled) { connectionParameters.TemplateBehaviors.Add(new TimeSyncBehavior(this.timeSyncBehaviorState, this.dateTimeProvider, this.loggerFactory)); } else { this.logger.LogDebug("Time synchronization with peers is disabled."); } // Block store must be initialized before consensus manager. // This may be a temporary solution until a better way is found to solve this dependency. this.blockStore.Initialize(); this.consensusRules.Initialize(this.chainIndexer.Tip); await this.consensusManager.InitializeAsync(this.chainIndexer.Tip).ConfigureAwait(false); this.chainState.ConsensusTip = this.consensusManager.Tip; this.nodeStats.RegisterStats(sb => sb.Append(this.asyncProvider.GetStatistics(!this.nodeSettings.LogSettings.DebugArgs.Any())), StatsType.Component, this.GetType().Name, 100); // TODO: Should this always be called? ((IBlockStoreQueue)this.blockStore).ReindexChain(this.consensusManager, this.nodeLifetime.ApplicationStopping); } /// <summary> /// Initializes node's chain repository. /// Creates periodic task to persist changes to the database. /// </summary> private async Task StartChainAsync() { if (!Directory.Exists(this.dataFolder.ChainPath)) { this.logger.LogInformation("Creating {0}.", this.dataFolder.ChainPath); Directory.CreateDirectory(this.dataFolder.ChainPath); } if (!Directory.Exists(this.dataFolder.KeyValueRepositoryPath)) { this.logger.LogInformation("Creating {0}.", this.dataFolder.KeyValueRepositoryPath); Directory.CreateDirectory(this.dataFolder.KeyValueRepositoryPath); } this.logger.LogInformation("Loading finalized block height."); await this.finalizedBlockInfoRepository.LoadFinalizedBlockInfoAsync(this.network).ConfigureAwait(false); this.logger.LogInformation("Loading chain."); ChainedHeader chainTip = await this.chainRepository.LoadAsync(this.chainIndexer.Genesis).ConfigureAwait(false); this.chainIndexer.Initialize(chainTip); this.logger.LogInformation("Chain loaded at height {0}.", this.chainIndexer.Height); this.flushChainLoop = this.asyncProvider.CreateAndRunAsyncLoop("FlushChain", async token => { await this.chainRepository.SaveAsync(this.chainIndexer).ConfigureAwait(false); if (this.provenBlockHeaderStore != null) await this.provenBlockHeaderStore.SaveAsync().ConfigureAwait(false); }, this.nodeLifetime.ApplicationStopping, repeatEvery: TimeSpan.FromMinutes(1.0), startAfter: TimeSpan.FromMinutes(1.0)); } /// <summary> /// Initializes node's address manager. Loads previously known peers from the file /// or creates new peer file if it does not exist. Creates periodic task to persist changes /// in peers to disk. /// </summary> private void StartAddressManager(NetworkPeerConnectionParameters connectionParameters) { var addressManagerBehaviour = new PeerAddressManagerBehaviour(this.dateTimeProvider, this.peerAddressManager, this.peerBanning, this.loggerFactory); connectionParameters.TemplateBehaviors.Add(addressManagerBehaviour); if (File.Exists(Path.Combine(this.dataFolder.AddressManagerFilePath, PeerAddressManager.PeerFileName))) { this.logger.LogInformation($"Loading peers from : {this.dataFolder.AddressManagerFilePath}."); this.peerAddressManager.LoadPeers(); } this.flushAddressManagerLoop = this.asyncProvider.CreateAndRunAsyncLoop("Periodic peer flush", token => { this.peerAddressManager.SavePeers(); return Task.CompletedTask; }, this.nodeLifetime.ApplicationStopping, repeatEvery: TimeSpan.FromMinutes(5.0), startAfter: TimeSpan.FromMinutes(5.0)); } /// <inheritdoc /> public override void Dispose() { this.logger.LogInformation("Flushing peers."); this.flushAddressManagerLoop.Dispose(); this.logger.LogInformation("Disposing peer address manager."); this.peerAddressManager.Dispose(); if (this.flushChainLoop != null) { this.logger.LogInformation("Flushing headers chain."); this.flushChainLoop.Dispose(); } this.logger.LogInformation("Disposing time sync behavior."); this.timeSyncBehaviorState.Dispose(); this.logger.LogInformation("Disposing consensus manager."); this.consensusManager.Dispose(); this.logger.LogInformation("Disposing block puller."); this.blockPuller.Dispose(); this.logger.LogInformation("Disposing partial validator."); this.partialValidator.Dispose(); this.logger.LogInformation("Disposing consensus rules."); this.consensusRules.Dispose(); this.logger.LogInformation("Saving chain repository."); this.chainRepository.SaveAsync(this.chainIndexer).GetAwaiter().GetResult(); this.chainRepository.Dispose(); if (this.provenBlockHeaderStore != null) { this.logger.LogInformation("Saving proven header store."); this.provenBlockHeaderStore.SaveAsync().GetAwaiter().GetResult(); this.provenBlockHeaderStore.Dispose(); } this.logger.LogInformation("Disposing finalized block info repository."); this.finalizedBlockInfoRepository.Dispose(); this.logger.LogInformation("Disposing address indexer."); this.logger.LogInformation("Disposing block store."); this.blockStore.Dispose(); this.keyValueRepo.Dispose(); } } /// <summary> /// A class providing extension methods for <see cref="IFullNodeBuilder"/>. /// </summary> public static class FullNodeBuilderBaseFeatureExtension { /// <summary> /// Makes the full node use all the required features - <see cref="BaseFeature"/>. /// </summary> /// <param name="fullNodeBuilder">Builder responsible for creating the node.</param> /// <returns>Full node builder's interface to allow fluent code.</returns> public static IFullNodeBuilder UseBaseFeature(this IFullNodeBuilder fullNodeBuilder) { fullNodeBuilder.ConfigureFeature(features => { features .AddFeature<BaseFeature>() .FeatureServices(services => { services.AddSingleton(fullNodeBuilder.Network.Consensus.ConsensusFactory); services.AddSingleton<DBreezeSerializer>(); services.AddSingleton(fullNodeBuilder.NodeSettings.LoggerFactory); services.AddSingleton(fullNodeBuilder.NodeSettings.DataFolder); services.AddSingleton<INodeLifetime, NodeLifetime>(); services.AddSingleton<IPeerBanning, PeerBanning>(); services.AddSingleton<FullNodeFeatureExecutor>(); services.AddSingleton<ISignals, Signals.Signals>(); services.AddSingleton<ISubscriptionErrorHandler, DefaultSubscriptionErrorHandler>(); services.AddSingleton<FullNode>().AddSingleton((provider) => { return provider.GetService<FullNode>() as IFullNode; }); services.AddSingleton(new ChainIndexer(fullNodeBuilder.Network)); services.AddSingleton(DateTimeProvider.Default); services.AddSingleton<IInvalidBlockHashStore, InvalidBlockHashStore>(); services.AddSingleton<IChainState, ChainState>(); services.AddSingleton<IChainRepository, ChainRepository>(); services.AddSingleton<IChainStore, LeveldbHeaderStore>(); services.AddSingleton<IFinalizedBlockInfoRepository, FinalizedBlockInfoRepository>(); services.AddSingleton<ITimeSyncBehaviorState, TimeSyncBehaviorState>(); services.AddSingleton<NodeDeployments>(); services.AddSingleton<IInitialBlockDownloadState, InitialBlockDownloadState>(); services.AddSingleton<IKeyValueRepository, KeyValueRepository>(); services.AddSingleton<ITipsManager, TipsManager>(); services.AddSingleton<IAsyncProvider, AsyncProvider>(); // Consensus services.AddSingleton<ConsensusSettings>(); services.AddSingleton<ICheckpoints, Checkpoints>(); services.AddSingleton<ConsensusRulesContainer>(); foreach (var ruleType in fullNodeBuilder.Network.Consensus.ConsensusRules.HeaderValidationRules) services.AddSingleton(typeof(IHeaderValidationConsensusRule), ruleType); foreach (var ruleType in fullNodeBuilder.Network.Consensus.ConsensusRules.IntegrityValidationRules) services.AddSingleton(typeof(IIntegrityValidationConsensusRule), ruleType); foreach (var ruleType in fullNodeBuilder.Network.Consensus.ConsensusRules.PartialValidationRules) services.AddSingleton(typeof(IPartialValidationConsensusRule), ruleType); foreach (var ruleType in fullNodeBuilder.Network.Consensus.ConsensusRules.FullValidationRules) services.AddSingleton(typeof(IFullValidationConsensusRule), ruleType); // Connection services.AddSingleton<INetworkPeerFactory, NetworkPeerFactory>(); services.AddSingleton<NetworkPeerConnectionParameters>(); services.AddSingleton<IConnectionManager, ConnectionManager>(); services.AddSingleton<ConnectionManagerSettings>(); services.AddSingleton(new PayloadProvider().DiscoverPayloads()); services.AddSingleton<IVersionProvider, VersionProvider>(); services.AddSingleton<IBlockPuller, BlockPuller>(); // Peer address manager services.AddSingleton<IPeerAddressManager, PeerAddressManager>(); services.AddSingleton<IPeerConnector, PeerConnectorAddNode>(); services.AddSingleton<IPeerConnector, PeerConnectorConnectNode>(); services.AddSingleton<IPeerConnector, PeerConnectorDiscovery>(); services.AddSingleton<IPeerDiscovery, PeerDiscovery>(); services.AddSingleton<ISelfEndpointTracker, SelfEndpointTracker>(); // Consensus // Consensus manager is created like that due to CM's constructor being internal. This is done // in order to prevent access to CM creation and CHT usage from another features. CHT is supposed // to be used only by CM and no other component. services.AddSingleton<IConsensusManager>(provider => new ConsensusManager( chainedHeaderTree: provider.GetService<IChainedHeaderTree>(), network: provider.GetService<Network>(), loggerFactory: provider.GetService<ILoggerFactory>(), chainState: provider.GetService<IChainState>(), integrityValidator: provider.GetService<IIntegrityValidator>(), partialValidator: provider.GetService<IPartialValidator>(), fullValidator: provider.GetService<IFullValidator>(), consensusRules: provider.GetService<IConsensusRuleEngine>(), finalizedBlockInfo: provider.GetService<IFinalizedBlockInfoRepository>(), signals: provider.GetService<ISignals>(), peerBanning: provider.GetService<IPeerBanning>(), ibdState: provider.GetService<IInitialBlockDownloadState>(), chainIndexer: provider.GetService<ChainIndexer>(), blockPuller: provider.GetService<IBlockPuller>(), blockStore: provider.GetService<IBlockStore>(), connectionManager: provider.GetService<IConnectionManager>(), nodeStats: provider.GetService<INodeStats>(), nodeLifetime: provider.GetService<INodeLifetime>(), consensusSettings: provider.GetService<ConsensusSettings>(), dateTimeProvider: provider.GetService<IDateTimeProvider>())); services.AddSingleton<IChainWorkComparer, ChainWorkComparer>(); services.AddSingleton<IChainedHeaderTree, ChainedHeaderTree>(); services.AddSingleton<IHeaderValidator, HeaderValidator>(); services.AddSingleton<IIntegrityValidator, IntegrityValidator>(); services.AddSingleton<IPartialValidator, PartialValidator>(); services.AddSingleton<IFullValidator, FullValidator>(); // Console services.AddSingleton<INodeStats, NodeStats>(); }); }); return fullNodeBuilder; } } }
51.554622
197
0.6663
[ "MIT" ]
0tim0/StratisFullNode
src/Stratis.Bitcoin/Base/BaseFeature.cs
24,540
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.HDInsight.Models { using Newtonsoft.Json; using System.Linq; /// <summary> /// The cluster host information. /// </summary> public partial class HostInfo { /// <summary> /// Initializes a new instance of the HostInfo class. /// </summary> public HostInfo() { CustomInit(); } /// <summary> /// Initializes a new instance of the HostInfo class. /// </summary> /// <param name="name">The host name</param> public HostInfo(string name = default(string)) { Name = name; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets the host name /// </summary> [JsonProperty(PropertyName = "name")] public string Name { get; set; } } }
26.807692
90
0.585366
[ "MIT" ]
AWESOME-S-MINDSET/azure-sdk-for-net
sdk/hdinsight/Microsoft.Azure.Management.HDInsight/src/Generated/Models/HostInfo.cs
1,394
C#
// ******************************************************************************************************** // Product Name: DotSpatial.Positioning.dll // Description: A library for managing GPS connections. // ******************************************************************************************************** // The contents of this file are subject to the MIT License (MIT) // you may not use this file except in compliance with the License. You may obtain a copy of the License at // http://dotspatial.codeplex.com/license // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either expressed or implied. See the License for the specific language governing rights and // limitations under the License. // // The Original Code is from http://gps3.codeplex.com/ version 3.0 // // The Initial Developer of this original code is Jon Pearson. Submitted Oct. 21, 2010 by Ben Tombs (tidyup) // // Contributor(s): (Open source contributors should list themselves and their modifications here). // ------------------------------------------------------------------------------------------------------- // | Developer | Date | Comments // |--------------------------|------------|-------------------------------------------------------------- // | Tidyup (Ben Tombs) | 10/21/2010 | Original copy submitted from modified GPS.Net 3.0 // | Shade1974 (Ted Dunsford) | 10/22/2010 | Added file headers reviewed formatting with resharper. // ******************************************************************************************************** using System; using System.IO; using System.Text; using System.Threading; namespace DotSpatial.Positioning { /// <summary> /// Emulator that sources it's data from a text file /// </summary> public class TextFileEmulator : Emulator { /// <summary> /// /// </summary> private readonly string _filePath; /// <summary> /// /// </summary> private StreamReader _reader; /// <summary> /// /// </summary> private TimeSpan _readInterval; /// <summary> /// Creates a Text File Emulator from the specified file path with a default read interval of 400 seconds /// </summary> /// <param name="filePath">The file path.</param> public TextFileEmulator(string filePath) : this(filePath, TimeSpan.FromSeconds(400)) { } /// <summary> /// Creates a Text File Emulator from the specified file path with the specified read interval /// </summary> /// <param name="filePath">The file path.</param> /// <param name="readInterval">The read interval.</param> public TextFileEmulator(string filePath, TimeSpan readInterval) { _filePath = filePath; _readInterval = readInterval; } /// <summary> /// Gets or sets the ReadInterval for the Text File Emulator /// </summary> /// <value>The read interval.</value> public TimeSpan ReadInterval { get { return _readInterval; } set { _readInterval = value; } } /// <summary> /// OnEmulation event handler /// </summary> protected override void OnEmulation() { // Are we at the end of the file? if (_reader == null || _reader.EndOfStream) { // Yes. Re-open it from the beginning FileStream stream = new FileStream(_filePath, FileMode.Open, FileAccess.Read, FileShare.Read); _reader = new StreamReader(stream); } // Read a line from the file string line = _reader.ReadLine(); // Don't write to the buffer if it's full if (line != null) { if (ReadBuffer.Count + line.Length > ReadBuffer.Capacity) return; // Write the string ReadBuffer.AddRange(Encoding.ASCII.GetBytes(line)); } // Sleep #if PocketPC Thread.Sleep((int)_ReadInterval.TotalMilliseconds); #else Thread.Sleep(_readInterval); #endif } // TODO: We should be able to get rid of this. Not used internally anymore. //public override Emulator Clone() //{ // // Return a copy of this emulator // return new TextFileEmulator(_FilePath); //} } }
39.358333
114
0.508363
[ "MIT" ]
sdrmaps/dotspatial
Source/DotSpatial.Positioning/TextFileEmulator.cs
4,725
C#
#pragma checksum "C:\Users\sneha\Desktop\iCLASS\iCLASS\sci4.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "D85F1157545F6B56B926DA29377F6618" //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Windows; using System.Windows.Automation; using System.Windows.Automation.Peers; using System.Windows.Automation.Provider; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Interop; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Imaging; using System.Windows.Resources; using System.Windows.Shapes; using System.Windows.Threading; namespace iCLASS { public partial class sci4 : System.Windows.Controls.UserControl { internal System.Windows.Controls.Canvas LayoutRoot; internal System.Windows.Controls.Image ima1; internal System.Windows.Controls.Button button561; internal System.Windows.Shapes.Rectangle rectangle1; internal System.Windows.Controls.Label label21; internal System.Windows.Controls.Image image8; internal System.Windows.Controls.Label label8; internal System.Windows.Controls.Image image1332; internal System.Windows.Controls.Image image1; private bool _contentLoaded; /// <summary> /// InitializeComponent /// </summary> [System.Diagnostics.DebuggerNonUserCodeAttribute()] public void InitializeComponent() { if (_contentLoaded) { return; } _contentLoaded = true; System.Windows.Application.LoadComponent(this, new System.Uri("/iCLASS;component/sci4.xaml", System.UriKind.Relative)); this.LayoutRoot = ((System.Windows.Controls.Canvas)(this.FindName("LayoutRoot"))); this.ima1 = ((System.Windows.Controls.Image)(this.FindName("ima1"))); this.button561 = ((System.Windows.Controls.Button)(this.FindName("button561"))); this.rectangle1 = ((System.Windows.Shapes.Rectangle)(this.FindName("rectangle1"))); this.label21 = ((System.Windows.Controls.Label)(this.FindName("label21"))); this.image8 = ((System.Windows.Controls.Image)(this.FindName("image8"))); this.label8 = ((System.Windows.Controls.Label)(this.FindName("label8"))); this.image1332 = ((System.Windows.Controls.Image)(this.FindName("image1332"))); this.image1 = ((System.Windows.Controls.Image)(this.FindName("image1"))); } } }
39.95
143
0.623279
[ "MIT" ]
VikramadityaJakkula/MyLearnMateCode
iCLASS/obj/Debug/sci4.g.cs
3,198
C#