content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Collections.Generic; using Newtonsoft.Json; using Stripe.Infrastructure; namespace Stripe { public abstract class SubscriptionSharedOptions : StripeBaseOptions, ISupportMetadata { /// <summary> /// A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice subtotal that will be transferred to the application owner’s Stripe account. The request must be made with an OAuth key in order to set an application fee percentage. For more information, see the application fees <see href="https://stripe.com/docs/connect/subscriptions#collecting-fees-on-subscriptions">documentation</see>. /// </summary> [JsonProperty("application_fee_percent")] public decimal? ApplicationFeePercent { get; set; } /// <summary> /// One of <see cref="StripeBilling" />. When charging automatically, Stripe will attempt to pay this subscription at the end of the cycle using the default source attached to the customer. When sending an invoice, Stripe will email your customer an invoice with payment instructions. Defaults to <c>charge_automatically</c>. /// </summary> [JsonProperty("billing")] public StripeBilling? Billing { get; set; } /// <summary> /// The code of the coupon to apply to this subscription. A coupon applied to a subscription will only affect invoices created for that particular subscription. /// </summary> [JsonProperty("coupon")] public string CouponId { get; set; } /// <summary> /// Number of days a customer has to pay invoices generated by this subscription. Only valid for subscriptions where <c>billing=send_invoice</c>. /// </summary> [JsonProperty("days_until_due")] public int? DaysUntilDue { get; set; } /// <summary> /// A set of key/value pairs that you can attach to a subscription object. It can be useful for storing additional information about the subscription in a structured format. /// </summary> [JsonProperty("metadata")] public Dictionary<string, string> Metadata { get; set; } /// <summary> /// Boolean (default <c>true</c>). Use with a <c>billing_cycle_anchor</c> timestamp to determine whether the customer will be invoiced a prorated amount until the anchor date. If <c>false</c>, the anchor period will be free (similar to a trial). /// </summary> [JsonProperty("prorate")] public bool? Prorate { get; set; } /// <summary> /// ID of a Token or a Source, as returned by <see cref="https://stripe.com/docs/elements">Elements</see>. You must provide a source if the customer does not already have a valid source attached, and you are subscribing the customer to be charged automatically for a plan that is not free. Passing <c>source</c> will create a new source object, make it the customer default source, and delete the old customer default if one exists. If you want to add an additional source, instead use the <see cref="https://stripe.com/docs/api#create_card">card creation API</see> to add the card and then the <see cref="https://stripe.com/docs/api#update_customer">customer update API</see> to set it as the default. Whenever you attach a card to a customer, Stripe will automatically validate the card. /// <para>If you use Source, you cannot use SourceCard also.</para> /// </summary> [JsonProperty("source")] public string Source { get; set; } /// <summary> /// <see cref="SourceCard"/> instance containing a user’s credit card details. You must provide a source if the customer does not already have a valid source attached, and you are subscribing the customer to be charged automatically for a plan that is not free. Passing <c>source</c> will create a new source object, make it the customer default source, and delete the old customer default if one exists. If you want to add an additional source, instead use the <see cref="https://stripe.com/docs/api#create_card">card creation API</see> to add the card and then the <see cref="https://stripe.com/docs/api#update_customer">customer update API</see> to set it as the default. Whenever you attach a card to a customer, Stripe will automatically validate the card. /// <para>If you use SourceCard, you cannot use Source also.</para> /// </summary> [JsonProperty("source")] public SourceCard SourceCard { get; set; } /// <summary> /// A non-negative decimal (with at most four decimal places) between 0 and 100. This represents the percentage of the subscription invoice subtotal that will be calculated and added as tax to the final amount each billing period. For example, a plan which charges $10/month with a <c>tax_percent</c> of 20.0 will charge $12 per invoice. /// </summary> [JsonProperty("tax_percent")] public decimal? TaxPercent { get; set; } #region TrialEnd /// <summary> /// Date representing the end of the trial period the customer will get before being charged for the first time. Set <see cref="EndTrialNow"/> to <c>true</c> to end the customer’s trial immediately. /// </summary> public DateTime? TrialEnd { get; set; } public bool EndTrialNow { get; set; } [JsonProperty("trial_end")] internal string TrialEndInternal => EndTrialNow ? "now" : TrialEnd?.ConvertDateTimeToEpoch().ToString(); #endregion /// <summary> /// Boolean. Decide whether to use the default trial on the plan when creating a subscription. /// </summary> [JsonProperty("trial_from_plan")] public bool? TrialFromPlan { get; set; } [Obsolete("Use Source or SourceCard")] [JsonProperty("card")] public StripeCreditCardOptions Card { get; set; } [Obsolete("Use Items")] [JsonProperty("plan")] public string PlanId { get; set; } [Obsolete("Use Items")] [JsonProperty("quantity")] public int? Quantity { get; set; } } }
64.489583
797
0.683411
[ "Apache-2.0" ]
TrueNorthIT/stripe-dotnet
src/Stripe.net/Services/Subscriptions/SubscriptionSharedOptions.cs
6,199
C#
using System; using System.Net; namespace GDataAPIConnecter { public class GoogleClient : WebClient { private readonly CookieContainer _Container = null; public GoogleClient() { _Container = new CookieContainer(); } public GoogleClient(CookieContainer container) { _Container = container; } protected override WebRequest GetWebRequest(Uri address) { WebRequest r = base.GetWebRequest(address); if (r is HttpWebRequest request) { request.CookieContainer = _Container; } return r; } protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult result) { WebResponse response = base.GetWebResponse(request, result); ReadCookies(response); return response; } protected override WebResponse GetWebResponse(WebRequest request) { WebResponse response = base.GetWebResponse(request); ReadCookies(response); return response; } private void ReadCookies(WebResponse r) { if (r is HttpWebResponse response) { CookieCollection cookies = response.Cookies; _Container.Add(cookies); } } } }
26.018519
94
0.569395
[ "MIT" ]
Arisix/GoogleSpreadSheetExporter
script/Downloader/APIConnecter/GoogleClient.cs
1,407
C#
// Copyright (c) 2019, UW Medicine Research IT, University of Washington // Developed by Nic Dobbins and Cliff Spital, CRIO Sean Mooney // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. using System; using System.Linq; using System.Data; using Dapper; using Model.Admin; using System.Collections.Generic; namespace Services.Tables { public class SpecializationTable : ISqlTableType { public DataTable Value { get; private set; } public const string Type = "app.SpecializationTable"; const string specializationGroupId = "SpecializationGroupId"; const string universalId = "UniversalId"; const string uiDisplayText = "UiDisplayText"; const string sqlSetWhere = "SqlSetWhere"; const string orderId = "OrderId"; SpecializationTable(IEnumerable<Specialization> specs) { var table = Schema(); Fill(table, with: specs); Value = table; } DataTable Schema() { var dt = new DataTable(); dt.Columns.Add(new DataColumn(specializationGroupId, typeof(int)) { AllowDBNull = true }); dt.Columns.Add(new DataColumn(universalId, typeof(string)) { AllowDBNull = true }); dt.Columns.Add(new DataColumn(uiDisplayText, typeof(string)) { AllowDBNull = true }); dt.Columns.Add(new DataColumn(sqlSetWhere, typeof(string)) { AllowDBNull = true }); dt.Columns.Add(new DataColumn(orderId, typeof(int)) { AllowDBNull = true }); return dt; } void Fill(DataTable table, IEnumerable<Specialization> with) { foreach (var s in with) { var row = table.NewRow(); row[specializationGroupId] = s.SpecializationGroupId; row[universalId] = s.UniversalId?.ToString(); row[uiDisplayText] = s.UiDisplayText; row[sqlSetWhere] = s.SqlSetWhere; row[orderId] = s.OrderId; table.Rows.Add(row); } } public static DataTable From(IEnumerable<Specialization> specs) { var ss = specs ?? new List<Specialization>(); return new SpecializationTable(ss).Value; } public static DataTable From(SpecializationGroup group) { return From(group.Specializations); } } }
31.111111
77
0.561071
[ "MPL-2.0" ]
jtlresearchit/leaf
src/server/Services/Tables/SpecializationTable.cs
2,802
C#
 // ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Commands.Utilities.Websites.Services { using DeploymentEntities; using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.ServiceModel; using System.ServiceModel.Web; /// <summary> /// Provides the Windows Azure Service Management Api for Windows Azure Websites Deployment. /// </summary> [ServiceContract] public interface IDeploymentServiceManagement { [Description("Gets all deployments for a given repository")] [OperationContract(AsyncPattern = true)] [WebInvoke(Method = "GET", UriTemplate = "deployments?%24orderby=ReceivedTime%20desc&%24top={maxItems}")] IAsyncResult BeginGetDeployments(int maxItems, AsyncCallback callback, object state); List<DeployResult> EndGetDeployments(IAsyncResult asyncResult); [Description("Gets all deployment logs for a given commit")] [OperationContract(AsyncPattern = true)] [WebInvoke(Method = "GET", UriTemplate = "deployments/{commitId}/log")] IAsyncResult BeginGetDeploymentLogs(string commitId, AsyncCallback callback, object state); List<LogEntry> EndGetDeploymentLogs(IAsyncResult asyncResult); [Description("Gets a deployment log for a given commit")] [OperationContract(AsyncPattern = true)] [WebInvoke(Method = "GET", UriTemplate = "deployments/{commitId}/log/{logId}")] IAsyncResult BeginGetDeploymentLog(string commitId, string logId, AsyncCallback callback, object state); LogEntry EndGetDeploymentLog(IAsyncResult asyncResult); [Description("Redeploys a specific commit")] [OperationContract(AsyncPattern = true)] [WebInvoke(Method = "PUT", UriTemplate = "deployments/{commitId}")] IAsyncResult BeginDeploy(string commitId, AsyncCallback callback, object state); void EndDeploy(IAsyncResult asyncResult); [Description("Downloads the website logs")] [OperationContract(AsyncPattern = true)] [WebInvoke(Method = "GET", UriTemplate = "dump")] IAsyncResult BeginDownloadLogs(AsyncCallback callback, object state); Stream EndDownloadLogs(IAsyncResult asyncResult); } }
48.936508
114
0.668829
[ "MIT" ]
stankovski/azure-sdk-tools
src/ServiceManagement/Services/Commands.Utilities/Websites/Services/IDeploymentServiceManagement.cs
3,023
C#
// <copyright file="IParameterBuilderReferenceBuilder.cs" company="Cui Ziqiang"> // Copyright (c) 2017 Cui Ziqiang // </copyright> namespace CrossCutterN.Weaver.Reference.Base.Metadata { using System; using System.Reflection; using CrossCutterN.Base.Common; /// <summary> /// Reference to <see cref="CrossCutterN.Base.Metadata.IParameterBuilder"/> interface to be built up. /// </summary> internal interface IParameterBuilderReferenceBuilder : IBuilder<IParameterBuilderReference> { /// <summary> /// Sets reference to the interface type. /// </summary> Type TypeReference { set; } /// <summary> /// Sets reference to the readonly only interface type it can build to. /// </summary> Type ReadOnlyTypeReference { set; } /// <summary> /// Sets reference to AddCustomAttribute method. /// </summary> MethodInfo AddCustomAttributeMethod { set; } /// <summary> /// Sets reference to Build method. /// </summary> MethodInfo BuildMethod { set; } } }
30.081081
105
0.627134
[ "MIT" ]
keeper013/CrossCutterN
CrossCutterN.Weaver/Reference/Base/Metadata/IParameterBuilderReferenceBuilder.cs
1,115
C#
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.OpenApi; using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; using QuickAPI.Configurations; using QuickAPI.Extensions; using QuickAPI.Security; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; namespace QuickAPI { public class Startup { private const string _defaultTitle = "QuickAPI"; private const string _loginEndpoint = "/api/login"; private const string _apiDocumentPath = "/api-document"; private readonly OpenApiDocument? _openApiDocument; private readonly OpenApiSecurityScheme? _openApiSecurityScheme; public Startup(IConfiguration configuration) { Configuration = configuration; EndpointConfiguration = configuration .GetSection("EndpointConfiguration") .Get<EndpointConfiguration>(); _openApiSecurityScheme = SwaggerEnabled && AuthEnabled ? AuthConfig!.BuildOpenApiSecurityScheme() : null; _openApiDocument = SwaggerEnabled ? SwaggerConfig!.BuildOpenApiDocument(_openApiSecurityScheme) : null; } public IConfiguration Configuration { get; } public EndpointConfiguration EndpointConfiguration { get; } public AuthenticationConfiguration? AuthConfig => EndpointConfiguration?.Authentication; public bool AuthEnabled => AuthConfig is AuthenticationConfiguration; public SwaggerConfiguration? SwaggerConfig => EndpointConfiguration?.Swagger; public bool SwaggerEnabled => SwaggerConfig?.Enabled ?? false; public void Configure(IApplicationBuilder app, ILogger<Program> logger) { app.UseRouting(); if (SwaggerEnabled) { app.UseSwaggerUI(setup => { setup.RoutePrefix = string.Empty; setup.SwaggerEndpoint( _apiDocumentPath, string.IsNullOrEmpty(SwaggerConfig?.Title) ? _defaultTitle : SwaggerConfig.Title); }); } if (EndpointConfiguration is EndpointConfiguration) { ConfigureEndpoints(app, logger); } else { ConfigureFallbackEndpoint(app, logger); } } private void ConfigureEndpoints(IApplicationBuilder app, ILogger logger) { app.UseEndpoints(endpoints => { if (EndpointConfiguration?.Endpoints?.Any() ?? false) { foreach (var endpointDefinition in EndpointConfiguration.Endpoints) { endpoints.MapGet(endpointDefinition.EndpointPath, async context => { await HandleRequestAsync(context, endpointDefinition, logger); }); if (SwaggerEnabled && _openApiDocument is OpenApiDocument) { _openApiDocument.AddOpenApiPathItem(endpointDefinition, _openApiSecurityScheme); } } if (AuthConfig?.AuthType == AuthType.Jwt) { endpoints.MapPost(_loginEndpoint, async context => { await HanldeLoginAsync(context, logger); }); if (SwaggerEnabled && _openApiDocument is OpenApiDocument) { _openApiDocument.AddLoginApiPathItem(_loginEndpoint); } } } if (SwaggerEnabled && _openApiDocument is OpenApiDocument) { var openApiDocumentJson = _openApiDocument.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0); endpoints.MapGet(_apiDocumentPath, async context => await context.WriteResponseAsync(openApiDocumentJson, HttpStatusCode.OK)); } endpoints.MapFallback(async context => await context.WriteErrorResponseAsync("Invalid Endpoint")); }); } private async Task HandleRequestAsync(HttpContext context, EndpointDefinition endpointDefinition, ILogger logger) { try { var credentials = AuthEnabled ? Credentials.Authenticate(context, AuthConfig!) : null; var parameterValues = RequestParameterValues.ResolveParameters(context, endpointDefinition); using var requestDbConnection = RequestDbConnection.GetRequestDbConnection(EndpointConfiguration, credentials); using var requestHandler = RequestHandler.GetRequestHandler(endpointDefinition, requestDbConnection, parameterValues); var items = await requestHandler.HandleRequestAsync(); await context.WriteResponseAsync(new { Items = items }, HttpStatusCode.OK); } catch (Exception e) { logger.LogError(e, e.Message); await context.WriteErrorResponseAsync(e); } } private async Task HanldeLoginAsync(HttpContext context, ILogger logger) { try { var credentialData = await context.ReadModelAsync<Dictionary<string, string>>(); var credentials = new Credentials(credentialData); using var requestDbConnection = RequestDbConnection.GetRequestDbConnection(EndpointConfiguration, credentials); var loginOk = await requestDbConnection.TestLoginAsync(); if (loginOk) { var tokens = credentials.Login(AuthConfig!); await context.WriteResponseAsync(tokens, HttpStatusCode.OK); } else { await context.WriteResponseAsync(new { Error = "Invalid Credentials" }, HttpStatusCode.Unauthorized); } } catch (Exception e) { logger.LogError(e, e.Message); await context.WriteErrorResponseAsync(e); } } private void ConfigureFallbackEndpoint(IApplicationBuilder app, ILogger logger) { logger.LogError("Incomplete or invalid configuration"); app.UseEndpoints(endpoints => { endpoints.MapFallback(async context => await context.WriteErrorResponseAsync("Incomplete or invalid configuration")); }); } } }
37.319149
134
0.578677
[ "Apache-2.0" ]
Vake93/QuickAPI
src/Startup.cs
7,016
C#
using System; using FluentAssertions; using JsonApiDotNetCore; using JsonApiDotNetCore.Resources; using Xunit; namespace UnitTests.Internal { public sealed class TypeExtensionsTests { [Fact] public void Implements_Returns_True_If_Type_Implements_Interface() { // Arrange Type type = typeof(Model); // Act bool result = type.IsOrImplementsInterface<IIdentifiable>(); // Assert result.Should().BeTrue(); } [Fact] public void Implements_Returns_False_If_Type_DoesNot_Implement_Interface() { // Arrange Type type = typeof(string); // Act bool result = type.IsOrImplementsInterface<IIdentifiable>(); // Assert result.Should().BeFalse(); } private sealed class Model : IIdentifiable { public string? StringId { get; set; } public string? LocalId { get; set; } } } }
23.522727
82
0.571981
[ "MIT" ]
agentilo/JsonApiDotNetCore
test/UnitTests/Internal/TypeExtensionsTests.cs
1,035
C#
//****************************************************************************************************** // PointIdMatchFilter.cs - Gbtc // // Copyright © 2014, Grid Protection Alliance. All Rights Reserved. // // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See // the NOTICE file distributed with this work for additional information regarding copyright ownership. // The GPA licenses this file to you under the MIT License (MIT), the "License"; you may // not use this file except in compliance with the License. You may obtain a copy of the License at: // // http://opensource.org/licenses/MIT // // Unless agreed to in writing, the subject software distributed under the License is distributed on an // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the // License for the specific language governing permissions and limitations. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 11/09/2013 - Steven E. Chisholm // Generated original version of source code. // 11/25/2014 - J. Ritchie Carroll // Added single point ID matching filter. // //****************************************************************************************************** using System.Collections.Generic; using System.Data; using System.Linq; using System.Runtime.CompilerServices; using GSF.IO; using GSF.Snap.Types; namespace GSF.Snap.Filters { public partial class PointIdMatchFilter { /// <summary> /// Creates a filter from the provided <paramref name="pointID"/>. /// </summary> /// <param name="pointID">Point ID to include in the filter.</param> public static MatchFilterBase<TKey, TValue> CreateFromPointID<TKey, TValue>(ulong pointID) where TKey : TimestampPointIDBase<TKey>, new() { if (pointID < 8 * 1024 * 64) // 64KB of space, 524288 return new BitArrayFilter<TKey, TValue>(new[] { pointID }, pointID); if (pointID <= uint.MaxValue) return new UIntHashSet<TKey, TValue>(new[] { pointID }, pointID); return new ULongHashSet<TKey, TValue>(new[] { pointID }, pointID); } /// <summary> /// Creates a filter from the list of points provided. /// </summary> /// <param name="listOfPointIDs">contains the list of pointIDs to include in the filter. List must support multiple enumerations</param> /// <returns></returns> public static MatchFilterBase<TKey, TValue> CreateFromList<TKey, TValue>(IEnumerable<ulong> listOfPointIDs) where TKey : TimestampPointIDBase<TKey>, new() { MatchFilterBase<TKey, TValue> filter; ulong maxValue = 0; if (listOfPointIDs.Any()) maxValue = listOfPointIDs.Max(); if (maxValue < 8 * 1024 * 64) //64KB of space, 524288 { filter = new BitArrayFilter<TKey, TValue>(listOfPointIDs, maxValue); } else if (maxValue <= uint.MaxValue) { filter = new UIntHashSet<TKey, TValue>(listOfPointIDs, maxValue); } else { filter = new ULongHashSet<TKey, TValue>(listOfPointIDs, maxValue); } return filter; } /// <summary> /// Loads a <see cref="QueryFilterPointId"/> from the provided <see cref="stream"/>. /// </summary> /// <param name="stream">The stream to load the filter from</param> /// <returns></returns> [MethodImpl(MethodImplOptions.NoOptimization)] private static MatchFilterBase<TKey, TValue> CreateFromStream<TKey, TValue>(BinaryStreamBase stream) where TKey : TimestampPointIDBase<TKey>, new() { MatchFilterBase<TKey, TValue> filter; byte version = stream.ReadUInt8(); ulong maxValue; int count; switch (version) { case 0: return null; case 1: maxValue = stream.ReadUInt64(); count = stream.ReadInt32(); if (maxValue < 8 * 1024 * 64) //64KB of space, 524288 { filter = new BitArrayFilter<TKey, TValue>(stream, count, maxValue); } else { filter = new UIntHashSet<TKey, TValue>(stream, count, maxValue); } break; case 2: maxValue = stream.ReadUInt64(); count = stream.ReadInt32(); filter = new ULongHashSet<TKey, TValue>(stream, count, maxValue); break; default: throw new VersionNotFoundException("Unknown Version"); } return filter; } } }
41.658537
144
0.541179
[ "MIT" ]
GridProtectionAlliance/openHistorian
Source/Libraries/GSF.SortedTreeStore/Snap/Filters/PointIdMatchFilter.cs
5,127
C#
using System.ComponentModel.DataAnnotations.Schema; using Xunit; namespace Dommel.Tests { public class LikeTests { [Fact] public void LikeOperandContains() { // Arrange var sqlExpression = new SqlExpression<Foo>(new SqlServerSqlBuilder()); // Act var expression = sqlExpression.Where(p => p.Bar.Contains("test")); var sql = expression.ToSql(out var dynamicParameters); // Assert Assert.Equal("where (lower([Bar]) like lower(@p1))", sql.Trim()); Assert.Single(dynamicParameters.ParameterNames); Assert.Equal("%test%", dynamicParameters.Get<string>("p1")); } [Fact] public void LikeOperandContainsVariable() { // Arrange var sqlExpression = new SqlExpression<Foo>(new SqlServerSqlBuilder()); var substring = "test"; // Act var expression = sqlExpression.Where(p => p.Bar.Contains(substring)); var sql = expression.ToSql(out var dynamicParameters); // Assert Assert.Equal("where (lower([Bar]) like lower(@p1))", sql.Trim()); Assert.Single(dynamicParameters.ParameterNames); Assert.Equal("%test%", dynamicParameters.Get<string>("p1")); } [Fact] public void LikeOperandStartsWith() { // Arrange var sqlExpression = new SqlExpression<Foo>(new SqlServerSqlBuilder()); // Act var expression = sqlExpression.Where(p => p.Bar.StartsWith("test")); var sql = expression.ToSql(out var dynamicParameters); // Assert Assert.Equal("where (lower([Bar]) like lower(@p1))", sql.Trim()); Assert.Single(dynamicParameters.ParameterNames); Assert.Equal("test%", dynamicParameters.Get<string>("p1")); } [Fact] public void LikeOperandEndsWith() { // Arrange var sqlExpression = new SqlExpression<Foo>(new SqlServerSqlBuilder()); // Act var expression = sqlExpression.Where(p => p.Bar.EndsWith("test")); var sql = expression.ToSql(out var dynamicParameters); // Assert Assert.Equal("where (lower([Bar]) like lower(@p1))", sql.Trim()); Assert.Single(dynamicParameters.ParameterNames); Assert.Equal("%test", dynamicParameters.Get<string>("p1")); } [Table("tblFoo")] public class Foo { public int Id { get; set; } public string Bar { get; set; } = ""; } } }
32.731707
82
0.557377
[ "MIT" ]
IQuixote/Dommel
test/Dommel.Tests/SqlExpressions/LikeTests.cs
2,686
C#
using System; using Castle.Facilities.Logging; using Abp; using Abp.Castle.Logging.Log4Net; using Abp.Collections.Extensions; using Abp.Dependency; namespace Acme.HeroShop.Migrator { public class Program { private static bool _quietMode; public static void Main(string[] args) { ParseArgs(args); using (var bootstrapper = AbpBootstrapper.Create<HeroShopMigratorModule>()) { bootstrapper.IocManager.IocContainer .AddFacility<LoggingFacility>( f => f.UseAbpLog4Net().WithConfig("log4net.config") ); bootstrapper.Initialize(); using (var migrateExecuter = bootstrapper.IocManager.ResolveAsDisposable<MultiTenantMigrateExecuter>()) { var migrationSucceeded = migrateExecuter.Object.Run(_quietMode); if (_quietMode) { // exit clean (with exit code 0) if migration is a success, otherwise exit with code 1 var exitCode = Convert.ToInt32(!migrationSucceeded); Environment.Exit(exitCode); } else { Console.WriteLine("Press ENTER to exit..."); Console.ReadLine(); } } } } private static void ParseArgs(string[] args) { if (args.IsNullOrEmpty()) { return; } foreach (var arg in args) { switch (arg) { case "-q": _quietMode = true; break; } } } } }
29.092308
119
0.462189
[ "MIT" ]
NHarendra/HeroShop
aspnet-core/src/Acme.HeroShop.Migrator/Program.cs
1,893
C#
using System; using System.Collections.Generic; using System.Numerics; using System.Text; namespace lcsclib { public class LCSCarcConverter { public struct ArcParams { public double center_x; public double center_y; public double radius; public double startAngle; public double endAngle; } public struct SvgArcPath { public double x1; public double y1; public double rx; public double ry; public double phi; public bool fA; public bool fS; public double x2; public double y2; } private static double Radian(double ux, double uy, double vx, double vy) { var dot = ux * vx + uy * vy; var mod = Math.Sqrt((ux * ux + uy * uy) * (vx * vx + vy * vy)); var rad = Math.Acos(dot / mod); if (ux * vy - uy * vx < 0.0) { rad = -rad; } return rad; } //conversion_from_endpoint_to_center_parameterization //sample : svgArcToCenterParam(200,200,50,50,0,1,1,300,200) // x1 y1 rx ry φ fA fS x2 y2 private static ArcParams SvgArcToArcParam(SvgArcPath svgArc) { double cx, cy, startAngle, deltaAngle, endAngle; var PIx2 = Math.PI * 2.0; if (svgArc.rx < 0) { svgArc.rx = -svgArc.rx; } if (svgArc.ry < 0) { svgArc.ry = -svgArc.ry; } if (svgArc.rx == 0.0 || svgArc.ry == 0.0) { // invalid arguments throw new Exception("rx and ry can not be 0"); } var s_phi = Math.Sin(svgArc.phi); var c_phi = Math.Cos(svgArc.phi); var hd_x = (svgArc.x1 - svgArc.x2) / 2.0; // half diff of x var hd_y = (svgArc.y1 - svgArc.y2) / 2.0; // half diff of y var hs_x = (svgArc.x1 + svgArc.x2) / 2.0; // half sum of x var hs_y = (svgArc.y1 + svgArc.y2) / 2.0; // half sum of y // F6.5.1 var x1_ = c_phi * hd_x + s_phi * hd_y; var y1_ = c_phi * hd_y - s_phi * hd_x; // F.6.6 Correction of out-of-range radii // Step 3: Ensure radii are large enough var lambda = (x1_ * x1_) / (svgArc.rx * svgArc.rx) + (y1_ * y1_) / (svgArc.ry * svgArc.ry); if (lambda > 1) { svgArc.rx *= Math.Sqrt(lambda); svgArc.ry *= Math.Sqrt(lambda); } var rxry = svgArc.rx * svgArc.ry; var rxy1_ = svgArc.rx * y1_; var ryx1_ = svgArc.ry * x1_; var sum_of_sq = rxy1_ * rxy1_ + ryx1_ * ryx1_; // sum of square if (sum_of_sq == 0) { throw new Exception("start point can not be same as end point"); } var coe = Math.Sqrt(Math.Abs((rxry * rxry - sum_of_sq) / sum_of_sq)); if (svgArc.fA == svgArc.fS) { coe = -coe; } // F6.5.2 var cx_ = coe * rxy1_ / svgArc.ry; var cy_ = -coe * ryx1_ / svgArc.rx; // F6.5.3 cx = c_phi * cx_ - s_phi * cy_ + hs_x; cy = s_phi * cx_ + c_phi * cy_ + hs_y; var xcr1 = (x1_ - cx_) / svgArc.rx; var xcr2 = (x1_ + cx_) / svgArc.rx; var ycr1 = (y1_ - cy_) / svgArc.ry; var ycr2 = (y1_ + cy_) / svgArc.ry; // F6.5.5 startAngle = Radian(1.0, 0.0, xcr1, ycr1); // F6.5.6 deltaAngle = Radian(xcr1, ycr1, -xcr2, -ycr2); while (deltaAngle > PIx2) { deltaAngle -= PIx2; } while (deltaAngle < 0.0) { deltaAngle += PIx2; } if (!svgArc.fS) { deltaAngle -= PIx2; } endAngle = startAngle + deltaAngle; while (endAngle > PIx2) { endAngle -= PIx2; } while (endAngle < 0.0) { endAngle += PIx2; } ArcParams outputObj = new ArcParams() { /* cx, cy, startAngle, deltaAngle */ center_x = cx, center_y = cy, startAngle = startAngle * (180 / Math.PI), endAngle = endAngle * (180 / Math.PI), radius = svgArc.rx }; return outputObj; } public static bool TryParseArcPath(string ArcPath, out SvgArcPath arc) { string[] strArray = ArcPath.Split(' '); if (strArray[0] == "M" && strArray[3] == "A") { double.TryParse(strArray[1], out arc.x1);//x1 double.TryParse(strArray[2], out arc.y1);//y1 double.TryParse(strArray[4], out arc.rx);//rx double.TryParse(strArray[5], out arc.ry);//ry double.TryParse(strArray[6], out arc.phi);//x-axis-rotation int.TryParse(strArray[7], out int fA);//large-arc-flag arc.fA = fA == 1; int.TryParse(strArray[8], out int fS);//sweep-flag arc.fS = fS == 1; double.TryParse(strArray[9], out arc.x2);//x2 double.TryParse(strArray[10], out arc.y2);//y2 return true; } else if (strArray[0].StartsWith("M") && strArray[2].StartsWith("A")) { double.TryParse(strArray[0][1..], out arc.x1);//x1 double.TryParse(strArray[1], out arc.y1);//y1 double.TryParse(strArray[2][1..], out arc.rx);//rx double.TryParse(strArray[3], out arc.ry);//ry double.TryParse(strArray[4], out arc.phi);//x-axis-rotation int.TryParse(strArray[5], out int fA);//large-arc-flag arc.fA = fA == 1; int.TryParse(strArray[6], out int fS);//sweep-flag arc.fS = fS == 1; double.TryParse(strArray[7], out arc.x2);//x2 double.TryParse(strArray[8], out arc.y2);//y2 return true; } else { string[] twoParts = ArcPath.Split('A'); if (twoParts[0].StartsWith("M")) { strArray = twoParts[0].Split(' '); double.TryParse(strArray[0][1..], out arc.x1); double.TryParse(strArray[1], out arc.y1); strArray = twoParts[1].Split(' '); double.TryParse(strArray[0], out arc.rx); double.TryParse(strArray[1], out arc.ry); double.TryParse(strArray[2], out arc.phi); int.TryParse(strArray[3], out int fA); arc.fA = fA == 1; int.TryParse(strArray[4], out int fS); arc.fS = fS == 1; double.TryParse(strArray[5], out arc.x2); double.TryParse(strArray[6], out arc.y2); return true; } } arc = new SvgArcPath(); return false; } public static ArcParams SvgArcPathToArc(SvgArcPath svgArc) { return SvgArcToArcParam(svgArc); } } }
38.051813
103
0.469771
[ "MIT" ]
alexgubanow/lcscToaltium
lcsclib/LCSCarcConverter.cs
7,347
C#
using System; using System.Text; namespace Surging.Cloud.CPlatform.Serialization.Implementation { /// <summary> /// 基于string类型的byte[]序列化器。 /// </summary> public class StringByteArraySerializer : ISerializer<byte[]> { #region Field private readonly ISerializer<string> _serializer; #endregion Field #region Constructor public StringByteArraySerializer(ISerializer<string> serializer) { _serializer = serializer; } #endregion Constructor #region Implementation of ISerializer<byte[]> /// <summary> /// 序列化。 /// </summary> /// <param name="instance">需要序列化的对象。</param> /// <returns>序列化之后的结果。</returns> public byte[] Serialize(object instance, bool camelCase = true, bool indented = false) { return Encoding.UTF8.GetBytes(_serializer.Serialize(instance,camelCase,indented)); } /// <summary> /// 反序列化。 /// </summary> /// <param name="content">序列化的内容。</param> /// <param name="type">对象类型。</param> /// <returns>一个对象实例。</returns> public object Deserialize(byte[] content, Type type, bool camelCase = true, bool indented = false) { return _serializer.Deserialize(Encoding.UTF8.GetString(content), type, camelCase, indented); } #endregion Implementation of ISerializer<byte[]> } }
28.54902
106
0.600962
[ "MIT" ]
microserviceframe/surging.cloud-new
src/Surging.Cloud/Surging.Cloud.CPlatform/Serialization/Implementation/StringByteArraySerializer.cs
1,570
C#
//****************************************************************************************************** // GetPointStream.cs - Gbtc // // Copyright © 2014, Grid Protection Alliance. All Rights Reserved. // // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See // the NOTICE file distributed with this work for additional information regarding copyright ownership. // The GPA licenses this file to you under the MIT License (MIT), the "License"; you may // not use this file except in compliance with the License. You may obtain a copy of the License at: // // http://opensource.org/licenses/MIT // // Unless agreed to in writing, the subject software distributed under the License is distributed on an // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the // License for the specific language governing permissions and limitations. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 8/7/2013 - Steven E. Chisholm // Generated original version of source code. // //****************************************************************************************************** using System; using System.Collections.Generic; using System.Linq; using GSF.Collections; using GSF.Snap; using GSF.Snap.Services.Reader; using GSF.Snap.Filters; using openHistorian.Snap; namespace openHistorian.Data.Query { /// <summary> /// A helper way to read data from a stream. /// </summary> [Obsolete("This will soon be removed")] public class PointStream : TreeStream<HistorianKey, HistorianValue> { IDatabaseReader<HistorianKey, HistorianValue> m_reader; readonly TreeStream<HistorianKey, HistorianValue> m_stream; public PointStream(IDatabaseReader<HistorianKey, HistorianValue> reader, TreeStream<HistorianKey, HistorianValue> stream) { m_stream = stream; m_reader = reader; } public HistorianKey CurrentKey = new HistorianKey(); public HistorianValue CurrentValue = new HistorianValue(); public bool IsValid; public bool Read() { return Read(CurrentKey, CurrentValue); } protected override bool ReadNext(HistorianKey key, HistorianValue value) { if (m_stream.Read(CurrentKey, CurrentValue)) { IsValid = true; return true; } else { IsValid = false; return false; } } protected override void Dispose(bool disposing) { if (disposing) { m_reader.Dispose(); m_reader = null; } } } /// <summary> /// Queries a historian database for a set of signals. /// </summary> public static partial class GetPointStreamExtensionMethods { ///// <summary> ///// Gets frames from the historian as individual frames. ///// </summary> ///// <param name="database">the database to use</param> ///// <returns></returns> //public static SortedList<DateTime, FrameData> GetFrames(this SortedTreeEngineBase<HistorianKey, HistorianValue> database, DateTime timestamp) //{ // return database.GetFrames(SortedTreeEngineReaderOptions.Default, TimestampFilter.CreateFromRange<HistorianKey>(timestamp, timestamp), PointIDFilter.CreateAllKeysValid<HistorianKey>(), null); //} /// <summary> /// Gets frames from the historian as individual frames. /// </summary> /// <param name="database">the database to use</param> /// <returns></returns> public static PointStream GetPointStream(this IDatabaseReader<HistorianKey, HistorianValue> database, DateTime startTime, DateTime stopTime) { return database.GetPointStream(SortedTreeEngineReaderOptions.Default, TimestampSeekFilter.CreateFromRange<HistorianKey>(startTime, stopTime), null); } /// <summary> /// Gets frames from the historian as individual frames. /// </summary> /// <param name="database">the database to use</param> /// <returns></returns> public static PointStream GetPointStream(this IDatabaseReader<HistorianKey, HistorianValue> database, SeekFilterBase<HistorianKey> timestamps, params ulong[] points) { return database.GetPointStream(SortedTreeEngineReaderOptions.Default, timestamps, PointIdMatchFilter.CreateFromList<HistorianKey,HistorianValue>(points)); } /// <summary> /// Gets frames from the historian as individual frames. /// </summary> /// <param name="database">the database to use</param> /// <returns></returns> public static PointStream GetPointStream(this IDatabaseReader<HistorianKey, HistorianValue> database, DateTime startTime, DateTime stopTime, params ulong[] points) { return database.GetPointStream(SortedTreeEngineReaderOptions.Default, TimestampSeekFilter.CreateFromRange<HistorianKey>(startTime, stopTime), PointIdMatchFilter.CreateFromList<HistorianKey, HistorianValue>(points)); } ///// <summary> ///// Gets frames from the historian as individual frames. ///// </summary> ///// <param name="database">the database to use</param> ///// <returns></returns> //public static SortedList<DateTime, FrameData> GetFrames(this SortedTreeEngineBase<HistorianKey, HistorianValue> database) //{ // return database.GetFrames(QueryFilterTimestamp.CreateAllKeysValid(), QueryFilterPointId.CreateAllKeysValid(), SortedTreeEngineReaderOptions.Default); //} ///// <summary> ///// Gets frames from the historian as individual frames. ///// </summary> ///// <param name="database">the database to use</param> ///// <param name="timestamps">the timestamps to query for</param> ///// <returns></returns> //public static SortedList<DateTime, FrameData> GetFrames(this SortedTreeEngineBase<HistorianKey, HistorianValue> database, QueryFilterTimestamp timestamps) //{ // return database.GetFrames(timestamps, QueryFilterPointId.CreateAllKeysValid(), SortedTreeEngineReaderOptions.Default); //} /// <summary> /// Gets frames from the historian as individual frames. /// </summary> /// <param name="database">the database to use</param> /// <param name="timestamps">the timestamps to query for</param> /// <param name="points">the points to query</param> /// <returns></returns> public static PointStream GetPointStream(this IDatabaseReader<HistorianKey, HistorianValue> database, SeekFilterBase<HistorianKey> timestamps, MatchFilterBase<HistorianKey, HistorianValue> points) { return database.GetPointStream(SortedTreeEngineReaderOptions.Default, timestamps, points); } /// <summary> /// Gets frames from the historian as individual frames. /// </summary> /// <param name="database">the database to use</param> /// <param name="timestamps">the timestamps to query for</param> /// <param name="points">the points to query</param> /// <param name="options">A list of query options</param> /// <returns></returns> public static PointStream GetPointStream(this IDatabaseReader<HistorianKey, HistorianValue> database, SortedTreeEngineReaderOptions options, SeekFilterBase<HistorianKey> timestamps, MatchFilterBase<HistorianKey, HistorianValue> points) { return new PointStream(database, database.Read(options, timestamps, points)); } class FrameDataConstructor { public readonly List<ulong> PointId = new List<ulong>(); public readonly List<HistorianValueStruct> Values = new List<HistorianValueStruct>(); public FrameData ToFrameData() { return new FrameData(PointId, Values); } } /// <summary> /// Gets concentrated frames from the provided stream /// </summary> /// <param name="stream">the database to use</param> /// <returns></returns> public static SortedList<DateTime, FrameData> GetPointStream(this TreeStream<HistorianKey, HistorianValue> stream) { HistorianKey key = new HistorianKey(); HistorianValue value = new HistorianValue(); SortedList<DateTime, FrameDataConstructor> results = new SortedList<DateTime, FrameDataConstructor>(); ulong lastTime = ulong.MinValue; FrameDataConstructor lastFrame = null; while (stream.Read(key,value)) { if (lastFrame is null || key.Timestamp != lastTime) { lastTime = key.Timestamp; DateTime timestamp = new DateTime((long)lastTime); if (!results.TryGetValue(timestamp, out lastFrame)) { lastFrame = new FrameDataConstructor(); results.Add(timestamp, lastFrame); } } lastFrame.PointId.Add(key.PointID); lastFrame.Values.Add(value.ToStruct()); } List<FrameData> data = new List<FrameData>(results.Count); data.AddRange(results.Values.Select(x => x.ToFrameData())); return SortedListConstructor.Create(results.Keys, data); } } }
43.414097
227
0.617047
[ "MIT" ]
GridProtectionAlliance/openHistorian
Source/Libraries/openHistorian.Core/Data/Query/GetPointStream.cs
9,858
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.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace Microsoft.Rest.ClientRuntime.Tests.Fakes { public class FakeHttpHandler : HttpClientHandler { public FakeHttpHandler() { StatusCodeToReturn = HttpStatusCode.InternalServerError; NumberOfTimesToFail = int.MaxValue; } public int NumberOfTimesToFail { get; set; } public int NumberOfTimesFailedSoFar { get; private set; } public HttpStatusCode StatusCodeToReturn { get; set; } protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var response = new HttpResponseMessage(HttpStatusCode.OK); if (NumberOfTimesToFail > NumberOfTimesFailedSoFar) { response = new HttpResponseMessage(StatusCodeToReturn); NumberOfTimesFailedSoFar++; } return Task.Run(() => response); } } }
31.179487
95
0.665296
[ "MIT" ]
216Giorgiy/azure-sdk-for-net
src/SdkCommon/ClientRuntime/ClientRuntime.Tests/Fakes/FakeHttpHandler.cs
1,218
C#
/* * Copyright (c) 2015-2016 EdonGashi * https://github.com/EdonGashi/ShipScript */ using System; namespace hmV8DynamicNS { public class ModuleExports : Attribute { } }
13.357143
42
0.673797
[ "Apache-2.0" ]
komiyamma/hm_ecmascript
hmV8.src/hmJSStaticLib/ClearScript/Extension/Annotations/ModuleExports.cs
189
C#
namespace Donker.Hmac.ExampleServer.Models { public class ExampleModel { public string Value { get; set; } } }
18.714286
43
0.641221
[ "MIT" ]
Saritasa/hmac
Source/Example/Donker.Hmac.ExampleServer/Models/ExampleModel.cs
133
C#
using System; using System.Collections.Generic; using UnityEngine; using System.Linq; namespace ssjj_hack { public class Watcher : ModuleBase { private static Dictionary<string, RecordTicks> records = new Dictionary<string, RecordTicks>(); private static Vector2 scroll; private static Window window = new Window("监测", new Vector2(Screen.width - 1120, 10), new Vector2(700, 400), OnWindowGUI); public class RecordTicks { public long min = long.MaxValue; public long max; public long current; public long total; public long count; public long avg => total / count; public void SetCurrent(long val) { this.current = val; this.min = Math.Min(min, val); this.max = Math.Max(max, val); this.total += val; this.count++; } } public override void OnGUI() { base.OnGUI(); window.CallOnGUI(); } public static void OnWindowGUI() { if (records.Count <= 0) return; Color contentColor = GUI.contentColor; GUI.contentColor = Color.green; if (GUILayout.Button("清空记录", GUILayout.Width(64))) { records.Clear(); } scroll = GUILayout.BeginScrollView(scroll); GUI.contentColor = Color.white; var index = 0; foreach (var kv in records) { GUILayout.BeginHorizontal(); GUILayout.Label($"{++index}.", GUILayout.Width(20)); GUILayout.Label($"{kv.Key}", GUILayout.Width(200)); GUILayout.Label($"{kv.Value.current}", GUILayout.Width(60)); GUILayout.Label($"{kv.Value.min}", GUILayout.Width(60)); GUILayout.Label($"{kv.Value.max}", GUILayout.Width(60)); GUILayout.Label($"{kv.Value.avg}", GUILayout.Width(60)); GUILayout.Label($"{kv.Value.count}", GUILayout.Width(60)); GUILayout.Label($"{kv.Value.total}", GUILayout.Width(100)); GUILayout.EndHorizontal(); } GUILayout.EndScrollView(); GUI.contentColor = contentColor; } public static void Record(string key, long ticks) { if (!records.ContainsKey(key)) { records.Add(key, new RecordTicks()); } records[key].SetCurrent(ticks); } } }
32.097561
130
0.518237
[ "MIT" ]
Airahc/hack_ssjj
ssjj2_hack/ssjj_hack/Module/Watcher.cs
2,646
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace FactoryFactory.Tests.MicrosoftTests.Fakes { public class FakeDisposableCallbackInnerService : FakeDisposableCallbackService, IFakeMultipleService { public FakeDisposableCallbackInnerService(FakeDisposeCallback callback) : base(callback) { } } }
38.166667
111
0.759825
[ "MIT" ]
gitter-badger/factoryfactory
src/FactoryFactory.Tests/MicrosoftTests/Fakes/FakeDisposableCallbackInnerService.cs
458
C#
using Cuemon.AspNetCore.Configuration; using Cuemon.Configuration; using Microsoft.AspNetCore.Razor.TagHelpers; using Microsoft.Extensions.Options; namespace Cuemon.AspNetCore.Razor.TagHelpers { /// <summary> /// Provides a base-class for static content related <see cref="TagHelper"/> implementation in Razor for ASP.NET Core. /// </summary> /// <seealso cref="TagHelper" /> /// <seealso cref="IConfigurable{TOptions}" /> public abstract class CacheBustingTagHelper<TOptions> : TagHelper, IConfigurable<TOptions> where TOptions : TagHelperOptions, new() { /// <summary> /// Initializes a new instance of the <see cref="CdnTagHelper"/> class. /// </summary> /// <param name="setup">The <typeparamref name="TOptions"/> which need to be configured.</param> /// <param name="cacheBusting">An optional object implementing the <see cref="ICacheBusting"/> interface.</param> protected CacheBustingTagHelper(IOptions<TOptions> setup, ICacheBusting cacheBusting = null) { CacheBusting = cacheBusting; Options = setup.Value; } /// <summary> /// Gets the by constructor optional supplied object implementing the <see cref="ICacheBusting"/> interface. /// </summary> /// <value>The by constructor optional supplied object implementing the <see cref="ICacheBusting"/> interface.</value> protected ICacheBusting CacheBusting { get; } /// <summary> /// Gets a value indicating whether an object implementing the <see cref="ICacheBusting"/> interface is specified. /// </summary> /// <value><c>true</c> if an object implementing the <see cref="ICacheBusting"/> interface is specified; otherwise, <c>false</c>.</value> protected bool UseCacheBusting => CacheBusting != null; /// <summary> /// Gets the configured options of this instance. /// </summary> /// <value>The configured options of this instance.</value> public TOptions Options { get; } } }
47.25
145
0.659452
[ "MIT" ]
gimlichael/Cuemon
src/Cuemon.AspNetCore.Razor.TagHelpers/CacheBustingTagHelper.cs
2,081
C#
namespace CrewChiefV4.PCars { public enum eAPIStructLengths { STRING_LENGTH_MAX = 64, NUM_PARTICIPANTS = 64 } }
17.375
33
0.640288
[ "MIT" ]
SHWotever/CrewChiefV4
CrewChiefV4/PCars/_eNums/eAPIStructLengths.cs
139
C#
using System; using System.Globalization; using System.Windows.Data; namespace BrightstarDB.Mobile.Tests { public class TypeNameConverter : IValueConverter { #region Implementation of IValueConverter /// <summary> /// Modifies the source data before passing it to the target for display in the UI. /// </summary> /// <returns> /// The value to be passed to the target dependency property. /// </returns> /// <param name="value">The source data being passed to the target.</param><param name="targetType">The <see cref="T:System.Type"/> of data expected by the target dependency property.</param><param name="parameter">An optional parameter to be used in the converter logic.</param><param name="culture">The culture of the conversion.</param> public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } #endregion #region Implementation of IValueConverter /// <summary> /// Modifies the target data before passing it to the source object. This method is called only in <see cref="F:System.Windows.Data.BindingMode.TwoWay"/> bindings. /// </summary> /// <returns> /// The value to be passed to the source object. /// </returns> /// <param name="value">The target data being passed to the source.</param><param name="targetType">The <see cref="T:System.Type"/> of data expected by the source object.</param><param name="parameter">An optional parameter to be used in the converter logic.</param><param name="culture">The culture of the conversion.</param> public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } #endregion } }
45.619048
347
0.665449
[ "MIT" ]
smkgeekfreak/BrightstarDB
src/mobile/BrightstarDB.Mobile.Tests/TypeNameConverter.cs
1,918
C#
using System.Collections.Generic; using AventStack.ExtentReports.Configuration; namespace AventStack.ExtentReports.Reporter.Configuration { public static class DefaultConfig { private static Dictionary<string, string> _configOptions = new Dictionary<string, string>() { { "encoding", "utf-8" }, { "protocol", "https" }, { "theme", "standard" }, { "documentTitle", "Extent Framework" }, { "reportName", "Extent Framework" }, { "js", "" }, { "css", "" }, { "enableCategoryView", "true" }, { "enableExceptionView", "true" }, { "enableAuthorView", "true" }, { "enableTestRunnerLogsView", "true" }, { "enableTimeline", "true" }, { "chartVisibleOnOpen", "true" } }; public static void InitializeManager(ConfigurationManager manager) { foreach (var option in _configOptions) { manager.AddConfig(option.Key, option.Value); } } } }
34.060606
100
0.519573
[ "Apache-2.0" ]
fean/extentreports-csharp
ExtentReports/Reporter/Configuration/Default/DefaultConfig.cs
1,124
C#
// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Microsoft.EntityFrameworkCore; namespace DryIoc.Facilities.EFCore { /// <summary> /// DbContext manager interface. The default /// DbContext lifestyle is per-transaction, so call OpenDbContext within a transaction! /// </summary> public interface IDbContextManager { /// <summary> /// Gets a new or existing DbContext depending on your context. /// </summary> /// <returns>A non-null DbContext.</returns> DbContext OpenDbContext(); /// <summary> /// Helper method for getting DbContext with specific type. Gets a new or existing DbContext depending on your context. /// </summary> /// <typeparam name="TDbContext"></typeparam> /// <returns>A non-null DbContext.</returns> TDbContext OpenDbContextTyped<TDbContext>() where TDbContext : DbContext; } }
37.421053
122
0.728551
[ "Apache-2.0" ]
Misterinecompany/DryIoc.Transactions
src/DryIoc.Facilities.EFCore/IDbContextManager.cs
1,422
C#
namespace TeamProjectFluxday.Data.Models { public class User { public User(string email, string password, string name) { Email = email; Password = password; Name = name; } public string Email { get; set; } public string Password { get; set; } public string Name { get; set; } } }
20
63
0.531579
[ "MIT" ]
ksolenkova/TeamProjectFluxday
TeamProjectFluxday/TeamProjectFluxday/Data/Models/User.cs
382
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Bot.Builder.Community.WebChatStyling { public enum CSSUnitCategory { Absolute, Relative } }
15.333333
46
0.708696
[ "MIT" ]
weretygr/BotRelated
libraries/Bot.Builder.Community.WebChatStyling/CSS/CSSUnitCategory.cs
232
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the securityhub-2018-10-26.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.SecurityHub.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.SecurityHub.Model.Internal.MarshallTransformations { /// <summary> /// AwsWafWebAclRule Marshaller /// </summary> public class AwsWafWebAclRuleMarshaller : IRequestMarshaller<AwsWafWebAclRule, JsonMarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="requestObject"></param> /// <param name="context"></param> /// <returns></returns> public void Marshall(AwsWafWebAclRule requestObject, JsonMarshallerContext context) { if(requestObject.IsSetAction()) { context.Writer.WritePropertyName("Action"); context.Writer.WriteObjectStart(); var marshaller = WafActionMarshaller.Instance; marshaller.Marshall(requestObject.Action, context); context.Writer.WriteObjectEnd(); } if(requestObject.IsSetExcludedRules()) { context.Writer.WritePropertyName("ExcludedRules"); context.Writer.WriteArrayStart(); foreach(var requestObjectExcludedRulesListValue in requestObject.ExcludedRules) { context.Writer.WriteObjectStart(); var marshaller = WafExcludedRuleMarshaller.Instance; marshaller.Marshall(requestObjectExcludedRulesListValue, context); context.Writer.WriteObjectEnd(); } context.Writer.WriteArrayEnd(); } if(requestObject.IsSetOverrideAction()) { context.Writer.WritePropertyName("OverrideAction"); context.Writer.WriteObjectStart(); var marshaller = WafOverrideActionMarshaller.Instance; marshaller.Marshall(requestObject.OverrideAction, context); context.Writer.WriteObjectEnd(); } if(requestObject.IsSetPriority()) { context.Writer.WritePropertyName("Priority"); context.Writer.Write(requestObject.Priority); } if(requestObject.IsSetRuleId()) { context.Writer.WritePropertyName("RuleId"); context.Writer.Write(requestObject.RuleId); } if(requestObject.IsSetType()) { context.Writer.WritePropertyName("Type"); context.Writer.Write(requestObject.Type); } } /// <summary> /// Singleton Marshaller. /// </summary> public readonly static AwsWafWebAclRuleMarshaller Instance = new AwsWafWebAclRuleMarshaller(); } }
34.392857
109
0.625649
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/SecurityHub/Generated/Model/Internal/MarshallTransformations/AwsWafWebAclRuleMarshaller.cs
3,852
C#
using JqueryDataTables.ServerSide.AspNetCoreWeb.Attributes; using JqueryDataTables.ServerSide.AspNetCoreWeb.Infrastructure; using JqueryDataTables.ServerSide.AspNetCoreWeb.Models; using Microsoft.AspNetCore.Razor.TagHelpers; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace JqueryDataTables.ServerSide.AspNetCoreWeb.TagHelpers { [HtmlTargetElement("jquery-datatables", Attributes = "id,class,model")] public class JqueryDataTablesTagHelper : TagHelper { public string Id { get; set; } public string Class { get; set; } public object Model { get; set; } [HtmlAttributeName("enable-searching")] public bool EnableSearching { get; set; } [HtmlAttributeName("thead-class")] public string TheadClass { get; set; } [HtmlAttributeName("search-row-th-class")] public string SearchRowThClass { get; set; } [HtmlAttributeName("search-input-class")] public string SearchInputClass { get; set; } [HtmlAttributeName("search-input-style")] public string SearchInputStyle { get; set; } [HtmlAttributeName("search-input-placeholder-prefix")] public string SearchInputPlaceholderPrefix { get; set; } public override void Process(TagHelperContext context, TagHelperOutput output) { output.TagName = "table"; output.Attributes.Add("id", Id); output.Attributes.Add("class", Class); output.PreContent.SetHtmlContent($@"<thead class=""{TheadClass}"">"); var headerRow = new StringBuilder(); var searchRow = new StringBuilder(); headerRow.AppendLine("<tr>"); if (EnableSearching) { searchRow.AppendLine("<tr>"); } var columns = GetColumnsFromModel(Model.GetType()).Where(c => !c.Exclude).OrderBy(c => c.Order); foreach (var column in columns) { headerRow.AppendLine($"<th>{column.Name}</th>"); if (!EnableSearching) { continue; } searchRow.AppendLine($@"<th class=""{SearchRowThClass}""><span class=""sr-only"">{column.Name}</span>"); if (column.HasSearch) { searchRow.AppendLine($@"<input type=""search"" style=""{SearchInputStyle}"" class=""{SearchInputClass}"" placeholder=""{SearchInputPlaceholderPrefix} {column.Name}"" aria-label=""{column.Name}"" />"); } searchRow.AppendLine("</th>"); } headerRow.AppendLine("</tr>"); if (EnableSearching) { searchRow.AppendLine("</tr>"); } output.Content.SetHtmlContent($"{headerRow.ToString()}{searchRow.ToString()}"); output.PostContent.SetHtmlContent("</thead>"); } private static IEnumerable<TableColumn> GetColumnsFromModel(Type parentClass) { var complexProperties = parentClass.GetProperties() .Where(p => p.GetCustomAttributes<NestedSortableAttribute>().Any() || p.GetCustomAttributes<NestedSearchableAttribute>().Any()); var properties = parentClass.GetProperties(); foreach (var prop in properties.Except(complexProperties)) { var jqueryDataTableColumn = prop.GetCustomAttribute<JqueryDataTableColumnAttribute>(); yield return new TableColumn { Name = ExpressionHelper.GetPropertyDisplayName(prop), HasSearch = prop.GetCustomAttributes<SearchableAttribute>().Any(), Order = jqueryDataTableColumn != null ? jqueryDataTableColumn.Order : 0, Exclude = jqueryDataTableColumn != null ? jqueryDataTableColumn.Exclude : true }; } if (complexProperties.Any()) { foreach (var parentProperty in complexProperties) { var parentType = parentProperty.PropertyType; var nestedProperties = GetColumnsFromModel(parentType); foreach (var nestedProperty in nestedProperties) { yield return nestedProperty; } } } } } }
36.322581
220
0.584147
[ "MIT" ]
UseMuse/JqueryDataTablesServerSide
AspNetCoreWeb/TagHelpers/JqueryDataTablesTagHelper.cs
4,506
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the devops-guru-2020-12-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.DevOpsGuru.Model { /// <summary> /// Information about a reactive insight. This object is returned by <code>DescribeInsight.</code> /// </summary> public partial class ReactiveInsightSummary { private string _id; private InsightTimeRange _insightTimeRange; private string _name; private ResourceCollection _resourceCollection; private ServiceCollection _serviceCollection; private InsightSeverity _severity; private InsightStatus _status; /// <summary> /// Gets and sets the property Id. /// <para> /// The ID of a reactive summary. /// </para> /// </summary> [AWSProperty(Min=1, Max=100)] public string Id { get { return this._id; } set { this._id = value; } } // Check to see if Id property is set internal bool IsSetId() { return this._id != null; } /// <summary> /// Gets and sets the property InsightTimeRange. /// </summary> public InsightTimeRange InsightTimeRange { get { return this._insightTimeRange; } set { this._insightTimeRange = value; } } // Check to see if InsightTimeRange property is set internal bool IsSetInsightTimeRange() { return this._insightTimeRange != null; } /// <summary> /// Gets and sets the property Name. /// <para> /// The name of a reactive insight. /// </para> /// </summary> [AWSProperty(Min=1, Max=530)] public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } /// <summary> /// Gets and sets the property ResourceCollection. /// </summary> public ResourceCollection ResourceCollection { get { return this._resourceCollection; } set { this._resourceCollection = value; } } // Check to see if ResourceCollection property is set internal bool IsSetResourceCollection() { return this._resourceCollection != null; } /// <summary> /// Gets and sets the property ServiceCollection. /// <para> /// A collection of the names of AWS services. /// </para> /// </summary> public ServiceCollection ServiceCollection { get { return this._serviceCollection; } set { this._serviceCollection = value; } } // Check to see if ServiceCollection property is set internal bool IsSetServiceCollection() { return this._serviceCollection != null; } /// <summary> /// Gets and sets the property Severity. /// <para> /// The severity of a reactive insight. /// </para> /// </summary> public InsightSeverity Severity { get { return this._severity; } set { this._severity = value; } } // Check to see if Severity property is set internal bool IsSetSeverity() { return this._severity != null; } /// <summary> /// Gets and sets the property Status. /// <para> /// The status of a reactive insight. /// </para> /// </summary> public InsightStatus Status { get { return this._status; } set { this._status = value; } } // Check to see if Status property is set internal bool IsSetStatus() { return this._status != null; } } }
28.784431
109
0.567506
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/DevOpsGuru/Generated/Model/ReactiveInsightSummary.cs
4,807
C#
// <copyright file="PlayerStats.cs" company="Google Inc."> // Copyright (C) 2015 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> #if UNITY_ANDROID namespace GooglePlayGames.BasicApi { using System; /// <summary> /// Player stats. See https://developers.google.com/games/services/android/stats /// </summary> public class PlayerStats { private static float UNSET_VALUE = -1.0f; /// <summary> /// If this PlayerStats object is valid (i.e. successfully retrieved from games services). /// </summary> /// <remarks> /// Note that a PlayerStats with all stats unset may still be valid. /// </remarks> public bool Valid { get; set; } /// <summary> /// The number of in-app purchases. /// </summary> public int NumberOfPurchases { get; set; } /// <summary> /// The length of the avg sesson in minutes. /// </summary> public float AvgSessonLength { get; set; } /// <summary> /// The days since last played. /// </summary> public int DaysSinceLastPlayed { get; set; } /// <summary> /// The number of sessions based on sign-ins. /// </summary> public int NumberOfSessions { get; set; } /// <summary> /// The approximation of sessions percentile for the player. /// </summary> /// <remarks> /// This value is given as a decimal value between 0 and 1 (inclusive). /// It indicates how many sessions the current player has /// played in comparison to the rest of this game's player base. /// Higher numbers indicate that this player has played more sessions. /// A return value less than zero indicates this value is not available. /// </remarks> public float SessPercentile { get; set; } /// <summary> /// The approximate spend percentile of the player. /// </summary> /// <remarks> /// This value is given as a decimal value between 0 and 1 (inclusive). /// It indicates how much the current player has spent in /// comparison to the rest of this game's player base. Higher /// numbers indicate that this player has spent more. /// A return value less than zero indicates this value is not available. /// </remarks> public float SpendPercentile { get; set; } /// <summary> /// The approximate probability of the player choosing to spend in this game. /// </summary> /// <remarks> /// This value is given as a decimal value between 0 and 1 (inclusive). /// Higher values indicate that a player is more likely to spend. /// A return value less than zero indicates this value is not available. /// </remarks> public float SpendProbability { get; set; } /// <summary> /// The approximate probability of the player not returning to play the game. /// </summary> /// <remarks> /// Higher values indicate that a player is less likely to return. /// A return value less than zero indicates this value is not available. /// </remarks> public float ChurnProbability { get; set; } /// <summary> /// The high spender probability of this player. /// </summary> public float HighSpenderProbability { get; set; } /// <summary> /// The predicted total spend of this player over the next 28 days. /// </summary> public float TotalSpendNext28Days { get; set; } /// <summary> /// Initializes a new instance of the <see cref="GooglePlayGames.BasicApi.PlayerStats"/> class. /// Sets all values to -1. /// </summary> public PlayerStats() { Valid = false; } /// <summary> /// Determines whether this instance has NumberOfPurchases. /// </summary> /// <returns><c>true</c> if this instance has NumberOfPurchases; otherwise, <c>false</c>.</returns> public bool HasNumberOfPurchases() { return NumberOfPurchases != (int)UNSET_VALUE; } /// <summary> /// Determines whether this instance has AvgSessonLength. /// </summary> /// <returns><c>true</c> if this instance has AvgSessonLength; otherwise, <c>false</c>.</returns> public bool HasAvgSessonLength() { return AvgSessonLength != UNSET_VALUE; } /// <summary> /// Determines whether this instance has DaysSinceLastPlayed. /// </summary> /// <returns><c>true</c> if this instance has DaysSinceLastPlayed; otherwise, <c>false</c>.</returns> public bool HasDaysSinceLastPlayed() { return DaysSinceLastPlayed != (int)UNSET_VALUE; } /// <summary> /// Determines whether this instance has NumberOfSessions. /// </summary> /// <returns><c>true</c> if this instance has NumberOfSessions; otherwise, <c>false</c>.</returns> public bool HasNumberOfSessions() { return NumberOfSessions != (int)UNSET_VALUE; } /// <summary> /// Determines whether this instance has SessPercentile. /// </summary> /// <returns><c>true</c> if this instance has SessPercentile; otherwise, <c>false</c>.</returns> public bool HasSessPercentile() { return SessPercentile != UNSET_VALUE; } /// <summary> /// Determines whether this instance has SpendPercentile. /// </summary> /// <returns><c>true</c> if this instance has SpendPercentile; otherwise, <c>false</c>.</returns> public bool HasSpendPercentile() { return SpendPercentile != UNSET_VALUE; } /// <summary> /// Determines whether this instance has ChurnProbability. /// </summary> /// <returns><c>true</c> if this instance has ChurnProbability; otherwise, <c>false</c>.</returns> public bool HasChurnProbability() { return ChurnProbability != UNSET_VALUE; } /// <summary> /// Determines whether this instance has HighSpenderProbability. /// </summary> /// <returns><c>true</c> if this instance has HighSpenderProbability; otherwise, <c>false</c>.</returns> public bool HasHighSpenderProbability() { return HighSpenderProbability != UNSET_VALUE; } /// <summary> /// Determines whether this instance has TotalSpendNext28Days. /// </summary> /// <returns><c>true</c> if this instance has TotalSpendNext28Days; otherwise, <c>false</c>.</returns> public bool HasTotalSpendNext28Days() { return TotalSpendNext28Days != UNSET_VALUE; } } } #endif
32.329268
112
0.562429
[ "Apache-2.0" ]
BUR58rus/play-games-plugin-for-unity
source/PluginDev/Assets/GooglePlayGames/BasicApi/PlayerStats.cs
7,955
C#
using Huobi.Client.Websocket.Clients.Streams; namespace Huobi.Client.Websocket.Clients { public interface IHuobiGenericWebsocketClient : IHuobiWebsocketClient<HuobiGenericClientStreams, object> { } }
26.625
108
0.798122
[ "Apache-2.0" ]
tiagosiebler/huobi-client-websocket
src/Huobi.Client.Websocket/Clients/IHuobiGenericWebsocketClient.cs
215
C#
namespace Gu.Persist.Core.Tests.Repositories { using System; using System.Runtime.Serialization.Formatters.Binary; using NUnit.Framework; public class RestoreExceptionTest { [Test] public void SerializationRoundtrip() { var exception = new RestoreException(new Exception("Save failed"), new Exception("Restore failed")); var binaryFormatter = new BinaryFormatter(); using (var steram = PooledMemoryStream.Borrow()) { binaryFormatter.Serialize(steram, exception); steram.Position = 0; var roundtripped = (RestoreException)binaryFormatter.Deserialize(steram); Assert.AreEqual("Save failed", roundtripped.SaveException.Message); Assert.NotNull(roundtripped.InnerException); Assert.AreEqual("Restore failed", roundtripped.InnerException.Message); } } } }
38.56
112
0.629668
[ "MIT" ]
forki/Gu.Persist
Gu.Persist.Core.Tests/Repositories/RestoreExceptionTest.cs
966
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the organizations-2016-11-28.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.Organizations.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Organizations.Model.Internal.MarshallTransformations { /// <summary> /// DescribePolicy Request Marshaller /// </summary> public class DescribePolicyRequestMarshaller : IMarshaller<IRequest, DescribePolicyRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((DescribePolicyRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(DescribePolicyRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.Organizations"); string target = "AWSOrganizationsV20161128.DescribePolicy"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2016-11-28"; request.HttpMethod = "POST"; string uriResourcePath = "/"; request.ResourcePath = uriResourcePath; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetPolicyId()) { context.Writer.WritePropertyName("PolicyId"); context.Writer.Write(publicRequest.PolicyId); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static DescribePolicyRequestMarshaller _instance = new DescribePolicyRequestMarshaller(); internal static DescribePolicyRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DescribePolicyRequestMarshaller Instance { get { return _instance; } } } }
35.419048
143
0.632428
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/Organizations/Generated/Model/Internal/MarshallTransformations/DescribePolicyRequestMarshaller.cs
3,719
C#
using System; using System.Collections.Generic; using System.Text; using Tricentis.Automation.WseToApiMigrationAddOn.Extensions; using Tricentis.Automation.WseToApiMigrationAddOn.Helper; using Tricentis.Automation.WseToApiMigrationAddOn.Migrator.Parser.Model; using Tricentis.Automation.WseToApiMigrationAddOn.Shared; using Tricentis.TCAPIObjects.Objects; namespace Tricentis.Automation.WseToApiMigrationAddOn.Migrator.Parser { /// <summary> /// Extracts data required for creation of Api Module creation from WSE Module. /// </summary> public class WseModuleParser : IWseArtifactsParser { #region Public Properties public string Endpoint { get; set; } public int HashCode { get; set; } public Dictionary<string, string> Headers { get; private set; } = new Dictionary<string, string>(); public string Method { get; set; } public Dictionary<string, string> PathParams { get; } = new Dictionary<string, string>(); public Dictionary<string, string> QueryParams { get; private set; } = new Dictionary<string, string>(); public string RequestPayload { get; set; } public string Resource { get; set; } public Dictionary<string, string> ResponseHeaders { get; private set; } = new Dictionary<string, string>(); public string ResponsePayload { get; set; } public string ResponseStatus { get; set; } #endregion #region Public Methods and Operators /// <summary> /// Parses WSE XModule to get data. /// </summary> /// <param name="wseModule">WSE XModule</param> public void Parse(XModule wseModule) { try { var methodParser = new MethodParser(); Method = methodParser.Parse(wseModule); var addressParser = new AddressParser(); AddressParserResult addressParserResult = addressParser.Parse(wseModule); Endpoint = addressParserResult.Endpoint; Resource = addressParserResult.Resource; QueryParams = addressParserResult.QueryParams; var headerParser = new HeaderParser(); Headers = headerParser.Parse(wseModule, AddOnConstants.RequestHeadersTql); Headers = CommonUtilities.ModifyContentTypeToEmpty(Headers); ResponseHeaders = headerParser.Parse(wseModule, AddOnConstants.ResponseHeadersTql); var payloadParser = new XmlPayloadParser(); RequestPayload = payloadParser.Parse(wseModule, AddOnConstants.RequestPayloadTql); ResponsePayload = payloadParser.Parse(wseModule, AddOnConstants.ResponsePayloadTql); var statusCodeParser = new StatusCodeParser(); ResponseStatus = statusCodeParser.ParseResponseStatus(wseModule); HashCode = GetHashCode(wseModule); } catch (Exception e) { FileLogger.Instance.Error(e); } } #endregion #region Methods private static int GetHashCode(XModule xModule) { var stringBuilder = new StringBuilder(); var treeObjects = xModule.Search("=>SUBPARTS:XModuleAttribute[Name==\"Request\"]=>SubAttributes"); foreach (var t in treeObjects) { stringBuilder.Append(t.DisplayedName); } return stringBuilder.ToString().GetHashCode(); } #endregion } }
37.340426
115
0.646154
[ "MIT" ]
Tricentis/WSEToAPIMigrator
src/WseToApiMigrationAddOn/Migrator/Parser/WseModuleParser.cs
3,512
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace Formulario { static class Program { /// <summary> /// Punto de entrada principal para la aplicación. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new frm_Principal()); } } }
23.652174
66
0.595588
[ "MIT" ]
AkeyiroDamar/Borrase-en-caso-de-reprobar
Formulario/Program.cs
547
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable enable using System.Diagnostics; using System.Text; namespace System.Net.Mime { internal static class MailBnfHelper { // characters allowed in atoms internal static readonly bool[] Atext = CreateCharactersAllowedInAtoms(); // characters allowed in quoted strings (not including Unicode) internal static readonly bool[] Qtext = CreateCharactersAllowedInQuotedStrings(); // characters allowed in domain literals internal static readonly bool[] Dtext = CreateCharactersAllowedInDomainLiterals(); // characters allowed in header names internal static readonly bool[] Ftext = CreateCharactersAllowedInHeaderNames(); // characters allowed in tokens internal static readonly bool[] Ttext = CreateCharactersAllowedInTokens(); // characters allowed inside of comments internal static readonly bool[] Ctext = CreateCharactersAllowedInComments(); internal const int Ascii7bitMaxValue = 127; internal const char Quote = '\"'; internal const char Space = ' '; internal const char Tab = '\t'; internal const char CR = '\r'; internal const char LF = '\n'; internal const char StartComment = '('; internal const char EndComment = ')'; internal const char Backslash = '\\'; internal const char At = '@'; internal const char EndAngleBracket = '>'; internal const char StartAngleBracket = '<'; internal const char StartSquareBracket = '['; internal const char EndSquareBracket = ']'; internal const char Comma = ','; internal const char Dot = '.'; // NOTE: See RFC 2822 for more detail. By default, every value in the array is false and only // those values which are allowed in that particular set are then set to true. The numbers // annotating each definition below are the range of ASCII values which are allowed in that definition. private static bool[] CreateCharactersAllowedInAtoms() { // atext = ALPHA / DIGIT / "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "/" / "=" / "?" / "^" / "_" / "`" / "{" / "|" / "}" / "~" var atext = new bool[128]; for (int i = '0'; i <= '9'; i++) { atext[i] = true; } for (int i = 'A'; i <= 'Z'; i++) { atext[i] = true; } for (int i = 'a'; i <= 'z'; i++) { atext[i] = true; } atext['!'] = true; atext['#'] = true; atext['$'] = true; atext['%'] = true; atext['&'] = true; atext['\''] = true; atext['*'] = true; atext['+'] = true; atext['-'] = true; atext['/'] = true; atext['='] = true; atext['?'] = true; atext['^'] = true; atext['_'] = true; atext['`'] = true; atext['{'] = true; atext['|'] = true; atext['}'] = true; atext['~'] = true; return atext; } private static bool[] CreateCharactersAllowedInQuotedStrings() { // fqtext = %d1-9 / %d11 / %d12 / %d14-33 / %d35-91 / %d93-127 var qtext = new bool[128]; for (int i = 1; i <= 9; i++) { qtext[i] = true; } qtext[11] = true; qtext[12] = true; for (int i = 14; i <= 33; i++) { qtext[i] = true; } for (int i = 35; i <= 91; i++) { qtext[i] = true; } for (int i = 93; i <= 127; i++) { qtext[i] = true; } return qtext; } private static bool[] CreateCharactersAllowedInDomainLiterals() { // fdtext = %d1-8 / %d11 / %d12 / %d14-31 / %d33-90 / %d94-127 var dtext = new bool[128]; for (int i = 1; i <= 8; i++) { dtext[i] = true; } dtext[11] = true; dtext[12] = true; for (int i = 14; i <= 31; i++) { dtext[i] = true; } for (int i = 33; i <= 90; i++) { dtext[i] = true; } for (int i = 94; i <= 127; i++) { dtext[i] = true; } return dtext; } private static bool[] CreateCharactersAllowedInHeaderNames() { // ftext = %d33-57 / %d59-126 var ftext = new bool[128]; for (int i = 33; i <= 57; i++) { ftext[i] = true; } for (int i = 59; i <= 126; i++) { ftext[i] = true; } return ftext; } private static bool[] CreateCharactersAllowedInTokens() { // ttext = %d33-126 except '()<>@,;:\"/[]?=' var ttext = new bool[128]; for (int i = 33; i <= 126; i++) { ttext[i] = true; } ttext['('] = false; ttext[')'] = false; ttext['<'] = false; ttext['>'] = false; ttext['@'] = false; ttext[','] = false; ttext[';'] = false; ttext[':'] = false; ttext['\\'] = false; ttext['"'] = false; ttext['/'] = false; ttext['['] = false; ttext[']'] = false; ttext['?'] = false; ttext['='] = false; return ttext; } private static bool[] CreateCharactersAllowedInComments() { // ctext- %d1-8 / %d11 / %d12 / %d14-31 / %33-39 / %42-91 / %93-127 var ctext = new bool[128]; for (int i = 1; i <= 8; i++) { ctext[i] = true; } ctext[11] = true; ctext[12] = true; for (int i = 14; i <= 31; i++) { ctext[i] = true; } for (int i = 33; i <= 39; i++) { ctext[i] = true; } for (int i = 42; i <= 91; i++) { ctext[i] = true; } for (int i = 93; i <= 127; i++) { ctext[i] = true; } return ctext; } internal static bool SkipCFWS(string data, ref int offset) { int comments = 0; for (; offset < data.Length; offset++) { if (data[offset] > 127) throw new FormatException(SR.Format(SR.MailHeaderFieldInvalidCharacter, data[offset])); else if (data[offset] == '\\' && comments > 0) offset += 2; else if (data[offset] == '(') comments++; else if (data[offset] == ')') comments--; else if (data[offset] != ' ' && data[offset] != '\t' && comments == 0) return true; if (comments < 0) { throw new FormatException(SR.Format(SR.MailHeaderFieldInvalidCharacter, data[offset])); } } //returns false if end of string return false; } internal static void ValidateHeaderName(string data) { int offset = 0; for (; offset < data.Length; offset++) { if (data[offset] > Ftext.Length || !Ftext[data[offset]]) throw new FormatException(SR.InvalidHeaderName); } if (offset == 0) throw new FormatException(SR.InvalidHeaderName); } internal static string? ReadQuotedString(string data, ref int offset, StringBuilder? builder) { return ReadQuotedString(data, ref offset, builder, false, false); } internal static string? ReadQuotedString(string data, ref int offset, StringBuilder? builder, bool doesntRequireQuotes, bool permitUnicodeInDisplayName) { // assume first char is the opening quote if (!doesntRequireQuotes) { ++offset; } int start = offset; StringBuilder localBuilder = (builder != null ? builder : new StringBuilder()); for (; offset < data.Length; offset++) { if (data[offset] == '\\') { localBuilder.Append(data, start, offset - start); start = ++offset; } else if (data[offset] == '"') { localBuilder.Append(data, start, offset - start); offset++; return (builder != null ? null : localBuilder.ToString()); } else if (data[offset] == '=' && data.Length > offset + 3 && data[offset + 1] == '\r' && data[offset + 2] == '\n' && (data[offset + 3] == ' ' || data[offset + 3] == '\t')) { //it's a soft crlf so it's ok offset += 3; } else if (permitUnicodeInDisplayName) { //if data contains Unicode and Unicode is permitted, then //it is valid in a quoted string in a header. if (data[offset] <= Ascii7bitMaxValue && !Qtext[data[offset]]) throw new FormatException(SR.Format(SR.MailHeaderFieldInvalidCharacter, data[offset])); } //not permitting Unicode, in which case Unicode is a formatting error else if (data[offset] > Ascii7bitMaxValue || !Qtext[data[offset]]) { throw new FormatException(SR.Format(SR.MailHeaderFieldInvalidCharacter, data[offset])); } } if (doesntRequireQuotes) { localBuilder.Append(data, start, offset - start); return (builder != null ? null : localBuilder.ToString()); } throw new FormatException(SR.MailHeaderFieldMalformedHeader); } internal static string? ReadParameterAttribute(string data, ref int offset, StringBuilder? builder) { if (!SkipCFWS(data, ref offset)) return null; // return ReadToken(data, ref offset, null); } internal static string ReadToken(string data, ref int offset, StringBuilder? builder) { int start = offset; for (; offset < data.Length; offset++) { if (data[offset] > Ascii7bitMaxValue) { throw new FormatException(SR.Format(SR.MailHeaderFieldInvalidCharacter, data[offset])); } else if (!Ttext[data[offset]]) { break; } } if (start == offset) { throw new FormatException(SR.Format(SR.MailHeaderFieldInvalidCharacter, data[offset])); } return data.Substring(start, offset - start); } private static readonly string?[] s_months = new string?[] { null, "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; internal static string? GetDateTimeString(DateTime value, StringBuilder? builder) { StringBuilder localBuilder = (builder != null ? builder : new StringBuilder()); localBuilder.Append(value.Day); localBuilder.Append(' '); localBuilder.Append(s_months[value.Month]); localBuilder.Append(' '); localBuilder.Append(value.Year); localBuilder.Append(' '); if (value.Hour <= 9) { localBuilder.Append('0'); } localBuilder.Append(value.Hour); localBuilder.Append(':'); if (value.Minute <= 9) { localBuilder.Append('0'); } localBuilder.Append(value.Minute); localBuilder.Append(':'); if (value.Second <= 9) { localBuilder.Append('0'); } localBuilder.Append(value.Second); string offset = TimeZoneInfo.Local.GetUtcOffset(value).ToString(); if (offset[0] != '-') { localBuilder.Append(" +"); } else { localBuilder.Append(' '); } string[] offsetFields = offset.Split(':'); localBuilder.Append(offsetFields[0]); localBuilder.Append(offsetFields[1]); return (builder != null ? null : localBuilder.ToString()); } internal static void GetTokenOrQuotedString(string data, StringBuilder builder, bool allowUnicode) { int offset = 0, start = 0; for (; offset < data.Length; offset++) { if (CheckForUnicode(data[offset], allowUnicode)) { continue; } if (!Ttext[data[offset]] || data[offset] == ' ') { builder.Append('"'); for (; offset < data.Length; offset++) { if (CheckForUnicode(data[offset], allowUnicode)) { continue; } else if (IsFWSAt(data, offset)) // Allow FWS == "\r\n " { // No-op, skip these three chars offset += 2; } else if (!Qtext[data[offset]]) { builder.Append(data, start, offset - start); builder.Append('\\'); start = offset; } } builder.Append(data, start, offset - start); builder.Append('"'); return; } } //always a quoted string if it was empty. if (data.Length == 0) { builder.Append("\"\""); } // Token, no quotes needed builder.Append(data); } private static bool CheckForUnicode(char ch, bool allowUnicode) { if (ch < Ascii7bitMaxValue) { return false; } if (!allowUnicode) { throw new FormatException(SR.Format(SR.MailHeaderFieldInvalidCharacter, ch)); } return true; } internal static bool IsAllowedWhiteSpace(char c) { // all allowed whitespace characters return c == Tab || c == Space || c == CR || c == LF; } internal static bool HasCROrLF(string data) { for (int i = 0; i < data.Length; i++) { if (data[i] == '\r' || data[i] == '\n') { return true; } } return false; } // Is there a FWS ("\r\n " or "\r\n\t") starting at the given index? internal static bool IsFWSAt(string data, int index) { Debug.Assert(index >= 0); Debug.Assert(index < data.Length); return (data[index] == MailBnfHelper.CR && index + 2 < data.Length && data[index + 1] == MailBnfHelper.LF && (data[index + 2] == MailBnfHelper.Space || data[index + 2] == MailBnfHelper.Tab)); } } }
37.942308
160
0.463951
[ "MIT" ]
06needhamt/runtime
src/libraries/Common/src/System/Net/Mail/MailBnfHelper.cs
15,784
C#
//------------------------------------------------------------------------------ // <auto-generated> // Ce code a été généré par un outil. // Version du runtime :4.0.30319.42000 // // Les modifications apportées à ce fichier peuvent provoquer un comportement incorrect et seront perdues si // le code est régénéré. // </auto-generated> //------------------------------------------------------------------------------ namespace TvDBCtrl.Properties { using System; /// <summary> /// Une classe de ressource fortement typée destinée, entre autres, à la consultation des chaînes localisées. /// </summary> // Cette classe a été générée automatiquement par la classe StronglyTypedResourceBuilder // à l'aide d'un outil, tel que ResGen ou Visual Studio. // Pour ajouter ou supprimer un membre, modifiez votre fichier .ResX, puis réexécutez ResGen // avec l'option /str ou régénérez votre projet VS. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Retourne l'instance ResourceManager mise en cache utilisée par cette classe. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("TvDBCtrl.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Remplace la propriété CurrentUICulture du thread actuel pour toutes /// les recherches de ressources à l'aide de cette classe de ressource fortement typée. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Recherche une ressource localisée de type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap loupe { get { object obj = ResourceManager.GetObject("loupe", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Recherche une ressource localisée de type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap viewresult { get { object obj = ResourceManager.GetObject("viewresult", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } } }
43.857143
174
0.606406
[ "MIT" ]
Chlorel/TvDBCtrl
TvDBCtrl/Properties/Resources.Designer.cs
3,720
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace HPlusSportsAPI.Controllers { [Produces("application/json")] [Route("api/OrderItems")] public class OrderItemsController : Controller { public OrderItemsController() { } [HttpGet] public IActionResult GetOrderItem() { return Ok(); } [HttpGet("{id}")] public IActionResult GetOrderItem([FromRoute] int id) { return Ok(); } [HttpPost] public IActionResult PostOrderItem([FromBody] Object obj) { return Ok(); } [HttpPut("{id}")] public IActionResult PutOrderItem([FromRoute] int id, [FromBody] Object obj) { return Ok(); } [HttpDelete("{id}")] public IActionResult DeleteOrderItem([FromRoute] int id) { return Ok(); } } }
21.653061
84
0.562677
[ "MIT" ]
Anwar-Ul-Haq/AGSports
AGSports/AGSports/Controllers/OrderItemsController.cs
1,063
C#
// Based on http://stackoverflow.com/a/32417530, Windows 10 SDK and github project VirtualDesktop using System; using System.Runtime.InteropServices; using System.ComponentModel; namespace VirtualDesktops { internal static class Guids { public static readonly Guid CLSID_ImmersiveShell = new Guid("C2F03A33-21F5-47FA-B4BB-156362A2F239"); public static readonly Guid CLSID_VirtualDesktopManagerInternal = new Guid("C5E0CDCA-7B6E-41B2-9FC4-D93975CC467B"); public static readonly Guid CLSID_VirtualDesktopManager = new Guid("AA509086-5CA9-4C25-8F95-589D3C07B48A"); public static readonly Guid CLSID_VirtualDesktopPinnedApps = new Guid("B5A399E7-1C87-46B8-88E9-FC5747B171BD"); } [StructLayout(LayoutKind.Sequential)] internal struct Size { public int X; public int Y; } [StructLayout(LayoutKind.Sequential)] internal struct Rect { public int Left; public int Top; public int Right; public int Bottom; } internal enum APPLICATION_VIEW_CLOAK_TYPE : int { AVCT_NONE = 0, AVCT_DEFAULT = 1, AVCT_VIRTUAL_DESKTOP = 2 } internal enum APPLICATION_VIEW_COMPATIBILITY_POLICY : int { AVCP_NONE = 0, AVCP_SMALL_SCREEN = 1, AVCP_TABLET_SMALL_SCREEN = 2, AVCP_VERY_SMALL_SCREEN = 3, AVCP_HIGH_SCALE_FACTOR = 4 } [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIInspectable)] [Guid("372E1D3B-38D3-42E4-A15B-8AB2B178F513")] internal interface IApplicationView { int SetFocus(); int SwitchTo(); int TryInvokeBack(IntPtr /* IAsyncCallback* */ callback); int GetThumbnailWindow(out IntPtr hwnd); int GetMonitor(out IntPtr /* IImmersiveMonitor */ immersiveMonitor); int GetVisibility(out int visibility); int SetCloak(APPLICATION_VIEW_CLOAK_TYPE cloakType, int unknown); int GetPosition(ref Guid guid /* GUID for IApplicationViewPosition */, out IntPtr /* IApplicationViewPosition** */ position); int SetPosition(ref IntPtr /* IApplicationViewPosition* */ position); int InsertAfterWindow(IntPtr hwnd); int GetExtendedFramePosition(out Rect rect); int GetAppUserModelId([MarshalAs(UnmanagedType.LPWStr)] out string id); int SetAppUserModelId(string id); int IsEqualByAppUserModelId(string id, out int result); int GetViewState(out uint state); int SetViewState(uint state); int GetNeediness(out int neediness); int GetLastActivationTimestamp(out ulong timestamp); int SetLastActivationTimestamp(ulong timestamp); int GetVirtualDesktopId(out Guid guid); int SetVirtualDesktopId(ref Guid guid); int GetShowInSwitchers(out int flag); int SetShowInSwitchers(int flag); int GetScaleFactor(out int factor); int CanReceiveInput(out bool canReceiveInput); int GetCompatibilityPolicyType(out APPLICATION_VIEW_COMPATIBILITY_POLICY flags); int SetCompatibilityPolicyType(APPLICATION_VIEW_COMPATIBILITY_POLICY flags); int GetSizeConstraints(IntPtr /* IImmersiveMonitor* */ monitor, out Size size1, out Size size2); int GetSizeConstraintsForDpi(uint uint1, out Size size1, out Size size2); int SetSizeConstraintsForDpi(ref uint uint1, ref Size size1, ref Size size2); int OnMinSizePreferencesUpdated(IntPtr hwnd); int ApplyOperation(IntPtr /* IApplicationViewOperation* */ operation); int IsTray(out bool isTray); int IsInHighZOrderBand(out bool isInHighZOrderBand); int IsSplashScreenPresented(out bool isSplashScreenPresented); int Flash(); int GetRootSwitchableOwner(out IApplicationView rootSwitchableOwner); int EnumerateOwnershipTree(out IObjectArray ownershipTree); int GetEnterpriseId([MarshalAs(UnmanagedType.LPWStr)] out string enterpriseId); int IsMirrored(out bool isMirrored); int Unknown1(out int unknown); int Unknown2(out int unknown); int Unknown3(out int unknown); int Unknown4(out int unknown); int Unknown5(out int unknown); int Unknown6(int unknown); int Unknown7(); int Unknown8(out int unknown); int Unknown9(int unknown); int Unknown10(int unknownX, int unknownY); int Unknown11(int unknown); int Unknown12(out Size size1); } [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("1841C6D7-4F9D-42C0-AF41-8747538F10E5")] internal interface IApplicationViewCollection { int GetViews(out IObjectArray array); int GetViewsByZOrder(out IObjectArray array); int GetViewsByAppUserModelId(string id, out IObjectArray array); int GetViewForHwnd(IntPtr hwnd, out IApplicationView view); int GetViewForApplication(object application, out IApplicationView view); int GetViewForAppUserModelId(string id, out IApplicationView view); int GetViewInFocus(out IntPtr view); int Unknown1(out IntPtr view); void RefreshCollection(); int RegisterForApplicationViewChanges(object listener, out int cookie); int UnregisterForApplicationViewChanges(int cookie); } [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("FF72FFDD-BE7E-43FC-9C03-AD81681E88E4")] internal interface IVirtualDesktop { bool IsViewVisible(IApplicationView view); Guid GetId(); } [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("F31574D6-B682-4CDC-BD56-1827860ABEC6")] internal interface IVirtualDesktopManagerInternal { int GetCount(); void MoveViewToDesktop(IApplicationView view, IVirtualDesktop desktop); bool CanViewMoveDesktops(IApplicationView view); IVirtualDesktop GetCurrentDesktop(); void GetDesktops(out IObjectArray desktops); [PreserveSig] int GetAdjacentDesktop(IVirtualDesktop from, int direction, out IVirtualDesktop desktop); void SwitchDesktop(IVirtualDesktop desktop); IVirtualDesktop CreateDesktop(); void RemoveDesktop(IVirtualDesktop desktop, IVirtualDesktop fallback); IVirtualDesktop FindDesktop(ref Guid desktopid); } [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("A5CD92FF-29BE-454C-8D04-D82879FB3F1B")] internal interface IVirtualDesktopManager { bool IsWindowOnCurrentVirtualDesktop(IntPtr topLevelWindow); Guid GetWindowDesktopId(IntPtr topLevelWindow); void MoveWindowToDesktop(IntPtr topLevelWindow, ref Guid desktopId); } [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("4CE81583-1E4C-4632-A621-07A53543148F")] internal interface IVirtualDesktopPinnedApps { bool IsAppIdPinned(string appId); void PinAppID(string appId); void UnpinAppID(string appId); bool IsViewPinned(IApplicationView applicationView); void PinView(IApplicationView applicationView); void UnpinView(IApplicationView applicationView); } [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("92CA9DCD-5622-4BBA-A805-5E9F541BD8C9")] internal interface IObjectArray { void GetCount(out int count); void GetAt(int index, ref Guid iid, [MarshalAs(UnmanagedType.Interface)] out object obj); } [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("6D5140C1-7436-11CE-8034-00AA006009FA")] internal interface IServiceProvider10 { [return: MarshalAs(UnmanagedType.IUnknown)] object QueryService(ref Guid service, ref Guid riid); } internal static class DesktopManager { private static readonly object serviceLock = new object(); private static IServiceProvider10 shell; private static IVirtualDesktopManagerInternal virtualDesktopManagerInternal; private static IVirtualDesktopManager virtualDesktopManager; private static IApplicationViewCollection applicationViewCollection; private static IVirtualDesktopPinnedApps virtualDesktopPinnedApps; static DesktopManager() { shell = (IServiceProvider10)Activator.CreateInstance(Type.GetTypeFromCLSID(Guids.CLSID_ImmersiveShell)); } internal static IVirtualDesktopManagerInternal VirtualDesktopManagerInternal { get { if (virtualDesktopManagerInternal == null) { lock (serviceLock) { if (virtualDesktopManagerInternal == null) virtualDesktopManagerInternal = (IVirtualDesktopManagerInternal)shell.QueryService(Guids.CLSID_VirtualDesktopManagerInternal, typeof(IVirtualDesktopManagerInternal).GUID); } } return virtualDesktopManagerInternal; } } internal static IVirtualDesktopManager VirtualDesktopManager { get { if (virtualDesktopManager == null) { lock (serviceLock) { if (virtualDesktopManager == null) virtualDesktopManager = (IVirtualDesktopManager)Activator.CreateInstance(Type.GetTypeFromCLSID(Guids.CLSID_VirtualDesktopManager)); } } return virtualDesktopManager; } } internal static IApplicationViewCollection ApplicationViewCollection { get { if (applicationViewCollection == null) { lock (serviceLock) { if (applicationViewCollection == null) applicationViewCollection = (IApplicationViewCollection)shell.QueryService(typeof(IApplicationViewCollection).GUID, typeof(IApplicationViewCollection).GUID); } } return applicationViewCollection; } } internal static IVirtualDesktopPinnedApps VirtualDesktopPinnedApps { get { if (virtualDesktopPinnedApps == null) { lock (serviceLock) { if (virtualDesktopPinnedApps == null) virtualDesktopPinnedApps = (IVirtualDesktopPinnedApps)shell.QueryService(Guids.CLSID_VirtualDesktopPinnedApps, typeof(IVirtualDesktopPinnedApps).GUID); } } return virtualDesktopPinnedApps; } } internal static IVirtualDesktop GetDesktop(int index) { // get desktop with index int count = VirtualDesktopManagerInternal.GetCount(); if (index < 0 || index >= count) throw new ArgumentOutOfRangeException("index"); IObjectArray desktops; VirtualDesktopManagerInternal.GetDesktops(out desktops); object objdesktop; desktops.GetAt(index, typeof(IVirtualDesktop).GUID, out objdesktop); Marshal.ReleaseComObject(desktops); return (IVirtualDesktop)objdesktop; } internal static int GetDesktopIndex(IVirtualDesktop desktop) { // get index of desktop int index = -1; Guid IdSearch = desktop.GetId(); IObjectArray desktops; VirtualDesktopManagerInternal.GetDesktops(out desktops); object objdesktop; for (int i = 0; i < VirtualDesktopManagerInternal.GetCount(); i++) { desktops.GetAt(i, typeof(IVirtualDesktop).GUID, out objdesktop); if (IdSearch.CompareTo(((IVirtualDesktop)objdesktop).GetId()) == 0) { index = i; break; } } Marshal.ReleaseComObject(desktops); return index; } internal static IApplicationView GetApplicationView(this IntPtr hWnd) { // get application view to window handle IApplicationView view; ApplicationViewCollection.GetViewForHwnd(hWnd, out view); return view; } internal static string GetAppId(IntPtr hWnd) { // get Application ID to window handle string appId; hWnd.GetApplicationView().GetAppUserModelId(out appId); return appId; } } public class Desktop { private IVirtualDesktop ivd; private Desktop(IVirtualDesktop desktop) { this.ivd = desktop; } public override int GetHashCode() { // Get hash return ivd.GetHashCode(); } public override bool Equals(object obj) { // Compares with object var desk = obj as Desktop; return desk != null && object.ReferenceEquals(this.ivd, desk.ivd); } public static int Count { // Returns the number of desktops get { return DesktopManager.VirtualDesktopManagerInternal.GetCount(); } } public static Desktop Current { // Returns current desktop get { return new Desktop(DesktopManager.VirtualDesktopManagerInternal.GetCurrentDesktop()); } } public static Desktop FromIndex(int index) { // Create desktop object from index 0..Count-1 return new Desktop(DesktopManager.GetDesktop(index)); } public static Desktop FromWindow(IntPtr hWnd) { // Creates desktop object on which window <hWnd> is displayed if (hWnd == IntPtr.Zero) throw new ArgumentNullException(); Guid id = DesktopManager.VirtualDesktopManager.GetWindowDesktopId(hWnd); return new Desktop(DesktopManager.VirtualDesktopManagerInternal.FindDesktop(ref id)); } public static int FromDesktop(Desktop desktop) { // Returns index of desktop object or -1 if not found return DesktopManager.GetDesktopIndex(desktop.ivd); } public static Desktop Create() { // Create a new desktop return new Desktop(DesktopManager.VirtualDesktopManagerInternal.CreateDesktop()); } public void Remove(Desktop fallback = null) { // Destroy desktop and switch to <fallback> IVirtualDesktop fallbackdesktop; if (fallback == null) { // if no fallback is given use desktop to the left except for desktop 0. Desktop dtToCheck = new Desktop(DesktopManager.GetDesktop(0)); if (this.Equals(dtToCheck)) { // desktop 0: set fallback to second desktop (= "right" desktop) DesktopManager.VirtualDesktopManagerInternal.GetAdjacentDesktop(ivd, 4, out fallbackdesktop); // 4 = RightDirection } else { // set fallback to "left" desktop DesktopManager.VirtualDesktopManagerInternal.GetAdjacentDesktop(ivd, 3, out fallbackdesktop); // 3 = LeftDirection } } else // set fallback desktop fallbackdesktop = fallback.ivd; DesktopManager.VirtualDesktopManagerInternal.RemoveDesktop(ivd, fallbackdesktop); } public bool IsVisible { // Returns <true> if this desktop is the current displayed one get { return object.ReferenceEquals(ivd, DesktopManager.VirtualDesktopManagerInternal.GetCurrentDesktop()); } } public void MakeVisible() { // Make this desktop visible DesktopManager.VirtualDesktopManagerInternal.SwitchDesktop(ivd); } public Desktop Left { // Returns desktop at the left of this one, null if none get { IVirtualDesktop desktop; int hr = DesktopManager.VirtualDesktopManagerInternal.GetAdjacentDesktop(ivd, 3, out desktop); // 3 = LeftDirection if (hr == 0) return new Desktop(desktop); else return null; } } public Desktop Right { // Returns desktop at the right of this one, null if none get { IVirtualDesktop desktop; int hr = DesktopManager.VirtualDesktopManagerInternal.GetAdjacentDesktop(ivd, 4, out desktop); // 4 = RightDirection if (hr == 0) return new Desktop(desktop); else return null; } } public void MoveWindow(IntPtr hWnd) { // Move window <hWnd> to this desktop int processId; if (hWnd == IntPtr.Zero) throw new ArgumentNullException(); GetWindowThreadProcessId(hWnd, out processId); if (System.Diagnostics.Process.GetCurrentProcess().Id == processId) { // window of process try // the easy way (if we are owner) { DesktopManager.VirtualDesktopManager.MoveWindowToDesktop(hWnd, ivd.GetId()); } catch // window of process, but we are not the owner { IApplicationView view; DesktopManager.ApplicationViewCollection.GetViewForHwnd(hWnd, out view); DesktopManager.VirtualDesktopManagerInternal.MoveViewToDesktop(view, ivd); } } else { // window of other process IApplicationView view; DesktopManager.ApplicationViewCollection.GetViewForHwnd(hWnd, out view); DesktopManager.VirtualDesktopManagerInternal.MoveViewToDesktop(view, ivd); } } public void MoveActiveWindow() { MoveWindow(GetForegroundWindow()); } public bool HasWindow(IntPtr hWnd) { // Returns true if window <hWnd> is on this desktop if (hWnd == IntPtr.Zero) throw new ArgumentNullException(); return ivd.GetId() == DesktopManager.VirtualDesktopManager.GetWindowDesktopId(hWnd); } public static bool IsWindowPinned(IntPtr hWnd) { // Returns true if window <hWnd> is pinned to all desktops if (hWnd == IntPtr.Zero) throw new ArgumentNullException(); return DesktopManager.VirtualDesktopPinnedApps.IsViewPinned(hWnd.GetApplicationView()); } public static void PinWindow(IntPtr hWnd) { // pin window <hWnd> to all desktops if (hWnd == IntPtr.Zero) throw new ArgumentNullException(); var view = hWnd.GetApplicationView(); if (!DesktopManager.VirtualDesktopPinnedApps.IsViewPinned(view)) { // pin only if not already pinned DesktopManager.VirtualDesktopPinnedApps.PinView(view); } } public static void UnpinWindow(IntPtr hWnd) { // unpin window <hWnd> from all desktops if (hWnd == IntPtr.Zero) throw new ArgumentNullException(); var view = hWnd.GetApplicationView(); if (DesktopManager.VirtualDesktopPinnedApps.IsViewPinned(view)) { // unpin only if not already unpinned DesktopManager.VirtualDesktopPinnedApps.UnpinView(view); } } public static bool IsApplicationPinned(IntPtr hWnd) { // Returns true if application for window <hWnd> is pinned to all desktops if (hWnd == IntPtr.Zero) throw new ArgumentNullException(); return DesktopManager.VirtualDesktopPinnedApps.IsAppIdPinned(DesktopManager.GetAppId(hWnd)); } public static void PinApplication(IntPtr hWnd) { // pin application for window <hWnd> to all desktops if (hWnd == IntPtr.Zero) throw new ArgumentNullException(); string appId = DesktopManager.GetAppId(hWnd); if (!DesktopManager.VirtualDesktopPinnedApps.IsAppIdPinned(appId)) { // pin only if not already pinned DesktopManager.VirtualDesktopPinnedApps.PinAppID(appId); } } public static void UnpinApplication(IntPtr hWnd) { // unpin application for window <hWnd> from all desktops if (hWnd == IntPtr.Zero) throw new ArgumentNullException(); var view = hWnd.GetApplicationView(); string appId = DesktopManager.GetAppId(hWnd); if (DesktopManager.VirtualDesktopPinnedApps.IsAppIdPinned(appId)) { // unpin only if already pinned DesktopManager.VirtualDesktopPinnedApps.UnpinAppID(appId); } } // Get process id to window handle [DllImport("user32.dll")] public static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId); // Get handle of active window [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow(); } }
41.291902
200
0.61776
[ "Apache-2.0" ]
maraf/DevTools
src/WinRun.UI/TopMostWindows/Interop.VirtualDesktop.cs
21,926
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Template10.Services.FileService { class FileService { FileHelper _helper = new FileHelper(); public async Task<List<T>> ReadAsync<T>(string key) { try { return await _helper.ReadFileAsync<List<T>>(key, FileHelper.StorageStrategies.Roaming); } catch { return new List<T>(); } } public async Task WriteAsync<T>(string key, List<T> items) { await _helper.WriteFileAsync(key, items, FileHelper.StorageStrategies.Roaming); } } }
26.32
107
0.647416
[ "MIT" ]
HydAu/WebDevCamp
Presentation/07. XAML Performance/Demos/Performance/Performance/Services/FileService/FileService.cs
660
C#
using System; using System.Diagnostics; using System.IO; using System.Linq; using ImageResizer.Plugins.Licensing; using ImageResizer.Util; namespace ImageResizer.Plugins.LicenseVerifier { class RealClock : ILicenseClock { public long TicksPerSecond { get; } = Stopwatch.Frequency; public long GetTimestampTicks() => Stopwatch.GetTimestamp(); public DateTimeOffset GetUtcNow() => DateTimeOffset.UtcNow; public DateTimeOffset? GetBuildDate() { try { return GetType() .Assembly.GetCustomAttributes(typeof(BuildDateAttribute), false) .Select(a => ((BuildDateAttribute) a).ValueDate) .FirstOrDefault(); } catch { return null; } } public DateTimeOffset? GetAssemblyWriteDate() { var path = GetType().Assembly.Location; try { return path != null && File.Exists(path) ? new DateTimeOffset?(File.GetLastWriteTimeUtc(path)) : null; } catch { return null; } } } }
27.697674
84
0.553317
[ "MIT" ]
2sic/resizer
Plugins/LicenseVerifier/LicensingSupport.cs
1,193
C#
using System; // TODO: TBD: we very intentionally identify the namespace so that... // TODO: TBD: if when our development pipeline "sees" the package update with contributions, then we can respond accordingly... namespace Google.Protobuf.WellKnownTypes { using static Duration; /// <summary> /// Provides a set of extension methods supporting bits concerning the Google bits. /// </summary> /// <remarks>There is not a lot more we can add to the <em>Google.Protobuf</em> /// package, but we can allow for a more fluent usage in key areas.</remarks> public static class DurationExtensionMethods { /// <summary> /// Bounds the <paramref name="value"/> By the <paramref name="min"/> /// and <paramref name="max"/> Values. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="value"></param> /// <param name="min"></param> /// <param name="max"></param> /// <returns></returns> private static T BoundedBy<T>(this T value, T min, T max) where T : struct, IComparable<T> { const int eq = default; if (value.CompareTo(min) < eq) { return min; } if (value.CompareTo(max) > eq) { return max; } return value; } /// <summary> /// Returns the normalized <paramref name="value"/> Bounded By <paramref name="bounds"/>. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="value"></param> /// <param name="bounds"></param> /// <returns></returns> private static T BoundedBy<T>(this T value, (T min, T max) bounds) where T : struct, IComparable<T> => value.BoundedBy(bounds.min, bounds.max); /// <summary> /// Signed seconds of the span of time. Must be from <c>-315,576,000,000</c> to /// <c>+315,576,000,000</c>, inclusive. Note, these bounds are computed from: /// <c>60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years</c>. /// </summary> /// <see cref="Duration"/> /// <see cref="MinSeconds"/> /// <see cref="MaxSeconds"/> private static (long min, long max) IntegerSecondBounds { get; } = ( MinSeconds , MaxSeconds ); /// <summary> /// Signed fractions of a second at nanosecond resolution of the span of time. Durations /// less than one second are represented with a 0 <em>seconds</em> field and a positive /// or negative <em>nanos</em> field. For durations of one second or more, a non-zero /// value for the <em>nanos</em> field must be of the same sign as the <em>seconds</em> /// field. Must be from <c>-999,999,999</c> to <c>+999,999,999</c> inclusive. /// </summary> /// <see cref="Duration"/> /// <see cref="NanosecondsPerSecond"/> private static (int min, int max) IntegerNanosBounds { get; } = ( -NanosecondsPerSecond + 1 , NanosecondsPerSecond ); // TODO: TBD: re: Google.Protobuf contributions... /// <summary> /// Returns the <see cref="Duration"/> corresponding with the <paramref name="seconds"/> /// and optional <paramref name="nanos"/>. /// </summary> /// <param name="seconds"></param> /// <param name="nanos"></param> /// <returns>The <see cref="Duration"/> corresponding to the <paramref name="seconds"/> /// and optional <paramref name="nanos"/>.</returns> /// <remarks>We should consider another <em>Google.Protobuf</em> contribution that adds /// <c>implicit</c> conversion from <see cref="long"/> and or <see cref="int"/>, and /// possibly even <see cref="ValueTuple{Int64, Int32}"/>.</remarks> public static Duration AsDuration(this int seconds, int? nanos = default) => ((long)seconds).AsDuration(nanos); /// <summary> /// Returns the <see cref="Duration"/> corresponding with the <paramref name="seconds"/> /// and optional <paramref name="nanos"/>. /// </summary> /// <param name="seconds"></param> /// <param name="nanos"></param> /// <returns>The <see cref="Duration"/> corresponding to the <paramref name="seconds"/> /// and optional <paramref name="nanos"/>.</returns> public static Duration AsDuration(this long seconds, int? nanos = default) { seconds = seconds.BoundedBy(IntegerSecondBounds); // TODO: TBD: with perhaps more seconds/nanos interactions at the seconds edges... if (nanos.HasValue) { var args = ( seconds , nanos: (nanos ?? default).BoundedBy(IntegerNanosBounds) ); return new Duration { Seconds = args.seconds, Nanos = args.nanos }; } // Unspecified at this level means Zero, or its Default, to Duration. return new Duration { Seconds = seconds }; } /// <summary> /// Returns the <see cref="Duration"/> corresponding with the <see cref="Duration.Nanos"/> /// <paramref name="value"/>. Leaves the <see cref="Duration.Seconds"/> off. /// </summary> /// <param name="value"></param> /// <returns></returns> public static Duration AsNanoDuration(this int value) => new Duration { Nanos = value.BoundedBy(IntegerNanosBounds.min, IntegerNanosBounds.max) }; // TODO: TBD: note that this one is on the way... // TODO: TBD: drafting feature/duration-deconstruction branch vis-a-vis: // TODO: TBD: https://github.com/mwpowellhtx/protobuf/tree/feature/duration-deconstruction // TODO: TBD: PR pending draft changes, https://github.com/protocolbuffers/protobuf/pull/8173 // TODO: TBD: we have established that Int32 is more appropriate than Nullable<Int32>. // TODO: TBD: pending clarification re: LABEL checks... re: CHANGES.txt (?) // TODO: TBD: which we may or may not also "squash" commits, but not considering that nearly as critical /// <summary> /// Deconstructs the <paramref name="value"/> in terms of <paramref name="seconds"/> /// and, optionally, <paramref name="nanoseconds"/>. /// </summary> /// <param name="value">The Value being deconstructed.</param> /// <param name="seconds">Receives the <see cref="Duration.Seconds"/> component.</param> /// <param name="nanoseconds">Receives the <see cref="Duration.Nanos"/> component.</param> /// <remarks>There is no value in deconstructing in only <paramref name="seconds"/> /// terms, from a language, or even simple POCO, perspective.</remarks> public static void Deconstruct(this Duration value, out long seconds, out int nanoseconds) => (seconds, nanoseconds) = (value.Seconds, value.Nanos); } }
46.051613
127
0.580275
[ "Apache-2.0" ]
mwpowellhtx/Ellumination.Protobuf
src/Ellumination.Protobuf/Extensions/DurationExtensionMethods.cs
7,140
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.InteropServices; namespace WFM { namespace Native { public static class WaveFileManagerNative { const string DLL_NAME = "wavefile_manager.dll"; [DllImport(DLL_NAME, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)] public static extern void createFile(string path, IntPtr prop); [DllImport(DLL_NAME, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)] public static extern void generateWAVEFORMATEX(IntPtr format, EDataType type); [DllImport(DLL_NAME, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)] public static extern void generateMusicProperty(IntPtr mpm, IntPtr waveFormat, EDataType type, IntPtr data, UInt32 size); [DllImport(DLL_NAME, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)] public static extern void generateSoundMonaural16bits(IntPtr begin, UInt32 size, double herth, int samplesPerSec = 44100, int volume = 30000); } } }
40.3
154
0.713813
[ "MIT" ]
capra314cabra/WaveFileManager
WaveFileManagerCS/WFMNative.cs
1,211
C#
using MediatR; namespace SFA.DAS.Campaign.Application.Queries.PreviewArticles { public class GetPreviewArticleByHubAndSlugQuery : IRequest<GetPreviewArticleByHubAndSlugQueryResult> { public string Hub { get; set; } public string Slug { get; set; } } }
28
104
0.728571
[ "MIT" ]
SkillsFundingAgency/das-apim-endpoints
src/SFA.DAS.Campaign/Application/Queries/PreviewArticles/GetPreviewArticleByHubAndSlugQuery.cs
280
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.AzureNative.StorageCache.V20201001.Inputs { /// <summary> /// Active Directory settings used to join a cache to a domain. /// </summary> public sealed class CacheActiveDirectorySettingsArgs : Pulumi.ResourceArgs { /// <summary> /// The NetBIOS name to assign to the HPC Cache when it joins the Active Directory domain as a server. Length must 1-15 characters from the class [-0-9a-zA-Z]. /// </summary> [Input("cacheNetBiosName", required: true)] public Input<string> CacheNetBiosName { get; set; } = null!; /// <summary> /// Active Directory admin credentials used to join the HPC Cache to a domain. /// </summary> [Input("credentials")] public Input<Inputs.CacheActiveDirectorySettingsCredentialsArgs>? Credentials { get; set; } /// <summary> /// The fully qualified domain name of the Active Directory domain controller. /// </summary> [Input("domainName", required: true)] public Input<string> DomainName { get; set; } = null!; /// <summary> /// The Active Directory domain's NetBIOS name. /// </summary> [Input("domainNetBiosName", required: true)] public Input<string> DomainNetBiosName { get; set; } = null!; /// <summary> /// Primary DNS IP address used to resolve the Active Directory domain controller's fully qualified domain name. /// </summary> [Input("primaryDnsIpAddress", required: true)] public Input<string> PrimaryDnsIpAddress { get; set; } = null!; /// <summary> /// Secondary DNS IP address used to resolve the Active Directory domain controller's fully qualified domain name. /// </summary> [Input("secondaryDnsIpAddress")] public Input<string>? SecondaryDnsIpAddress { get; set; } public CacheActiveDirectorySettingsArgs() { } } }
38.389831
167
0.642826
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/StorageCache/V20201001/Inputs/CacheActiveDirectorySettingsArgs.cs
2,265
C#
/* Yet Another Forum.NET * Copyright (C) 2003-2005 Bjørnar Henden * Copyright (C) 2006-2013 Jaben Cargman * Copyright (C) 2014-2018 Ingo Herbote * http://www.yetanotherforum.net/ * * 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. */ namespace YAF.Core.Model { using System; using System.Collections.Generic; using System.Data; using YAF.Types; using YAF.Types.Interfaces; using YAF.Types.Interfaces.Data; using YAF.Types.Models; /// <summary> /// The Shoutbox Repository Extensions /// </summary> public static class ShoutboxRepositoryExtensions { #region Public Methods and Operators public static void ClearMessages(this IRepository<ShoutboxMessage> repository, int? boardId = null) { CodeContracts.VerifyNotNull(repository, "repository"); repository.DbFunction.Query.shoutbox_clearmessages(BoardId: boardId ?? repository.BoardID, UTCTIMESTAMP: DateTime.UtcNow); repository.FireDeleted(); } public static DataTable GetMessages( this IRepository<ShoutboxMessage> repository, int numberOfMessages, bool styledNicks, int? boardId = null) { CodeContracts.VerifyNotNull(repository, "repository"); return repository.DbFunction.GetData.shoutbox_getmessages( BoardId: boardId ?? repository.BoardID, NumberOfMessages: numberOfMessages, StyledNicks: styledNicks); } public static void SaveMessage( this IRepository<ShoutboxMessage> repository, string message, string userName, int userID, string ip, int? boardId = null, DateTime? date = null) { CodeContracts.VerifyNotNull(repository, "repository"); repository.DbFunction.Query.shoutbox_savemessage( UserName: userName, BoardId: boardId ?? repository.BoardID, UserID: userID, Message: message, Date: date, IP: ip, UTCTIMESTAMP: DateTime.UtcNow); repository.FireNew(); } #endregion } }
36.925926
158
0.650619
[ "Apache-2.0" ]
ammogcoder/YAFNET
yafsrc/YAF.Core/Model/ShoutboxRepositoryExtensions.cs
2,912
C#
using System.Runtime.Serialization; using Elasticsearch.Net.Utf8Json; namespace Nest { [InterfaceDataContract] public interface IGeoPointFielddata : IFielddata { [DataMember(Name ="format")] GeoPointFielddataFormat? Format { get; set; } [DataMember(Name ="precision")] Distance Precision { get; set; } } public class GeoPointFielddata : FielddataBase, IGeoPointFielddata { public GeoPointFielddataFormat? Format { get; set; } public Distance Precision { get; set; } } public class GeoPointFielddataDescriptor : FielddataDescriptorBase<GeoPointFielddataDescriptor, IGeoPointFielddata>, IGeoPointFielddata { GeoPointFielddataFormat? IGeoPointFielddata.Format { get; set; } Distance IGeoPointFielddata.Precision { get; set; } public GeoPointFielddataDescriptor Format(GeoPointFielddataFormat? format) => Assign(format, (a, v) => a.Format = v); public GeoPointFielddataDescriptor Precision(Distance distance) => Assign(distance, (a, v) => a.Precision = v); } }
30.181818
119
0.763052
[ "Apache-2.0" ]
AnthAbou/elasticsearch-net
src/Nest/Modules/Indices/Fielddata/GeoPoint/GeoPointFielddata.cs
998
C#
using System.Collections.Generic; namespace OsuLightBeatmapParser.Sections { public class MetadataSection { public List<string> Unparsed { get; set; } public string Title { get; set; } public string TitleUnicode { get; set; } public string Artist { get; set; } public string ArtistUnicode { get; set; } public string Creator { get; set; } public string Version { get; set; } public string Source { get; set; } = ""; public HashSet<string> Tags { get; set; } = new(); public int BeatmapID { get; set; } public int BeatmapSetID { get; set; } = -1; } }
32.6
58
0.596626
[ "MIT" ]
ssz7-ch2/OsuLightBeatmapParser
OsuLightBeatmapParser/Sections/MetadataSection.cs
654
C#
/* * Magic, Copyright(c) Thomas Hansen 2019 - 2021, thomas@servergardens.com, all rights reserved. * See the enclosed LICENSE file for details. */ using System; using System.Linq; using System.Globalization; using Xunit; using magic.node.extensions; namespace magic.lambda.dates.tests { public class DateTests { [Fact] public void Now() { var lambda = Common.Evaluate(@" date.now"); Assert.Equal(typeof(DateTime), lambda.Children.First().Value.GetType()); } [Fact] public void Format() { var lambda = Common.Evaluate(@" date.now date.format:x:- format:""MM:yyyy:ddTHH:mm:ss"" "); Assert.Equal( lambda.Children.First().GetEx<DateTime>() .ToString("MM:yyyy:ddTHH:mm:ss", CultureInfo.InvariantCulture), lambda.Children.Skip(1).First().Value); } [Fact] public void FormatThrows() { Assert.Throws<ArgumentException>(() => Common.Evaluate(@" date.now date.format:x:- ")); } [Fact] public void AddTime_01() { var lambda = Common.Evaluate(@" date.now math.add get-value:x:@date.now time hours:1"); Assert.Equal( lambda.Children.First().GetEx<DateTime>().AddHours(1), lambda.Children.Skip(1).First().Value); } [Fact] public void AddTime_02() { var lambda = Common.Evaluate(@" date.now math.add get-value:x:@date.now time days:1 hours:1 minutes:1 seconds:1 milliseconds:1"); Assert.Equal( lambda.Children.First().GetEx<DateTime>() .AddDays(1) .AddHours(1) .AddMinutes(1) .AddSeconds(1) .AddMilliseconds(1), lambda.Children.Skip(1).First().Value); } [Fact] public void AddTime_03() { var lambda = Common.Evaluate(@" date.now math.add get-value:x:@date.now time minutes:1"); Assert.Equal( lambda.Children.First().GetEx<DateTime>().AddMinutes(1), lambda.Children.Skip(1).First().Value); } } }
23.606061
96
0.524176
[ "MIT" ]
polterguy/magic.lambda.dates
magic.lambda.dates.tests/DateTests.cs
2,337
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Concurrency; using System.Reactive.Linq; using ShairportSync.Metadata.Models; using ShairportSync.Metadata.Resolvers; using ShairportSync.Metadata.Utilities; namespace ShairportSync.Metadata.Parsers { internal static class TrackInfoParser { public static IObservable<TrackInfo> GetObservable(IObservable<Item> itemSource) { var publishItemSource = itemSource.SubscribeOn(TaskPoolScheduler.Default).Publish().RefCount(); // TODO SubscribeOn/Publish/RefCount. var trackSource = publishItemSource.Parse(); return trackSource; } private static IObservable<TrackInfo> Parse(this IObservable<Item> itemSource) { var artworkItemSource = itemSource.Where(m => m.Code == "PICT"); var bufferClosing = itemSource.Where(m => m.Code == "mden"); var trackSource = itemSource .Buffer(() => bufferClosing) .Select(items => items.ToTrack()); var mperChangesTrackSource = trackSource .PairWithPrevious() .Where(t => t.Item1?.Mper != t.Item2.Mper && t.Item2.Mper != null) .Select(t => t.Item2); var artworkTrackSource = artworkItemSource .WithLatestFrom(trackSource, (i, t) => new Artwork(t) { Artwork = i.Data }); return mperChangesTrackSource.ToWithArtwork(artworkTrackSource); } private static TrackInfo ToTrack(this IList<Item> items) { var trackInfo = new TrackInfo { PlaybackDateTime = DateTime.Now, // TODO an approximate value. Mper = items.SingleOrDefault(m => m.Code == "mper")?.Data, Artist = items.SingleOrDefault(m => m.Code == "asar")?.Data, Album = items.SingleOrDefault(m => m.Code == "asal")?.Data, Song = items.SingleOrDefault(m => m.Code == "minm")?.Data, Artwork = /*items.SingleOrDefault(m => m.Code == "PICT")?.Data ??*/ TrackInfoReaderResolver.ArtworkSettings.DefaultArtwork, }; return trackInfo; } private static IObservable<TrackInfo> ToWithArtwork(this IObservable<TrackInfo> trackSource, IObservable<Artwork> artworkSource) { var trackWithArtworkSource = trackSource .WithLatestFrom(artworkSource.StartWith(default(Artwork)), (t, a) => t.UpdateArtwork(a)); return trackWithArtworkSource.Merge(artworkSource); } private static TrackInfo UpdateArtwork(this TrackInfo trackInfo, Artwork artwork) { if (trackInfo.IsSameArtwork(artwork)) trackInfo.Artwork = artwork.Artwork; return trackInfo; } private static bool IsSameArtwork(this TrackInfo trackInfo, Artwork artwork) { if (artwork == null) return false; if (trackInfo.Mper == artwork.Mper) return true; if (string.IsNullOrEmpty(trackInfo.Artist) || string.IsNullOrEmpty(trackInfo.Album)) return false; if (trackInfo.Artist == artwork.Artist && trackInfo.Album == artwork.Album) return true; return false; } } }
38.431818
145
0.608811
[ "MIT" ]
idubnori/shairport-sync-trackinfo-reader
src/TrackInfoReader/Parsers/TrackInfoParser.cs
3,384
C#
using System; using System.Collections.Generic; using System.Numerics; using System.Text; namespace _05_PerlinNoise { public class Moving_Sphere : HitTable { public Vector3 center0, center1; public float time0, time1; public float radius; public Material mat_ptr; public Moving_Sphere() { } public Moving_Sphere(Vector3 cen0, Vector3 cen1, float t0, float t1, float r, Material m) { this.center0 = cen0; this.center1 = cen1; this.time0 = t0; this.time1 = t1; this.radius = r; this.mat_ptr = m; } public bool Hit(Ray r, float t_min, float t_max, ref Hit_Record rec) { Vector3 oc = r.Origin - this.Center(r.Time); var a = r.Direction.LengthSquared(); var half_b = Vector3.Dot(oc, r.Direction); var c = oc.LengthSquared() - radius * radius; var discriminant = half_b * half_b - a * c; if (discriminant > 0) { var root = (float)Math.Sqrt(discriminant); var temp = (-half_b - root) / a; if (temp < t_max && temp > t_min) { rec.T = temp; rec.P = r.At(rec.T); var outward_normal = (rec.P - this.Center(r.Time)) / radius; rec.Set_Face_Normal(r, outward_normal); rec.Mat_ptr = mat_ptr; return true; } temp = (-half_b + root) / a; if (temp < t_max && temp > t_min) { rec.T = temp; rec.P = r.At(rec.T); var outward_normal = (rec.P - this.Center(r.Time)) / radius; rec.Set_Face_Normal(r, outward_normal); rec.Mat_ptr = mat_ptr; return true; } } return false; } public Vector3 Center(float time) { return center0 + ((time - time0) / (time1 - time0)) * (center1 - center0); } public bool Bounding_box(float t0, float t1, out AABB output_box) { AABB box0 = new AABB( this.Center(t0) - new Vector3(radius), this.Center(t0) + new Vector3(radius)); AABB box1 = new AABB( this.Center(t1) - new Vector3(radius), this.Center(t1) + new Vector3(radius)); output_box = Helpers.Surrounding_box(box0, box1); return true; } } }
32.126437
97
0.455814
[ "MIT" ]
Jorgemagic/RaytracingTheNextWeek
05-PerlinNoise/HitTables/Moving_Sphere.cs
2,797
C#
// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace Xenko.Core.Mathematics { /// <summary> /// Represents an axis-aligned bounding box in three dimensional space that store only the Center and Extent. /// </summary> [DataContract] [StructLayout(LayoutKind.Sequential, Pack = 4)] public struct BoundingBoxExt : IEquatable<BoundingBoxExt> { /// <summary> /// A <see cref="BoundingBoxExt"/> which represents an empty space. /// </summary> public static readonly BoundingBoxExt Empty = new BoundingBoxExt(BoundingBox.Empty); /// <summary> /// The center of this bounding box. /// </summary> public Vector3 Center; /// <summary> /// The extent of this bounding box. /// </summary> public Vector3 Extent; /// <summary> /// Initializes a new instance of the <see cref="Xenko.Core.Mathematics.BoundingBoxExt" /> struct. /// </summary> /// <param name="box">The box.</param> public BoundingBoxExt(BoundingBox box) { this.Center = box.Center; this.Extent = box.Extent; } /// <summary> /// Initializes a new instance of the <see cref="Xenko.Core.Mathematics.BoundingBoxExt"/> struct. /// </summary> /// <param name="minimum">The minimum vertex of the bounding box.</param> /// <param name="maximum">The maximum vertex of the bounding box.</param> public BoundingBoxExt(Vector3 minimum, Vector3 maximum) { this.Center = (minimum + maximum) / 2; this.Extent = (maximum - minimum) / 2; } /// <summary> /// Gets the minimum. /// </summary> /// <value>The minimum.</value> public Vector3 Minimum { get { return Center - Extent; } } /// <summary> /// Gets the maximum. /// </summary> /// <value>The maximum.</value> public Vector3 Maximum { get { return Center + Extent; } } /// <summary> /// Transform this Bounding box /// </summary> /// <param name="world">The transform to apply to the bounding box.</param> public void Transform(Matrix world) { // http://zeuxcg.org/2010/10/17/aabb-from-obb-with-component-wise-abs/ // Compute transformed AABB (by world) var center = Center; var extent = Extent; Vector3.TransformCoordinate(ref center, ref world, out Center); // Update world matrix into absolute form unsafe { // Perform an abs on the matrix var matrixData = (float*)&world; for (int j = 0; j < 16; ++j) { //*matrixData &= 0x7FFFFFFF; *matrixData = Math.Abs(*matrixData); ++matrixData; } } Vector3.TransformNormal(ref extent, ref world, out Extent); } /// <summary> /// Constructs a <see cref="Xenko.Core.Mathematics.BoundingBoxExt"/> that is as large as the total combined area of the two specified boxes. /// </summary> /// <param name="value1">The first box to merge.</param> /// <param name="value2">The second box to merge.</param> /// <param name="result">When the method completes, contains the newly constructed bounding box.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Merge(ref BoundingBoxExt value1, ref BoundingBoxExt value2, out BoundingBoxExt result) { var maximum = Vector3.Max(value1.Maximum, value2.Maximum); var minimum = Vector3.Min(value1.Minimum, value2.Minimum); result.Center = (minimum + maximum) / 2; result.Extent = (maximum - minimum) / 2; } /// <inheritdoc/> public bool Equals(BoundingBoxExt other) { return Center.Equals(other.Center) && Extent.Equals(other.Extent); } /// <inheritdoc/> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is BoundingBoxExt && Equals((BoundingBoxExt)obj); } /// <inheritdoc/> public override int GetHashCode() { unchecked { return (Center.GetHashCode() * 397) ^ Extent.GetHashCode(); } } /// <summary> /// Implements the ==. /// </summary> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <returns>The result of the operator.</returns> public static bool operator ==(BoundingBoxExt left, BoundingBoxExt right) { return left.Equals(right); } /// <summary> /// Implements the !=. /// </summary> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <returns>The result of the operator.</returns> public static bool operator !=(BoundingBoxExt left, BoundingBoxExt right) { return !left.Equals(right); } /// <summary> /// Performs an explicit conversion from <see cref="BoundingBoxExt"/> to <see cref="BoundingBox"/>. /// </summary> /// <param name="bbExt">The bb ext.</param> /// <returns>The result of the conversion.</returns> public static explicit operator BoundingBox(BoundingBoxExt bbExt) { return new BoundingBox(bbExt.Minimum, bbExt.Maximum); } /// <summary> /// Performs an explicit conversion from <see cref="BoundingBox"/> to <see cref="BoundingBoxExt"/>. /// </summary> /// <param name="boundingBox">The bounding box.</param> /// <returns>The result of the conversion.</returns> public static explicit operator BoundingBoxExt(BoundingBox boundingBox) { return new BoundingBoxExt(boundingBox); } } }
35.284946
148
0.556758
[ "MIT" ]
Beefr/xenko
sources/core/Xenko.Core.Mathematics/BoundingBoxExt.cs
6,563
C#
using ComponentFactory.Krypton.Toolkit; using System.Collections; using System.ComponentModel; using System.IO; using System.Windows.Forms; namespace ExtendedControls.ExtendedToolkit.Controls { [ToolboxItem(true)] public class KryptonHexadecimalColourTextBox : KryptonTextBox { #region Variables private ArrayList _hexadecimalColourList; private bool _uppercase = true; private string _hexadecimalColourDatabaseFilePath; #endregion #region Properties public bool Uppercase { get { return _uppercase; } set { _uppercase = value; } } /// <summary> /// Gets or sets the hexadecimal colour database file path. /// </summary> /// <value> /// The hexadecimal colour database file path. /// </value> [Category("Data")] [Description("Gets or sets the hexadecimal colour database file path.")] public string HexadecimalColourDatabaseFilePath { get { return _hexadecimalColourDatabaseFilePath; } set { _hexadecimalColourDatabaseFilePath = value; } } #endregion #region Constructors public KryptonHexadecimalColourTextBox() { TextAlign = HorizontalAlignment.Center; UpdateControl(); } #endregion #region Methods public void UpdateControl() { _hexadecimalColourList = new ArrayList(); if (HexadecimalColourDatabaseFilePath != string.Empty) { if (File.Exists(HexadecimalColourDatabaseFilePath)) { StreamReader reader = new StreamReader(HexadecimalColourDatabaseFilePath); string contents = reader.ReadToEnd(); } } } #endregion #region Overrides protected override void OnPaint(PaintEventArgs e) { //UpdateControl(); base.OnPaint(e); Invalidate(); } #endregion } }
28.901408
162
0.601852
[ "BSD-3-Clause" ]
Krypton-Suite-Legacy-Archive/Krypton-Toolkit-Suite-Extended-NET-5.470
Source/Krypton Toolkit Suite Extended/Full Toolkit/Extended Controls/ExtendedToolkit/Controls/KryptonHexadecimalColourTextBox.cs
2,054
C#
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; namespace Relm.Input { public class KeyboardManager { private KeyboardState _previousState; private KeyboardState _currentState; public void Update(GameTime gameTime) { _previousState = _currentState; _currentState = Keyboard.GetState(); } public bool IsKeyPressed(Keys key) { return _currentState.IsKeyDown(key) && _previousState.IsKeyUp(key); } public bool IsKeyDown(Keys key) { return _currentState.IsKeyDown(key); } public bool IsKeyUp(Keys key) { return _currentState.IsKeyUp(key); } public bool IsKeyReleased(Keys key) { return _currentState.IsKeyUp(key) && _previousState.IsKeyDown(key); } public bool IsKeyHeld(Keys key) { return _currentState.IsKeyDown(key) && _previousState.IsKeyDown(key); } } }
24.714286
81
0.595376
[ "MIT" ]
slyprid/Relm
Archive/Archive 2/Relm/Relm/Input/KeyboardManager.cs
1,040
C#
using ChessEngine.Moves; namespace ChessEngine.Search; public struct Limits { public uint TimeLimitWhite = 0; public uint TimeLimitBlack = 0; public uint TimeIncrementWhite = 0; public uint TimeIncrementBlack = 0; public ushort MovesUntilTimeControl = 0; public ushort SearchDepth = 0; public ulong MaximumNodesToSearch = 0; public List<Move> MovesToSearch = new(); public ushort SearchForMateInX = 0; public ulong StartTime = 0 ; public uint SearchForXMilliSeconds = 0; public bool SearchIndefinitely = false; public ushort PerftDepth = 0; }
24.68
44
0.700162
[ "Unlicense" ]
NritiNy/ChessClient
Engine/Search/Limits.cs
619
C#
using System; namespace edu.tum.cs.conqat.dotnet { // Declare delegate -- defines required signature: delegate void SomeDelegate(string message); public class Target { public static void SampleDelegateMethod(string message) { Console.WriteLine(message); } } public class Source { // Regular method that matches signature: void SourceMethod() { // Instantiate delegate with named method: SomeDelegate d1 = Target.SampleDelegateMethod; // Instantiate delegate with anonymous method: SomeDelegate d2 = delegate(string message) { Console.WriteLine(message); }; // Invoke delegate d1: d1("Hello"); // Invoke delegate d2: d2(" World"); } } }
24.823529
65
0.577014
[ "Apache-2.0" ]
SvenPeldszus/conqat
org.conqat.engine.dotnet/test-data/org.conqat.engine.dotnet.ila.scenario/delegateMethod.cs
844
C#
using System; using System.Collections.Generic; using System.Linq; using DS4Windows; using PropertyChanged; namespace DS4WinWPF.DS4Control.Profiles.Schema { [AddINotifyPropertyChangedInterface] public class AutoSwitchingProfileEntry { /// <summary> /// Association between controller slots and the profile (ID) to switch to. /// </summary> public Dictionary<int, Guid?> ControllerSlotProfileId { get; set; } = new(Enumerable .Range(0, Constants.MaxControllers) .Select(i => new KeyValuePair<int, Guid?>(i, null))); public bool TurnOff { get; set; } /// <summary> /// Full path to main executable file. /// </summary> public string Path { get; set; } /// <summary> /// Optional Window Title to further clamp down application detection. /// </summary> public string Title { get; set; } } [AddINotifyPropertyChangedInterface] public class AutoSwitchingProfiles : JsonSerializable<AutoSwitchingProfiles> { public List<AutoSwitchingProfileEntry> AutoSwitchingProfileEntries { get; set; } = new(); } }
31.918919
97
0.640982
[ "MIT" ]
midwan/DS4Windows
DS4Windows/DS4Control/Profiles/Schema/AutoProfilesSchema.cs
1,183
C#
namespace Topics.Radical.ChangeTracking.Specialized { using System.Collections.Generic; public class CollectionRangeDescriptor<T> : CollectionChangeDescriptor<T> { /// <summary> /// Initializes a new instance of the <see cref="CollectionRangeDescriptor&lt;T&gt;"/> class. /// </summary> /// <param name="items">The items.</param> public CollectionRangeDescriptor( IEnumerable<T> items ) { this.Items = items; } /// <summary> /// Gets the range of items. /// </summary> /// <value>The items.</value> public IEnumerable<T> Items { get; private set; } } }
22.923077
95
0.671141
[ "MIT" ]
pdeligia/nekara-artifact
TSVD/Radical/src/net35/Radical/Model/ChangeTracking/Collection Changes/Descriptors/CollectionRangeDescriptor (Generic).cs
598
C#
using Castle.Core.Interceptor; using Rhino.Mocks.Impl.InvocationSpecifications; using Rhino.Mocks.Interfaces; namespace Rhino.Mocks.Impl.Invocation.Specifications { ///<summary> ///</summary> public class IsAPropertyInvocation : ISpecification<IInvocation> { IMockedObject proxyInstance; ///<summary> ///</summary> public IsAPropertyInvocation(IMockedObject proxy_instance) { proxyInstance = proxy_instance; } ///<summary> ///</summary> public bool IsSatisfiedBy(IInvocation item) { return proxyInstance.IsPropertyMethod(item.GetConcreteMethod()); } } }
25.481481
76
0.640988
[ "BSD-3-Clause" ]
Carolinehan/rhino-mocks
Rhino.Mocks/Impl/Invocation/Specifications/IsAPropertyInvocation.cs
688
C#
using CustomerManager.Rest.Call.Services.Contracts; using System; using System.Linq; using System.Web.Mvc; namespace CustomerManager.MVC.Client.Controllers { public class CustomersController : Controller { private readonly ICustomerRestCallService customersService; public CustomersController(ICustomerRestCallService service) { if (service == null) { throw new NullReferenceException("Customer service should not be null!"); } this.customersService = service; } public ActionResult AllCustomers() { var allCustomers = this.customersService.GetAllCustomers(); if (allCustomers == null) { return RedirectToAction("Error"); } return View(allCustomers); } public ActionResult CustomerById(string id) { var customerById = this.customersService.GetCustomerById(id); var ordersByCustomerId = this.customersService.GetOrdersByCustomerId(id); if (customerById == null || ordersByCustomerId == null) { return RedirectToAction("Error"); } customerById.Orders = this.customersService.GetOrdersByCustomerId(id); return View(customerById); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Search(string search) { var customerByContactName = this.customersService .GetCustomerByContactName(search.Trim()) .ToList(); return View("AllCustomers", customerByContactName); } } }
29.229508
89
0.577117
[ "MIT" ]
todor-enikov/Customer-Manager-WebAPI-MVC-Project
CustomerManager/CustomerManager.MVC.Client/Controllers/CustomersController.cs
1,785
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace OwinSelfhostSample { using System; using System.Collections.Generic; public partial class Shipper { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public Shipper() { this.Orders = new HashSet<Order>(); } public int ShipperID { get; set; } public string CompanyName { get; set; } public string Phone { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Order> Orders { get; set; } } }
35.967742
128
0.573094
[ "MIT" ]
atomprogs/SelfHostingWebApi
WebApiWithOwin/OwinSelfhostSample/Shipper.cs
1,115
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 Aliyun.Acs.Core; using System.Collections.Generic; namespace Aliyun.Acs.Push.Model.V20160801 { public class QueryPushStatResponse : AcsResponse { public List<PushStat> PushStats { get; set; } public class PushStat{ public string MessageId { get; set; } public long? SentCount { get; set; } public long? ReceivedCount { get; set; } public long? OpenedCount { get; set; } public long? DeletedCount { get; set; } } } }
32.5
63
0.708462
[ "Apache-2.0" ]
VAllens/aliyun-openapi-sdk-net-core
src/aliyun-net-sdk-push-openapi-2.0/Model/V20160801/QueryPushStatResponse.cs
1,300
C#
using System; using NetRuntimeSystem = System; using System.ComponentModel; using NetOffice.Attributes; namespace NetOffice.MSHTMLApi { /// <summary> /// DispatchInterface DispHTMLBRElement /// SupportByVersion MSHTML, 4 /// </summary> [SupportByVersion("MSHTML", 4)] [EntityType(EntityType.IsDispatchInterface), BaseType] [TypeId("3050F53A-98B5-11CF-BB82-00AA00BDCE0B")] [CoClassSource(typeof(NetOffice.MSHTMLApi.HTMLBRElement))] public interface DispHTMLBRElement : ICOMObject { #region Properties /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] string className { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] string id { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] string tagName { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] [BaseResult] NetOffice.MSHTMLApi.IHTMLElement parentElement { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] [BaseResult] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] NetOffice.MSHTMLApi.IHTMLStyle style { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onhelp { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onclick { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object ondblclick { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onkeydown { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onkeyup { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onkeypress { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onmouseout { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onmouseover { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onmousemove { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onmousedown { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onmouseup { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// Unknown COM Proxy /// </summary> [SupportByVersion("MSHTML", 4), ProxyResult] object document { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] string title { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] string language { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onselectstart { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] Int32 sourceIndex { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] object recordNumber { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] string lang { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] Int32 offsetLeft { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] Int32 offsetTop { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] Int32 offsetWidth { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] Int32 offsetHeight { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] [BaseResult] NetOffice.MSHTMLApi.IHTMLElement offsetParent { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] string innerHTML { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] string innerText { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] string outerHTML { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] string outerText { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] [BaseResult] NetOffice.MSHTMLApi.IHTMLElement parentTextEdit { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] bool isTextEdit { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] NetOffice.MSHTMLApi.IHTMLFiltersCollection filters { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object ondragstart { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onbeforeupdate { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onafterupdate { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onerrorupdate { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onrowexit { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onrowenter { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object ondatasetchanged { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object ondataavailable { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object ondatasetcomplete { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onfilterchange { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// Unknown COM Proxy /// </summary> [SupportByVersion("MSHTML", 4), ProxyResult] object children { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// Unknown COM Proxy /// </summary> [SupportByVersion("MSHTML", 4), ProxyResult] object all { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] string scopeName { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onlosecapture { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onscroll { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object ondrag { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object ondragend { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object ondragenter { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object ondragover { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object ondragleave { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object ondrop { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onbeforecut { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object oncut { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onbeforecopy { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object oncopy { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onbeforepaste { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onpaste { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] [BaseResult] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] NetOffice.MSHTMLApi.IHTMLCurrentStyle currentStyle { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onpropertychange { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] Int16 tabIndex { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] string accessKey { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onblur { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onfocus { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onresize { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] Int32 clientHeight { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] Int32 clientWidth { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] Int32 clientTop { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] Int32 clientLeft { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] object readyState { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onreadystatechange { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onrowsdelete { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onrowsinserted { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object oncellchange { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] string dir { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] Int32 scrollHeight { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] Int32 scrollWidth { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] Int32 scrollTop { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] Int32 scrollLeft { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object oncontextmenu { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] bool canHaveChildren { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] [BaseResult] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] NetOffice.MSHTMLApi.IHTMLStyle runtimeStyle { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// Unknown COM Proxy /// </summary> [SupportByVersion("MSHTML", 4), ProxyResult] object behaviorUrns { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] string tagUrn { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onbeforeeditfocus { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] Int32 readyStateValue { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] bool isMultiLine { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] bool canHaveHTML { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onlayoutcomplete { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onpage { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] bool inflateBlock { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onbeforedeactivate { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] string contentEditable { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] bool isContentEditable { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] bool hideFocus { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] bool disabled { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] bool isDisabled { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onmove { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object oncontrolselect { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onresizestart { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onresizeend { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onmovestart { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onmoveend { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onmouseenter { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onmouseleave { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onactivate { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object ondeactivate { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] Int32 glyphMode { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onmousewheel { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onbeforeactivate { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onfocusin { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object onfocusout { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] Int32 uniqueNumber { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] string uniqueID { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] Int32 nodeType { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] [BaseResult] NetOffice.MSHTMLApi.IHTMLDOMNode parentNode { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// Unknown COM Proxy /// </summary> [SupportByVersion("MSHTML", 4), ProxyResult] object childNodes { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// Unknown COM Proxy /// </summary> [SupportByVersion("MSHTML", 4), ProxyResult] object attributes { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] string nodeName { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] object nodeValue { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] [BaseResult] NetOffice.MSHTMLApi.IHTMLDOMNode firstChild { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] [BaseResult] NetOffice.MSHTMLApi.IHTMLDOMNode lastChild { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] [BaseResult] NetOffice.MSHTMLApi.IHTMLDOMNode previousSibling { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] [BaseResult] NetOffice.MSHTMLApi.IHTMLDOMNode nextSibling { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// Unknown COM Proxy /// </summary> [SupportByVersion("MSHTML", 4), ProxyResult] object ownerDocument { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] string role { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] string ariaBusy { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] string ariaChecked { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] string ariaDisabled { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] string ariaExpanded { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] string ariaHaspopup { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] string ariaHidden { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] string ariaInvalid { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] string ariaMultiselectable { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] string ariaPressed { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] string ariaReadonly { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] string ariaRequired { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] string ariaSecret { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] string ariaSelected { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] NetOffice.MSHTMLApi.IHTMLAttributeCollection3 ie8_attributes { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] string ariaValuenow { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] Int16 ariaPosinset { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] Int16 ariaSetsize { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] Int16 ariaLevel { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] string ariaValuemin { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] string ariaValuemax { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] string ariaControls { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] string ariaDescribedby { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] string ariaFlowto { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] string ariaLabelledby { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] string ariaActivedescendant { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] string ariaOwns { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] string ariaLive { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] string ariaRelevant { get; set; } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// Unknown COM Proxy /// </summary> [SupportByVersion("MSHTML", 4), ProxyResult] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] object constructor { get; } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersion("MSHTML", 4)] string clear { get; set; } #endregion #region Methods /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="strAttributeName">string strAttributeName</param> /// <param name="attributeValue">object attributeValue</param> /// <param name="lFlags">optional Int32 lFlags = 1</param> [SupportByVersion("MSHTML", 4)] void setAttribute(string strAttributeName, object attributeValue, object lFlags); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="strAttributeName">string strAttributeName</param> /// <param name="attributeValue">object attributeValue</param> [CustomMethod] [SupportByVersion("MSHTML", 4)] void setAttribute(string strAttributeName, object attributeValue); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="strAttributeName">string strAttributeName</param> /// <param name="lFlags">optional Int32 lFlags = 0</param> [SupportByVersion("MSHTML", 4)] object getAttribute(string strAttributeName, object lFlags); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="strAttributeName">string strAttributeName</param> [CustomMethod] [SupportByVersion("MSHTML", 4)] object getAttribute(string strAttributeName); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="strAttributeName">string strAttributeName</param> /// <param name="lFlags">optional Int32 lFlags = 1</param> [SupportByVersion("MSHTML", 4)] bool removeAttribute(string strAttributeName, object lFlags); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="strAttributeName">string strAttributeName</param> [CustomMethod] [SupportByVersion("MSHTML", 4)] bool removeAttribute(string strAttributeName); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="varargStart">optional object varargStart</param> [SupportByVersion("MSHTML", 4)] void scrollIntoView(object varargStart); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> [CustomMethod] [SupportByVersion("MSHTML", 4)] void scrollIntoView(); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pChild">NetOffice.MSHTMLApi.IHTMLElement pChild</param> [SupportByVersion("MSHTML", 4)] bool contains(NetOffice.MSHTMLApi.IHTMLElement pChild); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="where">string where</param> /// <param name="html">string html</param> [SupportByVersion("MSHTML", 4)] void insertAdjacentHTML(string where, string html); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="where">string where</param> /// <param name="text">string text</param> [SupportByVersion("MSHTML", 4)] void insertAdjacentText(string where, string text); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> [SupportByVersion("MSHTML", 4)] void click(); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> [SupportByVersion("MSHTML", 4)] string toString(); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="containerCapture">optional bool containerCapture = true</param> [SupportByVersion("MSHTML", 4)] void setCapture(object containerCapture); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> [CustomMethod] [SupportByVersion("MSHTML", 4)] void setCapture(); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> [SupportByVersion("MSHTML", 4)] void releaseCapture(); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="x">Int32 x</param> /// <param name="y">Int32 y</param> [SupportByVersion("MSHTML", 4)] string componentFromPoint(Int32 x, Int32 y); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="component">optional object component</param> [SupportByVersion("MSHTML", 4)] void doScroll(object component); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> [CustomMethod] [SupportByVersion("MSHTML", 4)] void doScroll(); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> [SupportByVersion("MSHTML", 4)] NetOffice.MSHTMLApi.IHTMLRectCollection getClientRects(); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> [SupportByVersion("MSHTML", 4)] NetOffice.MSHTMLApi.IHTMLRect getBoundingClientRect(); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="propname">string propname</param> /// <param name="expression">string expression</param> /// <param name="language">optional string language = </param> [SupportByVersion("MSHTML", 4)] void setExpression(string propname, string expression, object language); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="propname">string propname</param> /// <param name="expression">string expression</param> [CustomMethod] [SupportByVersion("MSHTML", 4)] void setExpression(string propname, string expression); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="propname">string propname</param> [SupportByVersion("MSHTML", 4)] object getExpression(string propname); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="propname">string propname</param> [SupportByVersion("MSHTML", 4)] bool removeExpression(string propname); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> [SupportByVersion("MSHTML", 4)] void focus(); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> [SupportByVersion("MSHTML", 4)] void blur(); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pUnk">object pUnk</param> [SupportByVersion("MSHTML", 4)] void addFilter(object pUnk); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pUnk">object pUnk</param> [SupportByVersion("MSHTML", 4)] void removeFilter(object pUnk); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="_event">string event</param> /// <param name="pdisp">object pdisp</param> [SupportByVersion("MSHTML", 4)] bool attachEvent(string _event, object pdisp); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="_event">string event</param> /// <param name="pdisp">object pdisp</param> [SupportByVersion("MSHTML", 4)] void detachEvent(string _event, object pdisp); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> [SupportByVersion("MSHTML", 4)] object createControlRange(); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> [SupportByVersion("MSHTML", 4)] void clearAttributes(); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="where">string where</param> /// <param name="insertedElement">NetOffice.MSHTMLApi.IHTMLElement insertedElement</param> [SupportByVersion("MSHTML", 4)] [BaseResult] NetOffice.MSHTMLApi.IHTMLElement insertAdjacentElement(string where, NetOffice.MSHTMLApi.IHTMLElement insertedElement); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="apply">NetOffice.MSHTMLApi.IHTMLElement apply</param> /// <param name="where">string where</param> [SupportByVersion("MSHTML", 4)] [BaseResult] NetOffice.MSHTMLApi.IHTMLElement applyElement(NetOffice.MSHTMLApi.IHTMLElement apply, string where); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="where">string where</param> [SupportByVersion("MSHTML", 4)] string getAdjacentText(string where); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="where">string where</param> /// <param name="newText">string newText</param> [SupportByVersion("MSHTML", 4)] string replaceAdjacentText(string where, string newText); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="bstrUrl">string bstrUrl</param> /// <param name="pvarFactory">optional object pvarFactory</param> [SupportByVersion("MSHTML", 4)] Int32 addBehavior(string bstrUrl, object pvarFactory); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="bstrUrl">string bstrUrl</param> [CustomMethod] [SupportByVersion("MSHTML", 4)] Int32 addBehavior(string bstrUrl); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="cookie">Int32 cookie</param> [SupportByVersion("MSHTML", 4)] bool removeBehavior(Int32 cookie); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="v">string v</param> [SupportByVersion("MSHTML", 4)] [BaseResult] NetOffice.MSHTMLApi.IHTMLElementCollection getElementsByTagName(string v); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="mergeThis">NetOffice.MSHTMLApi.IHTMLElement mergeThis</param> /// <param name="pvarFlags">optional object pvarFlags</param> [SupportByVersion("MSHTML", 4)] void mergeAttributes(NetOffice.MSHTMLApi.IHTMLElement mergeThis, object pvarFlags); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="mergeThis">NetOffice.MSHTMLApi.IHTMLElement mergeThis</param> [CustomMethod] [SupportByVersion("MSHTML", 4)] void mergeAttributes(NetOffice.MSHTMLApi.IHTMLElement mergeThis); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> [SupportByVersion("MSHTML", 4)] void setActive(); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="bstrEventName">string bstrEventName</param> /// <param name="pvarEventObject">optional object pvarEventObject</param> [SupportByVersion("MSHTML", 4)] bool FireEvent(string bstrEventName, object pvarEventObject); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="bstrEventName">string bstrEventName</param> [CustomMethod] [SupportByVersion("MSHTML", 4)] bool FireEvent(string bstrEventName); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> [SupportByVersion("MSHTML", 4)] bool dragDrop(); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> [SupportByVersion("MSHTML", 4)] void normalize(); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="bstrName">string bstrName</param> [SupportByVersion("MSHTML", 4)] [BaseResult] NetOffice.MSHTMLApi.IHTMLDOMAttribute getAttributeNode(string bstrName); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pattr">NetOffice.MSHTMLApi.IHTMLDOMAttribute pattr</param> [SupportByVersion("MSHTML", 4)] [BaseResult] NetOffice.MSHTMLApi.IHTMLDOMAttribute setAttributeNode(NetOffice.MSHTMLApi.IHTMLDOMAttribute pattr); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pattr">NetOffice.MSHTMLApi.IHTMLDOMAttribute pattr</param> [SupportByVersion("MSHTML", 4)] [BaseResult] NetOffice.MSHTMLApi.IHTMLDOMAttribute removeAttributeNode(NetOffice.MSHTMLApi.IHTMLDOMAttribute pattr); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> [SupportByVersion("MSHTML", 4)] bool hasChildNodes(); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="newChild">NetOffice.MSHTMLApi.IHTMLDOMNode newChild</param> /// <param name="refChild">optional object refChild</param> [SupportByVersion("MSHTML", 4)] [BaseResult] NetOffice.MSHTMLApi.IHTMLDOMNode insertBefore(NetOffice.MSHTMLApi.IHTMLDOMNode newChild, object refChild); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="newChild">NetOffice.MSHTMLApi.IHTMLDOMNode newChild</param> [CustomMethod] [BaseResult] [SupportByVersion("MSHTML", 4)] NetOffice.MSHTMLApi.IHTMLDOMNode insertBefore(NetOffice.MSHTMLApi.IHTMLDOMNode newChild); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="oldChild">NetOffice.MSHTMLApi.IHTMLDOMNode oldChild</param> [SupportByVersion("MSHTML", 4)] [BaseResult] NetOffice.MSHTMLApi.IHTMLDOMNode removeChild(NetOffice.MSHTMLApi.IHTMLDOMNode oldChild); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="newChild">NetOffice.MSHTMLApi.IHTMLDOMNode newChild</param> /// <param name="oldChild">NetOffice.MSHTMLApi.IHTMLDOMNode oldChild</param> [SupportByVersion("MSHTML", 4)] [BaseResult] NetOffice.MSHTMLApi.IHTMLDOMNode replaceChild(NetOffice.MSHTMLApi.IHTMLDOMNode newChild, NetOffice.MSHTMLApi.IHTMLDOMNode oldChild); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="fDeep">bool fDeep</param> [SupportByVersion("MSHTML", 4)] [BaseResult] NetOffice.MSHTMLApi.IHTMLDOMNode cloneNode(bool fDeep); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="fDeep">optional bool fDeep = false</param> [SupportByVersion("MSHTML", 4)] [BaseResult] NetOffice.MSHTMLApi.IHTMLDOMNode removeNode(object fDeep); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> [CustomMethod] [BaseResult] [SupportByVersion("MSHTML", 4)] NetOffice.MSHTMLApi.IHTMLDOMNode removeNode(); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="otherNode">NetOffice.MSHTMLApi.IHTMLDOMNode otherNode</param> [SupportByVersion("MSHTML", 4)] [BaseResult] NetOffice.MSHTMLApi.IHTMLDOMNode swapNode(NetOffice.MSHTMLApi.IHTMLDOMNode otherNode); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="replacement">NetOffice.MSHTMLApi.IHTMLDOMNode replacement</param> [SupportByVersion("MSHTML", 4)] [BaseResult] NetOffice.MSHTMLApi.IHTMLDOMNode replaceNode(NetOffice.MSHTMLApi.IHTMLDOMNode replacement); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="newChild">NetOffice.MSHTMLApi.IHTMLDOMNode newChild</param> [SupportByVersion("MSHTML", 4)] [BaseResult] NetOffice.MSHTMLApi.IHTMLDOMNode appendChild(NetOffice.MSHTMLApi.IHTMLDOMNode newChild); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="bstrName">string bstrName</param> [SupportByVersion("MSHTML", 4)] [BaseResult] NetOffice.MSHTMLApi.IHTMLDOMAttribute2 ie8_getAttributeNode(string bstrName); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pattr">NetOffice.MSHTMLApi.IHTMLDOMAttribute2 pattr</param> [SupportByVersion("MSHTML", 4)] [BaseResult] NetOffice.MSHTMLApi.IHTMLDOMAttribute2 ie8_setAttributeNode(NetOffice.MSHTMLApi.IHTMLDOMAttribute2 pattr); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pattr">NetOffice.MSHTMLApi.IHTMLDOMAttribute2 pattr</param> [SupportByVersion("MSHTML", 4)] [BaseResult] NetOffice.MSHTMLApi.IHTMLDOMAttribute2 ie8_removeAttributeNode(NetOffice.MSHTMLApi.IHTMLDOMAttribute2 pattr); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="name">string name</param> [SupportByVersion("MSHTML", 4)] bool hasAttribute(string name); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="strAttributeName">string strAttributeName</param> [SupportByVersion("MSHTML", 4)] object ie8_getAttribute(string strAttributeName); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="strAttributeName">string strAttributeName</param> /// <param name="attributeValue">object attributeValue</param> [SupportByVersion("MSHTML", 4)] void ie8_setAttribute(string strAttributeName, object attributeValue); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="strAttributeName">string strAttributeName</param> [SupportByVersion("MSHTML", 4)] bool ie8_removeAttribute(string strAttributeName); /// <summary> /// SupportByVersion MSHTML 4 /// </summary> [SupportByVersion("MSHTML", 4)] bool hasAttributes(); #endregion } }
24.325294
134
0.641259
[ "MIT" ]
igoreksiz/NetOffice
Source/MSHTML/DispatchInterfaces/DispHTMLBRElement.cs
41,355
C#
using System; using Cake.Common.Tests.Fixtures.Tools.Chocolatey.Packer; using Cake.Common.Tests.Properties; using Cake.Common.Tools.Chocolatey.Pack; using Cake.Core; using Cake.Core.IO; using Cake.Testing; using Cake.Testing.Xunit; using Xunit; namespace Cake.Common.Tests.Unit.Tools.Chocolatey.Pack { public sealed class ChocolateyPackerTests { public sealed class ThePackMethod { [Fact] public void Should_Throw_If_Nuspec_File_Path_Is_Null() { // Given var fixture = new ChocolateyPackerWithNuSpecFixture(); fixture.NuSpecFilePath = null; // When var result = Record.Exception(() => fixture.Run()); // Then Assert.IsArgumentNullException(result, "nuspecFilePath"); } [Fact] public void Should_Throw_If_Settings_Is_Null() { // Given var fixture = new ChocolateyPackerWithNuSpecFixture(); fixture.Settings = null; // When var result = Record.Exception(() => fixture.Run()); // Then Assert.IsArgumentNullException(result, "settings"); } [Fact] public void Should_Throw_If_Chocolatey_Executable_Was_Not_Found() { // Given var fixture = new ChocolateyPackerWithNuSpecFixture(); fixture.GivenDefaultToolDoNotExist(); // When var result = Record.Exception(() => fixture.Run()); // Then Assert.IsCakeException(result, "Chocolatey: Could not locate executable."); } [Theory] [InlineData("/bin/chocolatey/choco.exe", "/bin/chocolatey/choco.exe")] [InlineData("./chocolatey/choco.exe", "/Working/chocolatey/choco.exe")] public void Should_Use_Chocolatey_Executable_From_Tool_Path_If_Provided(string toolPath, string expected) { // Given var fixture = new ChocolateyPackerWithNuSpecFixture(); fixture.Settings.ToolPath = toolPath; fixture.GivenSettingsToolPathExist(); // When var result = fixture.Run(); // Then Assert.Equal(expected, result.Path.FullPath); } [WindowsTheory] [InlineData("C:/ProgramData/chocolatey/choco.exe", "C:/ProgramData/chocolatey/choco.exe")] public void Should_Use_Chocolatey_Executable_From_Tool_Path_If_Provided_On_Windows(string toolPath, string expected) { // Given var fixture = new ChocolateyPackerWithNuSpecFixture(); fixture.Settings.ToolPath = toolPath; fixture.GivenSettingsToolPathExist(); // When var result = fixture.Run(); // Then Assert.Equal(expected, result.Path.FullPath); } [Fact] public void Should_Find_Chocolatey_Executable_If_Tool_Path_Not_Provided() { // Given var fixture = new ChocolateyPackerWithNuSpecFixture(); // When var result = fixture.Run(); // Then Assert.Equal("/Working/tools/choco.exe", result.Path.FullPath); } [Fact] public void Should_Throw_If_Process_Was_Not_Started() { // Given var fixture = new ChocolateyPackerWithNuSpecFixture(); fixture.GivenProcessCannotStart(); // When var result = Record.Exception(() => fixture.Run()); // Then Assert.IsCakeException(result, "Chocolatey: Process was not started."); } [Fact] public void Should_Throw_If_Process_Has_A_Non_Zero_Exit_Code() { // Given var fixture = new ChocolateyPackerWithNuSpecFixture(); fixture.GivenProcessExitsWithCode(1); // When var result = Record.Exception(() => fixture.Run()); // Then Assert.IsCakeException(result, "Chocolatey: Process returned an error (exit code 1)."); } [Fact] public void Should_Delete_Transformed_Nuspec() { // Given var fixture = new ChocolateyPackerWithNuSpecFixture(); // When fixture.Run(); // Then Assert.False(fixture.FileSystem.Exist((FilePath)"/Working/existing.temp.nuspec")); } [Fact] public void Should_Throw_If_Nuspec_Do_Not_Exist() { // Given var fixture = new ChocolateyPackerWithNuSpecFixture(); fixture.NuSpecFilePath = "./nonexisting.nuspec"; // When var result = Record.Exception(() => fixture.Run()); // Then Assert.IsCakeException(result, "Could not find nuspec file '/Working/nonexisting.nuspec'."); } [Fact] public void Should_Throw_If_Temporary_Nuspec_Already_Exist() { // Given var fixture = new ChocolateyPackerWithNuSpecFixture(); fixture.GivenTemporaryNuSpecAlreadyExist(); // When var result = Record.Exception(() => fixture.Run()); // Then Assert.IsCakeException(result, "Could not create the nuspec file '/Working/existing.temp.nuspec' since it already exist."); } [Theory] [InlineData(true, "pack -d -y \"/Working/existing.temp.nuspec\"")] [InlineData(false, "pack -y \"/Working/existing.temp.nuspec\"")] public void Should_Add_Debug_Flag_To_Arguments_If_Set(bool debug, string expected) { // Given var fixture = new ChocolateyPackerWithNuSpecFixture(); fixture.Settings.Debug = debug; // When var result = fixture.Run(); // Then Assert.Equal(expected, result.Args); } [Theory] [InlineData(true, "pack -v -y \"/Working/existing.temp.nuspec\"")] [InlineData(false, "pack -y \"/Working/existing.temp.nuspec\"")] public void Should_Add_Verbose_Flag_To_Arguments_If_Set(bool verbose, string expected) { // Given var fixture = new ChocolateyPackerWithNuSpecFixture(); fixture.Settings.Verbose = verbose; // When var result = fixture.Run(); // Then Assert.Equal(expected, result.Args); } [Theory] [InlineData(true, "pack -y -f \"/Working/existing.temp.nuspec\"")] [InlineData(false, "pack -y \"/Working/existing.temp.nuspec\"")] public void Should_Add_Force_Flag_To_Arguments_If_Set(bool force, string expected) { // Given var fixture = new ChocolateyPackerWithNuSpecFixture(); fixture.Settings.Force = force; // When var result = fixture.Run(); // Then Assert.Equal(expected, result.Args); } [Theory] [InlineData(true, "pack -y --noop \"/Working/existing.temp.nuspec\"")] [InlineData(false, "pack -y \"/Working/existing.temp.nuspec\"")] public void Should_Add_Noop_Flag_To_Arguments_If_Set(bool noop, string expected) { // Given var fixture = new ChocolateyPackerWithNuSpecFixture(); fixture.Settings.Noop = noop; // When var result = fixture.Run(); // Then Assert.Equal(expected, result.Args); } [Theory] [InlineData(true, "pack -y -r \"/Working/existing.temp.nuspec\"")] [InlineData(false, "pack -y \"/Working/existing.temp.nuspec\"")] public void Should_Add_LimitOutput_Flag_To_Arguments_If_Set(bool limitOutput, string expected) { // Given var fixture = new ChocolateyPackerWithNuSpecFixture(); fixture.Settings.LimitOutput = limitOutput; // When var result = fixture.Run(); // Then Assert.Equal(expected, result.Args); } [Theory] [InlineData(5, "pack -y --execution-timeout \"5\" \"/Working/existing.temp.nuspec\"")] [InlineData(0, "pack -y \"/Working/existing.temp.nuspec\"")] public void Should_Add_ExecutionTimeout_To_Arguments_If_Set(int executionTimeout, string expected) { // Given var fixture = new ChocolateyPackerWithNuSpecFixture(); fixture.Settings.ExecutionTimeout = executionTimeout; // When var result = fixture.Run(); // Then Assert.Equal(expected, result.Args); } [Theory] [InlineData(@"c:\temp", "pack -y -c \"c:\\temp\" \"/Working/existing.temp.nuspec\"")] [InlineData("", "pack -y \"/Working/existing.temp.nuspec\"")] public void Should_Add_CacheLocation_Flag_To_Arguments_If_Set(string cacheLocation, string expected) { // Given var fixture = new ChocolateyPackerWithNuSpecFixture(); fixture.Settings.CacheLocation = cacheLocation; // When var result = fixture.Run(); // Then Assert.Equal(expected, result.Args); } [Theory] [InlineData(true, "pack -y --allowunofficial \"/Working/existing.temp.nuspec\"")] [InlineData(false, "pack -y \"/Working/existing.temp.nuspec\"")] public void Should_Add_AllowUnofficial_Flag_To_Arguments_If_Set(bool allowUnofficial, string expected) { // Given var fixture = new ChocolateyPackerWithNuSpecFixture(); fixture.Settings.AllowUnofficial = allowUnofficial; // When var result = fixture.Run(); // Then Assert.Equal(expected, result.Args); } [Fact] public void Should_Add_Version_To_Arguments_If_Not_Null() { // Given var fixture = new ChocolateyPackerWithNuSpecFixture(); fixture.Settings.Version = "1.0.0"; // When var result = fixture.Run(); // Then Assert.Equal("pack -y --version \"1.0.0\" " + "\"/Working/existing.temp.nuspec\"", result.Args); } [Fact] public void Should_Add_Metadata_Element_To_Nuspec_If_Missing() { // Given var fixture = new ChocolateyPackerWithNuSpecFixture(); fixture.WithNuSpecXml(Resources.ChocolateyNuspec_NoMetadataElement); fixture.Settings.Id = "The ID"; fixture.Settings.Title = "The title"; fixture.Settings.Version = "The version"; fixture.Settings.Authors = new[] { "Author #1", "Author #2" }; fixture.Settings.Owners = new[] { "Owner #1", "Owner #2" }; fixture.Settings.Summary = "The summary"; fixture.Settings.Description = "The description"; fixture.Settings.ProjectUrl = new Uri("https://project.com"); fixture.Settings.PackageSourceUrl = new Uri("https://packagesource.com"); fixture.Settings.ProjectSourceUrl = new Uri("https://projectsource.com"); fixture.Settings.DocsUrl = new Uri("https://docs.com"); fixture.Settings.MailingListUrl = new Uri("https://mailing.com"); fixture.Settings.BugTrackerUrl = new Uri("https://bug.com"); fixture.Settings.Tags = new[] { "Tag1", "Tag2", "Tag3" }; fixture.Settings.Copyright = "The copyright"; fixture.Settings.LicenseUrl = new Uri("https://license.com"); fixture.Settings.RequireLicenseAcceptance = true; fixture.Settings.IconUrl = new Uri("https://icon.com"); fixture.Settings.ReleaseNotes = new[] { "Line #1", "Line #2", "Line #3" }; // When var result = fixture.Run(); // Then Assert.Equal( Resources.ChocolateyNuspec_Metadata.NormalizeLineEndings(), result.NuspecContent.NormalizeLineEndings()); } [Fact] public void Should_Replace_Template_Tokens_In_Nuspec() { // Given var fixture = new ChocolateyPackerWithNuSpecFixture(); fixture.Settings.Id = "The ID"; fixture.Settings.Title = "The title"; fixture.Settings.Version = "The version"; fixture.Settings.Authors = new[] { "Author #1", "Author #2" }; fixture.Settings.Owners = new[] { "Owner #1", "Owner #2" }; fixture.Settings.Summary = "The summary"; fixture.Settings.Description = "The description"; fixture.Settings.ProjectUrl = new Uri("https://project.com"); fixture.Settings.PackageSourceUrl = new Uri("https://packagesource.com"); fixture.Settings.ProjectSourceUrl = new Uri("https://projectsource.com"); fixture.Settings.DocsUrl = new Uri("https://docs.com"); fixture.Settings.MailingListUrl = new Uri("https://mailing.com"); fixture.Settings.BugTrackerUrl = new Uri("https://bug.com"); fixture.Settings.Tags = new[] { "Tag1", "Tag2", "Tag3" }; fixture.Settings.Copyright = "The copyright"; fixture.Settings.LicenseUrl = new Uri("https://license.com"); fixture.Settings.RequireLicenseAcceptance = true; fixture.Settings.IconUrl = new Uri("https://icon.com"); fixture.Settings.ReleaseNotes = new[] { "Line #1", "Line #2", "Line #3" }; // When var result = fixture.Run(); // Then Assert.Equal( Resources.ChocolateyNuspec_Metadata.NormalizeLineEndings(), result.NuspecContent.NormalizeLineEndings()); } [Fact] public void Should_Replace_Template_Tokens_In_Nuspec_Without_Namespaces() { // Given var fixture = new ChocolateyPackerWithNuSpecFixture(); fixture.WithNuSpecXml(Resources.ChocolateyNuspec_NoMetadataValues_WithoutNamespaces); fixture.Settings.Id = "The ID"; fixture.Settings.Title = "The title"; fixture.Settings.Version = "The version"; fixture.Settings.Authors = new[] { "Author #1", "Author #2" }; fixture.Settings.Owners = new[] { "Owner #1", "Owner #2" }; fixture.Settings.Summary = "The summary"; fixture.Settings.Description = "The description"; fixture.Settings.ProjectUrl = new Uri("https://project.com"); fixture.Settings.PackageSourceUrl = new Uri("https://packagesource.com"); fixture.Settings.ProjectSourceUrl = new Uri("https://projectsource.com"); fixture.Settings.DocsUrl = new Uri("https://docs.com"); fixture.Settings.MailingListUrl = new Uri("https://mailing.com"); fixture.Settings.BugTrackerUrl = new Uri("https://bug.com"); fixture.Settings.Tags = new[] { "Tag1", "Tag2", "Tag3" }; fixture.Settings.Copyright = "The copyright"; fixture.Settings.LicenseUrl = new Uri("https://license.com"); fixture.Settings.RequireLicenseAcceptance = true; fixture.Settings.IconUrl = new Uri("https://icon.com"); fixture.Settings.ReleaseNotes = new[] { "Line #1", "Line #2", "Line #3" }; // When var result = fixture.Run(); // Then Assert.Equal( Resources.ChocolateyNuspec_Metadata_WithoutNamespaces.NormalizeLineEndings(), result.NuspecContent.NormalizeLineEndings()); } } [Fact] public void Should_Replace_Template_Tokens_In_Nuspec_With_Files() { // Given var fixture = new ChocolateyPackerWithNuSpecFixture(); fixture.Settings.Id = "The ID"; fixture.Settings.Title = "The title"; fixture.Settings.Version = "The version"; fixture.Settings.Authors = new[] { "Author #1", "Author #2" }; fixture.Settings.Owners = new[] { "Owner #1", "Owner #2" }; fixture.Settings.Summary = "The summary"; fixture.Settings.Description = "The description"; fixture.Settings.ProjectUrl = new Uri("https://project.com"); fixture.Settings.PackageSourceUrl = new Uri("https://packagesource.com"); fixture.Settings.ProjectSourceUrl = new Uri("https://projectsource.com"); fixture.Settings.DocsUrl = new Uri("https://docs.com"); fixture.Settings.MailingListUrl = new Uri("https://mailing.com"); fixture.Settings.BugTrackerUrl = new Uri("https://bug.com"); fixture.Settings.Tags = new[] { "Tag1", "Tag2", "Tag3" }; fixture.Settings.Copyright = "The copyright"; fixture.Settings.LicenseUrl = new Uri("https://license.com"); fixture.Settings.RequireLicenseAcceptance = true; fixture.Settings.IconUrl = new Uri("https://icon.com"); fixture.Settings.ReleaseNotes = new[] { "Line #1", "Line #2", "Line #3" }; fixture.Settings.Files = new[] { new ChocolateyNuSpecContent { Source = @"tools\**", Target = "tools" }, }; // When var result = fixture.Run(); // Then Assert.Equal( Resources.ChocolateyNuspec_Metadata.NormalizeLineEndings(), result.NuspecContent.NormalizeLineEndings()); } [Fact] public void Should_Replace_Template_Tokens_In_Nuspec_With_Files_Without_Namespaces() { // Given var fixture = new ChocolateyPackerWithNuSpecFixture(); fixture.WithNuSpecXml(Resources.ChocolateyNuspec_NoMetadataValues_WithoutNamespaces); fixture.Settings.Id = "The ID"; fixture.Settings.Title = "The title"; fixture.Settings.Version = "The version"; fixture.Settings.Authors = new[] { "Author #1", "Author #2" }; fixture.Settings.Owners = new[] { "Owner #1", "Owner #2" }; fixture.Settings.Summary = "The summary"; fixture.Settings.Description = "The description"; fixture.Settings.ProjectUrl = new Uri("https://project.com"); fixture.Settings.PackageSourceUrl = new Uri("https://packagesource.com"); fixture.Settings.ProjectSourceUrl = new Uri("https://projectsource.com"); fixture.Settings.DocsUrl = new Uri("https://docs.com"); fixture.Settings.MailingListUrl = new Uri("https://mailing.com"); fixture.Settings.BugTrackerUrl = new Uri("https://bug.com"); fixture.Settings.Tags = new[] { "Tag1", "Tag2", "Tag3" }; fixture.Settings.Copyright = "The copyright"; fixture.Settings.LicenseUrl = new Uri("https://license.com"); fixture.Settings.RequireLicenseAcceptance = true; fixture.Settings.IconUrl = new Uri("https://icon.com"); fixture.Settings.ReleaseNotes = new[] { "Line #1", "Line #2", "Line #3" }; fixture.Settings.Files = new[] { new ChocolateyNuSpecContent { Source = @"tools\**", Target = "tools" }, }; // When var result = fixture.Run(); // Then Assert.Equal( Resources.ChocolateyNuspec_Metadata_WithoutNamespaces.NormalizeLineEndings(), result.NuspecContent.NormalizeLineEndings()); } public sealed class TheSettingsPackMethod { [Fact] public void Should_Pack_If_Sufficient_Settings_Specified() { // Given var fixture = new ChocolateyPackerWithoutNuSpecFixture(); fixture.Settings.Id = "nonexisting"; fixture.Settings.Version = "1.0.0"; fixture.Settings.Description = "The description"; fixture.Settings.Authors = new[] { "Author #1", "Author #2" }; fixture.Settings.Files = new[] { new ChocolateyNuSpecContent { Source = @"tools\**" } }; // When var result = fixture.Run(); // Then Assert.Equal("pack -y --version \"1.0.0\" " + "\"/Working/nonexisting.temp.nuspec\"", result.Args); } [Fact] public void Should_Throw_If_Id_Setting_Not_Specified() { // Given var fixture = new ChocolateyPackerWithoutNuSpecFixture(); // When var result = Record.Exception(() => fixture.Run()); // Then Assert.IsCakeException(result, "Required setting Id not specified."); } [Fact] public void Should_Throw_If_Version_Setting_Not_Specified() { // Given var fixture = new ChocolateyPackerWithoutNuSpecFixture(); fixture.Settings.Id = "nonexisting"; // When var result = Record.Exception(() => fixture.Run()); // Then Assert.IsCakeException(result, "Required setting Version not specified."); } [Fact] public void Should_Throw_If_Authors_Setting_Not_Specified() { // Given var fixture = new ChocolateyPackerWithoutNuSpecFixture(); fixture.Settings.Id = "nonexisting"; fixture.Settings.Version = "1.0.0"; // When var result = Record.Exception(() => fixture.Run()); // Then Assert.IsCakeException(result, "Required setting Authors not specified."); } [Fact] public void Should_Throw_If_Description_Setting_Not_Specified() { // Given var fixture = new ChocolateyPackerWithoutNuSpecFixture(); fixture.Settings.Id = "nonexisting"; fixture.Settings.Version = "1.0.0"; fixture.Settings.Authors = new[] { "Author #1", "Author #2" }; // When var result = Record.Exception(() => fixture.Run()); // Then Assert.IsCakeException(result, "Required setting Description not specified."); } [Fact] public void Should_Throw_If_Files_Setting_Not_Specified() { // Given var fixture = new ChocolateyPackerWithoutNuSpecFixture(); fixture.Settings.Id = "nonexisting"; fixture.Settings.Version = "1.0.0"; fixture.Settings.Authors = new[] { "Author #1", "Author #2" }; fixture.Settings.Description = "The description"; // When var result = Record.Exception(() => fixture.Run()); // Then Assert.IsCakeException(result, "Required setting Files not specified."); } } } }
41.063228
139
0.537826
[ "MIT" ]
EvilMindz/cake
src/Cake.Common.Tests/Unit/Tools/Chocolatey/Pack/ChocolateyPackerTests.cs
24,681
C#
// Copyright (c) 2019, WebsitePanel-Support.net. // Distributed by websitepanel-support.net // Build and fixed by Key4ce - IT Professionals // https://www.key4ce.com // // Original source: // Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using WebsitePanel.Providers.Mail; namespace WebsitePanel.Portal.ProviderControls { public partial class MDaemon_EditForwarding : WebsitePanelControlBase, IMailEditForwardingControl { protected void Page_Load(object sender, EventArgs e) { } public void BindItem(MailAlias item) { } public void SaveItem(MailAlias item) { } } }
37.220588
99
0.728171
[ "BSD-3-Clause" ]
Key4ce/Websitepanel
WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ProviderControls/MDaemon_EditForwarding.ascx.cs
2,531
C#
using Godot; namespace GDMechanic.Extensions { public static class Vector3Extensions { public static Vector2 ToVector2(this Vector3 vector3) { return new Vector2(vector3.x, vector3.y); } public static Vector2[] ToVector2(this Vector3[] vector3s) { Vector2[] vector2s = new Vector2[vector3s.Length]; for (int i = 0; i < vector3s.Length; i++) { vector2s[i] = vector3s[i].ToVector2(); } return vector2s; } } }
19.391304
60
0.67713
[ "MIT" ]
11clock/GDMechanic
GDMechanic/Extensions/Vector3Extensions.cs
446
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Ornament.Entities { /// <summary> /// For a discussion of this object, see /// http://devlicio.us/blogs/billy_mccafferty/archive/2007/04/25/using-equals-gethashcode-effectively.aspx /// </summary> public abstract class EntityWithTypedId<TId> : ValidatableObject, IEntityWithTypedId<TId> where TId:IEquatable<TId> { /// <summary> /// To help ensure hash code uniqueness, a carefully selected random number multiplier /// is used within the calculation. Goodrich and Tamassia's Data Structures and /// Algorithms in Java asserts that 31, 33, 37, 39 and 41 will produce the fewest number /// of collissions. See http://computinglife.wordpress.com/2008/11/20/why-do-hash-functions-use-prime-numbers/ /// for more information. /// </summary> private const int HashMultiplier = 31; private int? cachedHashcode; /// <summary> /// Gets or sets the ID. /// </summary> /// <remarks> /// <para> /// The ID may be of type <c>string</c>, <c>int</c>, a custom type, etc. /// The setter is protected to allow unit tests to set this property via reflection /// and to allow domain objects more flexibility in setting this for those objects /// with assigned IDs. It's virtual to allow NHibernate-backed objects to be lazily /// loaded. This is ignored for XML serialization because it does not have a public /// setter (which is very much by design). See the FAQ within the documentation if /// you'd like to have the ID XML serialized. /// </para> /// </remarks> public virtual TId Id { get; protected set; } /// <summary> /// Determines whether the specified <see cref="System.Object" /> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="object" /> to compare with the current <see cref="object" />.</param> /// <returns><c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>.</returns> public override bool Equals(object obj) { var compareTo = obj as EntityWithTypedId<TId>; if (ReferenceEquals(this, compareTo)) { return true; } if (compareTo == null || !GetType().Equals(compareTo.GetTypeUnproxied())) { return false; } if (HasSameNonDefaultIdAs(compareTo)) { return true; } // Since the Ids aren't the same, both of them must be transient to // compare domain signatures; because if one is transient and the // other is a persisted entity, then they cannot be the same object. return IsTransient() && compareTo.IsTransient() && HasSameObjectSignatureAs(compareTo); } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns> /// <remarks> /// This is used to provide the hash code identifier of an object using the signature /// properties of the object; although it's necessary for NHibernate's use, this can /// also be useful for business logic purposes and has been included in this base /// class, accordingly. Since it is recommended that GetHashCode change infrequently, /// if at all, in an object's lifetime, it's important that properties are carefully /// selected which truly represent the signature of an object. /// </remarks> public override int GetHashCode() { if (cachedHashcode.HasValue) { return cachedHashcode.Value; } if (IsTransient()) { cachedHashcode = base.GetHashCode(); } else { unchecked { // It's possible for two objects to return the same hash code based on // identically valued properties, even if they're of two different types, // so we include the object's type in the hash calculation var hashCode = GetType().GetHashCode(); cachedHashcode = (hashCode*HashMultiplier) ^ Id.GetHashCode(); } } return cachedHashcode.Value; } /// <summary> /// Returns a value indicating whether the current object is transient. /// </summary> /// <remarks> /// Transient objects are not associated with an item already in storage. For instance, /// a Customer is transient if its ID is 0. It's virtual to allow NHibernate-backed /// objects to be lazily loaded. /// </remarks> public virtual bool IsTransient() { return Id == null || Id.Equals(default(TId)); } /// <summary> /// Returns the signature properties that are specific to the type of the current object. /// </summary> /// <remarks> /// If you choose NOT to override this method (which will be the most common scenario), /// then you should decorate the appropriate property(s) with the <see cref="DomainSignatureAttribute" /> /// attribute and they will be compared automatically. This is the preferred method of /// managing the domain signature of entity objects. This ensures that the entity has at /// least one property decorated with the <see cref="DomainSignatureAttribute" /> attribute. /// </remarks> protected override IEnumerable<PropertyInfo> GetTypeSpecificSignatureProperties() { #if DNX451 return this.GetType().GetProperties().Where( p => Attribute.IsDefined(p, typeof(DomainSignatureAttribute), true)); #else return (from prop in GetType().GetRuntimeProperties() let p = prop.GetCustomAttribute(typeof (DomainSignatureAttribute), true) where p != null select prop).ToList(); #endif } /// <summary> /// Returns a value indicating whether the current entity and the provided entity have /// the same ID values and the IDs are not of the default ID value. /// </summary> /// <returns> /// <c>true</c> if the current entity and the provided entity have the same ID values and the IDs are not of the /// default ID value; otherwise; <c>false</c>. /// </returns> private bool HasSameNonDefaultIdAs(EntityWithTypedId<TId> compareTo) { return !IsTransient() && !compareTo.IsTransient() && Id.Equals(compareTo.Id); } } }
44.402439
140
0.58212
[ "MIT" ]
luqizheng/Ornament.Core
src/Ornament.Domain/Entities/EntityWithTypedId.cs
7,282
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 13.05.2021. using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using xdb=lcpi.data.oledb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.GreaterThan.Complete.NullableTimeSpan.TimeSpan{ //////////////////////////////////////////////////////////////////////////////// using T_DATA1 =System.Nullable<System.TimeSpan>; using T_DATA2 =System.TimeSpan; using T_DATA1_U=System.TimeSpan; using T_DATA2_U=System.TimeSpan; using DB_TABLE=LocalDbObjNames.TEST_MODIFY_ROW2; //////////////////////////////////////////////////////////////////////////////// //class TestSet_001__fields__03__NV public static class TestSet_001__fields__03__NV { private const string c_NameOf__TABLE =DB_TABLE.Name; private const string c_NameOf__COL_DATA1 =DB_TABLE.Columns.COL_for_TimeSpan; private const string c_NameOf__COL_DATA2 =DB_TABLE.Columns.COL2_for_TimeSpan; private sealed class MyContext:TestBaseDbContext { [Table(c_NameOf__TABLE)] public sealed class TEST_RECORD { [Key] [Column("TEST_ID")] public System.Int64? TEST_ID { get; set; } [Column(c_NameOf__COL_DATA1)] public T_DATA1 COL_DATA1 { get; set; } [Column(c_NameOf__COL_DATA2)] public T_DATA2 COL_DATA2 { get; set; } };//class TEST_RECORD //---------------------------------------------------------------------- public DbSet<TEST_RECORD> testTable { get; set; } //---------------------------------------------------------------------- public MyContext(xdb.OleDbTransaction tr) :base(tr) { }//MyContext };//class MyContext //----------------------------------------------------------------------- [Test] public static void Test_001() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA2 c_value2=new T_DATA2_U(12,14,34).Add(new System.TimeSpan(1000*1234)).Add(new System.TimeSpan(0)); System.Int64? testID=Helper__InsertRow(db,null,c_value2); var recs=db.testTable.Where(r => (r.COL_DATA1 /*OP{*/ > /*}OP*/ r.COL_DATA2) && r.TEST_ID==testID); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE (").N("t",c_NameOf__COL_DATA1).T(" > ").N("t",c_NameOf__COL_DATA2).T(") AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")")); }//using db tr.Rollback(); }//using tr }//using cn }//Test_001 //----------------------------------------------------------------------- [Test] public static void Test_002() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA2 c_value2=new T_DATA2_U(12,14,34).Add(new System.TimeSpan(1000*1234)).Add(new System.TimeSpan(0)); System.Int64? testID=Helper__InsertRow(db,null,c_value2); var recs=db.testTable.Where(r => !(r.COL_DATA1 /*OP{*/ > /*}OP*/ r.COL_DATA2) && r.TEST_ID==testID); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE NOT (").N("t",c_NameOf__COL_DATA1).T(" > ").N("t",c_NameOf__COL_DATA2).T(") AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")")); }//using db tr.Rollback(); }//using tr }//using cn }//Test_002 //Helper methods -------------------------------------------------------- private static System.Int64 Helper__InsertRow(MyContext db, T_DATA1 valueForColData1, T_DATA2 valueForColData2) { var newRecord=new MyContext.TEST_RECORD(); newRecord.COL_DATA1 =valueForColData1; newRecord.COL_DATA2 =valueForColData2; db.testTable.Add(newRecord); db.SaveChanges(); db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("INSERT INTO ").N(c_NameOf__TABLE).T(" (").N(c_NameOf__COL_DATA1).T(", ").N(c_NameOf__COL_DATA2).T(")").EOL() .T("VALUES (").P("p0").T(", ").P("p1").T(")").EOL() .T("RETURNING ").N("TEST_ID").EOL() .T("INTO ").P("p2").T(";")); Assert.IsTrue (newRecord.TEST_ID.HasValue); Console.WriteLine("TEST_ID: {0}",newRecord.TEST_ID.Value); return newRecord.TEST_ID.Value; }//Helper__InsertRow };//class TestSet_001__fields__03__NV //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.GreaterThan.Complete.NullableTimeSpan.TimeSpan
33.656442
155
0.581845
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/Operators/SET_001/GreaterThan/Complete/NullableTimeSpan/TimeSpan/TestSet_001__fields__03__NV.cs
5,488
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DecimalToBinaryConverter { public class DecimalToBinaryConverter { public static void Main() { var input = int.Parse(Console.ReadLine()); var stack = new Stack<int>(); if (input == 0) { Console.WriteLine(0); } else { while (input != 0 ) { stack.Push(input % 2); input /= 2; } } while (stack.Count > 0) { Console.Write(stack.Pop()); } Console.WriteLine(); } } }
20.842105
54
0.436869
[ "MIT" ]
varbanov88/C-Advanced
StacksAndQueues/DecimalToBinaryConverter/DecimalToBinaryConverter.cs
794
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 Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // </auto-generated> //------------------------------------------------------------------------------ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet // // 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; // Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP namespace UnitsNet.Extensions.NumberToSpecificEnergy { public static class NumberToSpecificEnergyExtensions { #region CaloriePerGram /// <inheritdoc cref="SpecificEnergy.FromCaloriesPerGram(double)"/> public static SpecificEnergy CaloriesPerGram(this int value) => SpecificEnergy.FromCaloriesPerGram(value); /// <inheritdoc cref="SpecificEnergy.FromCaloriesPerGram(double?)"/> public static SpecificEnergy? CaloriesPerGram(this int? value) => SpecificEnergy.FromCaloriesPerGram(value); /// <inheritdoc cref="SpecificEnergy.FromCaloriesPerGram(double)"/> public static SpecificEnergy CaloriesPerGram(this long value) => SpecificEnergy.FromCaloriesPerGram(value); /// <inheritdoc cref="SpecificEnergy.FromCaloriesPerGram(double?)"/> public static SpecificEnergy? CaloriesPerGram(this long? value) => SpecificEnergy.FromCaloriesPerGram(value); /// <inheritdoc cref="SpecificEnergy.FromCaloriesPerGram(double)"/> public static SpecificEnergy CaloriesPerGram(this double value) => SpecificEnergy.FromCaloriesPerGram(value); /// <inheritdoc cref="SpecificEnergy.FromCaloriesPerGram(double?)"/> public static SpecificEnergy? CaloriesPerGram(this double? value) => SpecificEnergy.FromCaloriesPerGram(value); /// <inheritdoc cref="SpecificEnergy.FromCaloriesPerGram(double)"/> public static SpecificEnergy CaloriesPerGram(this float value) => SpecificEnergy.FromCaloriesPerGram(value); /// <inheritdoc cref="SpecificEnergy.FromCaloriesPerGram(double?)"/> public static SpecificEnergy? CaloriesPerGram(this float? value) => SpecificEnergy.FromCaloriesPerGram(value); /// <inheritdoc cref="SpecificEnergy.FromCaloriesPerGram(double)"/> public static SpecificEnergy CaloriesPerGram(this decimal value) => SpecificEnergy.FromCaloriesPerGram(Convert.ToDouble(value)); /// <inheritdoc cref="SpecificEnergy.FromCaloriesPerGram(double?)"/> public static SpecificEnergy? CaloriesPerGram(this decimal? value) => SpecificEnergy.FromCaloriesPerGram(value == null ? (double?)null : Convert.ToDouble(value.Value)); #endregion #region JoulePerKilogram /// <inheritdoc cref="SpecificEnergy.FromJoulesPerKilogram(double)"/> public static SpecificEnergy JoulesPerKilogram(this int value) => SpecificEnergy.FromJoulesPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromJoulesPerKilogram(double?)"/> public static SpecificEnergy? JoulesPerKilogram(this int? value) => SpecificEnergy.FromJoulesPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromJoulesPerKilogram(double)"/> public static SpecificEnergy JoulesPerKilogram(this long value) => SpecificEnergy.FromJoulesPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromJoulesPerKilogram(double?)"/> public static SpecificEnergy? JoulesPerKilogram(this long? value) => SpecificEnergy.FromJoulesPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromJoulesPerKilogram(double)"/> public static SpecificEnergy JoulesPerKilogram(this double value) => SpecificEnergy.FromJoulesPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromJoulesPerKilogram(double?)"/> public static SpecificEnergy? JoulesPerKilogram(this double? value) => SpecificEnergy.FromJoulesPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromJoulesPerKilogram(double)"/> public static SpecificEnergy JoulesPerKilogram(this float value) => SpecificEnergy.FromJoulesPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromJoulesPerKilogram(double?)"/> public static SpecificEnergy? JoulesPerKilogram(this float? value) => SpecificEnergy.FromJoulesPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromJoulesPerKilogram(double)"/> public static SpecificEnergy JoulesPerKilogram(this decimal value) => SpecificEnergy.FromJoulesPerKilogram(Convert.ToDouble(value)); /// <inheritdoc cref="SpecificEnergy.FromJoulesPerKilogram(double?)"/> public static SpecificEnergy? JoulesPerKilogram(this decimal? value) => SpecificEnergy.FromJoulesPerKilogram(value == null ? (double?)null : Convert.ToDouble(value.Value)); #endregion #region KilocaloriePerGram /// <inheritdoc cref="SpecificEnergy.FromKilocaloriesPerGram(double)"/> public static SpecificEnergy KilocaloriesPerGram(this int value) => SpecificEnergy.FromKilocaloriesPerGram(value); /// <inheritdoc cref="SpecificEnergy.FromKilocaloriesPerGram(double?)"/> public static SpecificEnergy? KilocaloriesPerGram(this int? value) => SpecificEnergy.FromKilocaloriesPerGram(value); /// <inheritdoc cref="SpecificEnergy.FromKilocaloriesPerGram(double)"/> public static SpecificEnergy KilocaloriesPerGram(this long value) => SpecificEnergy.FromKilocaloriesPerGram(value); /// <inheritdoc cref="SpecificEnergy.FromKilocaloriesPerGram(double?)"/> public static SpecificEnergy? KilocaloriesPerGram(this long? value) => SpecificEnergy.FromKilocaloriesPerGram(value); /// <inheritdoc cref="SpecificEnergy.FromKilocaloriesPerGram(double)"/> public static SpecificEnergy KilocaloriesPerGram(this double value) => SpecificEnergy.FromKilocaloriesPerGram(value); /// <inheritdoc cref="SpecificEnergy.FromKilocaloriesPerGram(double?)"/> public static SpecificEnergy? KilocaloriesPerGram(this double? value) => SpecificEnergy.FromKilocaloriesPerGram(value); /// <inheritdoc cref="SpecificEnergy.FromKilocaloriesPerGram(double)"/> public static SpecificEnergy KilocaloriesPerGram(this float value) => SpecificEnergy.FromKilocaloriesPerGram(value); /// <inheritdoc cref="SpecificEnergy.FromKilocaloriesPerGram(double?)"/> public static SpecificEnergy? KilocaloriesPerGram(this float? value) => SpecificEnergy.FromKilocaloriesPerGram(value); /// <inheritdoc cref="SpecificEnergy.FromKilocaloriesPerGram(double)"/> public static SpecificEnergy KilocaloriesPerGram(this decimal value) => SpecificEnergy.FromKilocaloriesPerGram(Convert.ToDouble(value)); /// <inheritdoc cref="SpecificEnergy.FromKilocaloriesPerGram(double?)"/> public static SpecificEnergy? KilocaloriesPerGram(this decimal? value) => SpecificEnergy.FromKilocaloriesPerGram(value == null ? (double?)null : Convert.ToDouble(value.Value)); #endregion #region KilojoulePerKilogram /// <inheritdoc cref="SpecificEnergy.FromKilojoulesPerKilogram(double)"/> public static SpecificEnergy KilojoulesPerKilogram(this int value) => SpecificEnergy.FromKilojoulesPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromKilojoulesPerKilogram(double?)"/> public static SpecificEnergy? KilojoulesPerKilogram(this int? value) => SpecificEnergy.FromKilojoulesPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromKilojoulesPerKilogram(double)"/> public static SpecificEnergy KilojoulesPerKilogram(this long value) => SpecificEnergy.FromKilojoulesPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromKilojoulesPerKilogram(double?)"/> public static SpecificEnergy? KilojoulesPerKilogram(this long? value) => SpecificEnergy.FromKilojoulesPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromKilojoulesPerKilogram(double)"/> public static SpecificEnergy KilojoulesPerKilogram(this double value) => SpecificEnergy.FromKilojoulesPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromKilojoulesPerKilogram(double?)"/> public static SpecificEnergy? KilojoulesPerKilogram(this double? value) => SpecificEnergy.FromKilojoulesPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromKilojoulesPerKilogram(double)"/> public static SpecificEnergy KilojoulesPerKilogram(this float value) => SpecificEnergy.FromKilojoulesPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromKilojoulesPerKilogram(double?)"/> public static SpecificEnergy? KilojoulesPerKilogram(this float? value) => SpecificEnergy.FromKilojoulesPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromKilojoulesPerKilogram(double)"/> public static SpecificEnergy KilojoulesPerKilogram(this decimal value) => SpecificEnergy.FromKilojoulesPerKilogram(Convert.ToDouble(value)); /// <inheritdoc cref="SpecificEnergy.FromKilojoulesPerKilogram(double?)"/> public static SpecificEnergy? KilojoulesPerKilogram(this decimal? value) => SpecificEnergy.FromKilojoulesPerKilogram(value == null ? (double?)null : Convert.ToDouble(value.Value)); #endregion #region KilowattHourPerKilogram /// <inheritdoc cref="SpecificEnergy.FromKilowattHoursPerKilogram(double)"/> public static SpecificEnergy KilowattHoursPerKilogram(this int value) => SpecificEnergy.FromKilowattHoursPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromKilowattHoursPerKilogram(double?)"/> public static SpecificEnergy? KilowattHoursPerKilogram(this int? value) => SpecificEnergy.FromKilowattHoursPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromKilowattHoursPerKilogram(double)"/> public static SpecificEnergy KilowattHoursPerKilogram(this long value) => SpecificEnergy.FromKilowattHoursPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromKilowattHoursPerKilogram(double?)"/> public static SpecificEnergy? KilowattHoursPerKilogram(this long? value) => SpecificEnergy.FromKilowattHoursPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromKilowattHoursPerKilogram(double)"/> public static SpecificEnergy KilowattHoursPerKilogram(this double value) => SpecificEnergy.FromKilowattHoursPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromKilowattHoursPerKilogram(double?)"/> public static SpecificEnergy? KilowattHoursPerKilogram(this double? value) => SpecificEnergy.FromKilowattHoursPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromKilowattHoursPerKilogram(double)"/> public static SpecificEnergy KilowattHoursPerKilogram(this float value) => SpecificEnergy.FromKilowattHoursPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromKilowattHoursPerKilogram(double?)"/> public static SpecificEnergy? KilowattHoursPerKilogram(this float? value) => SpecificEnergy.FromKilowattHoursPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromKilowattHoursPerKilogram(double)"/> public static SpecificEnergy KilowattHoursPerKilogram(this decimal value) => SpecificEnergy.FromKilowattHoursPerKilogram(Convert.ToDouble(value)); /// <inheritdoc cref="SpecificEnergy.FromKilowattHoursPerKilogram(double?)"/> public static SpecificEnergy? KilowattHoursPerKilogram(this decimal? value) => SpecificEnergy.FromKilowattHoursPerKilogram(value == null ? (double?)null : Convert.ToDouble(value.Value)); #endregion #region MegajoulePerKilogram /// <inheritdoc cref="SpecificEnergy.FromMegajoulesPerKilogram(double)"/> public static SpecificEnergy MegajoulesPerKilogram(this int value) => SpecificEnergy.FromMegajoulesPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromMegajoulesPerKilogram(double?)"/> public static SpecificEnergy? MegajoulesPerKilogram(this int? value) => SpecificEnergy.FromMegajoulesPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromMegajoulesPerKilogram(double)"/> public static SpecificEnergy MegajoulesPerKilogram(this long value) => SpecificEnergy.FromMegajoulesPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromMegajoulesPerKilogram(double?)"/> public static SpecificEnergy? MegajoulesPerKilogram(this long? value) => SpecificEnergy.FromMegajoulesPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromMegajoulesPerKilogram(double)"/> public static SpecificEnergy MegajoulesPerKilogram(this double value) => SpecificEnergy.FromMegajoulesPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromMegajoulesPerKilogram(double?)"/> public static SpecificEnergy? MegajoulesPerKilogram(this double? value) => SpecificEnergy.FromMegajoulesPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromMegajoulesPerKilogram(double)"/> public static SpecificEnergy MegajoulesPerKilogram(this float value) => SpecificEnergy.FromMegajoulesPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromMegajoulesPerKilogram(double?)"/> public static SpecificEnergy? MegajoulesPerKilogram(this float? value) => SpecificEnergy.FromMegajoulesPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromMegajoulesPerKilogram(double)"/> public static SpecificEnergy MegajoulesPerKilogram(this decimal value) => SpecificEnergy.FromMegajoulesPerKilogram(Convert.ToDouble(value)); /// <inheritdoc cref="SpecificEnergy.FromMegajoulesPerKilogram(double?)"/> public static SpecificEnergy? MegajoulesPerKilogram(this decimal? value) => SpecificEnergy.FromMegajoulesPerKilogram(value == null ? (double?)null : Convert.ToDouble(value.Value)); #endregion #region MegawattHourPerKilogram /// <inheritdoc cref="SpecificEnergy.FromMegawattHoursPerKilogram(double)"/> public static SpecificEnergy MegawattHoursPerKilogram(this int value) => SpecificEnergy.FromMegawattHoursPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromMegawattHoursPerKilogram(double?)"/> public static SpecificEnergy? MegawattHoursPerKilogram(this int? value) => SpecificEnergy.FromMegawattHoursPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromMegawattHoursPerKilogram(double)"/> public static SpecificEnergy MegawattHoursPerKilogram(this long value) => SpecificEnergy.FromMegawattHoursPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromMegawattHoursPerKilogram(double?)"/> public static SpecificEnergy? MegawattHoursPerKilogram(this long? value) => SpecificEnergy.FromMegawattHoursPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromMegawattHoursPerKilogram(double)"/> public static SpecificEnergy MegawattHoursPerKilogram(this double value) => SpecificEnergy.FromMegawattHoursPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromMegawattHoursPerKilogram(double?)"/> public static SpecificEnergy? MegawattHoursPerKilogram(this double? value) => SpecificEnergy.FromMegawattHoursPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromMegawattHoursPerKilogram(double)"/> public static SpecificEnergy MegawattHoursPerKilogram(this float value) => SpecificEnergy.FromMegawattHoursPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromMegawattHoursPerKilogram(double?)"/> public static SpecificEnergy? MegawattHoursPerKilogram(this float? value) => SpecificEnergy.FromMegawattHoursPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromMegawattHoursPerKilogram(double)"/> public static SpecificEnergy MegawattHoursPerKilogram(this decimal value) => SpecificEnergy.FromMegawattHoursPerKilogram(Convert.ToDouble(value)); /// <inheritdoc cref="SpecificEnergy.FromMegawattHoursPerKilogram(double?)"/> public static SpecificEnergy? MegawattHoursPerKilogram(this decimal? value) => SpecificEnergy.FromMegawattHoursPerKilogram(value == null ? (double?)null : Convert.ToDouble(value.Value)); #endregion #region WattHourPerKilogram /// <inheritdoc cref="SpecificEnergy.FromWattHoursPerKilogram(double)"/> public static SpecificEnergy WattHoursPerKilogram(this int value) => SpecificEnergy.FromWattHoursPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromWattHoursPerKilogram(double?)"/> public static SpecificEnergy? WattHoursPerKilogram(this int? value) => SpecificEnergy.FromWattHoursPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromWattHoursPerKilogram(double)"/> public static SpecificEnergy WattHoursPerKilogram(this long value) => SpecificEnergy.FromWattHoursPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromWattHoursPerKilogram(double?)"/> public static SpecificEnergy? WattHoursPerKilogram(this long? value) => SpecificEnergy.FromWattHoursPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromWattHoursPerKilogram(double)"/> public static SpecificEnergy WattHoursPerKilogram(this double value) => SpecificEnergy.FromWattHoursPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromWattHoursPerKilogram(double?)"/> public static SpecificEnergy? WattHoursPerKilogram(this double? value) => SpecificEnergy.FromWattHoursPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromWattHoursPerKilogram(double)"/> public static SpecificEnergy WattHoursPerKilogram(this float value) => SpecificEnergy.FromWattHoursPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromWattHoursPerKilogram(double?)"/> public static SpecificEnergy? WattHoursPerKilogram(this float? value) => SpecificEnergy.FromWattHoursPerKilogram(value); /// <inheritdoc cref="SpecificEnergy.FromWattHoursPerKilogram(double)"/> public static SpecificEnergy WattHoursPerKilogram(this decimal value) => SpecificEnergy.FromWattHoursPerKilogram(Convert.ToDouble(value)); /// <inheritdoc cref="SpecificEnergy.FromWattHoursPerKilogram(double?)"/> public static SpecificEnergy? WattHoursPerKilogram(this decimal? value) => SpecificEnergy.FromWattHoursPerKilogram(value == null ? (double?)null : Convert.ToDouble(value.Value)); #endregion } } #endif
63.021739
194
0.753462
[ "MIT" ]
lavantgarde/UnitsNet
UnitsNet/GeneratedCode/Extensions/Number/NumberToSpecificEnergyExtensions.g.cs
20,295
C#
//-------------------------------------------------- // <copyright file="DatabaseUtilsUnitTests.cs" company="Magenic"> // Copyright 2021 Magenic, All rights Reserved // </copyright> // <summary>Database base utilities unit tests</summary> //-------------------------------------------------- using Magenic.Maqs.BaseDatabaseTest; using Magenic.Maqs.Utilities.Helper; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Data; using System.Diagnostics.CodeAnalysis; using System.Linq; namespace DatabaseUnitTests { /// <summary> /// Database utilities unit tests /// </summary> [TestClass] [ExcludeFromCodeCoverage] public class DatabaseUtilsUnitTests : BaseDatabaseTest { /// <summary> /// Check if we get the expect number of results /// </summary> [TestMethod] [TestCategory(TestCategories.Database)] public void VerifyDataTableCountMatch() { var states = DatabaseDriver.Query("SELECT * FROM States").ToList(); var statesTable = DatabaseUtils.ToDataTable(states); // Our database only has 49 states Assert.AreEqual(states.Count, statesTable.Rows.Count, "Expected 49 states."); Assert.AreEqual(49, statesTable.Rows.Count, "Expected 49 states."); } /// <summary> /// Check if column counts are equal /// </summary> [TestMethod] [TestCategory(TestCategories.Database)] public void VerifyDataTableColumnsCount() { var states = DatabaseDriver.Query("SELECT * FROM States").ToList(); var statesTable = DatabaseUtils.ToDataTable(states); // Validate Column Count Assert.AreEqual(3, statesTable.Columns.Count); Assert.AreEqual(((IDictionary<string, object>)states.First()).Keys.Count, statesTable.Columns.Count); } /// <summary> /// Check if the column names and datatype are equal /// </summary> [TestMethod] [TestCategory(TestCategories.Database)] public void VerifyDataTableColumnsMatch() { var states = DatabaseDriver.Query("SELECT * FROM States").ToList(); IDictionary<string, object> statesColumns = states.First(); var statesTable = DatabaseUtils.ToDataTable(states); // Loop through rows and validate for (int i = 0; i < statesTable.Columns.Count; i++) { var dynamicRowKey = statesColumns.Keys.ToList()[i]; var dynamicRowType = statesColumns[dynamicRowKey].GetType(); // Check name Assert.AreEqual(statesTable.Columns[i].ColumnName, dynamicRowKey); // Check Data Type Assert.AreEqual(statesTable.Columns[i].DataType, dynamicRowType); } } /// <summary> /// Check if the values are equal /// </summary> [TestMethod] [TestCategory(TestCategories.Database)] public void VerifyDataTableValuesMatch() { var states = DatabaseDriver.Query("SELECT * FROM States").ToList(); var statesTable = DatabaseUtils.ToDataTable(states); // Loop through rows and validate for (int i = 0; i < states.Count; i++) { DataRow dataTableRow = statesTable.Rows[i]; IDictionary<string, object> dynamicRow = states[i]; foreach (var key in dynamicRow.Keys) { var dynamicValue = dynamicRow[key]; var dataTablevalue = dataTableRow[key]; Assert.AreEqual(dynamicValue, dataTablevalue); } } } /// <summary> /// Check if datatypes are properly parsed /// </summary> [TestMethod] [TestCategory(TestCategories.Database)] public void VerifyDataTableDataTypesMatch() { var datatypes = DatabaseDriver.Query("SELECT * FROM DataType").ToList(); var datatypesTable = DatabaseUtils.ToDataTable(datatypes); Assert.AreEqual(datatypesTable.Rows[0].ItemArray[0].GetType(), typeof(long)); Assert.AreEqual(datatypesTable.Rows[0].ItemArray[1].GetType(), typeof(bool)); Assert.AreEqual(datatypesTable.Rows[0].ItemArray[2].GetType(), typeof(string)); Assert.AreEqual(datatypesTable.Rows[0].ItemArray[3].GetType(), typeof(DateTime)); Assert.AreEqual(datatypesTable.Rows[0].ItemArray[4].GetType(), typeof(DateTime)); Assert.AreEqual(datatypesTable.Rows[0].ItemArray[5].GetType(), typeof(double)); Assert.AreEqual(datatypesTable.Rows[0].ItemArray[6].GetType(), typeof(int)); Assert.AreEqual(datatypesTable.Rows[0].ItemArray[7].GetType(), typeof(string)); Assert.AreEqual(datatypesTable.Rows[0].ItemArray[8].GetType(), typeof(string)); Assert.AreEqual(datatypesTable.Rows[0].ItemArray[9].GetType(), typeof(string)); Assert.AreEqual(datatypesTable.Rows[0].ItemArray[10].GetType(), typeof(decimal)); Assert.AreEqual(datatypesTable.Rows[0].ItemArray[11].GetType(), typeof(DBNull)); } /// <summary> /// Check that ToDataTable properly parses Null and String values /// </summary> [TestMethod] [TestCategory(TestCategories.Database)] public void VerifyDataTableColumnsNullStringValue() { var states = DatabaseDriver.Query("select City.CityName from States left Join Cities as City on City.CityName like 'Minneaplois' and City.CityId = States.StateId").ToList(); var statesTable = DatabaseUtils.ToDataTable(states); var found = false; // Loop through rows and validate for (int i = 0; i < statesTable.Rows.Count; i++) { // Check Data Type if (statesTable.Rows[i].ItemArray[0] != null && !(statesTable.Rows[i].ItemArray[0] is DBNull)) { Type dataType = statesTable.Rows[i].ItemArray[0].GetType(); Assert.AreEqual(dataType, typeof(string)); found = true; } } Assert.IsTrue(found, "Did not find any non null values. Verify the query is correct."); } /// <summary> /// Check that ToDataTable properly parses Null and int values /// </summary> [TestMethod] [TestCategory(TestCategories.Database)] public void VerifyDataTableColumnsNullIntValue() { var states = DatabaseDriver.Query("select City.CityId from States left Join Cities as City on City.CityName like 'Minneaplois' and City.CityId = States.StateId").ToList(); var statesTable = DatabaseUtils.ToDataTable(states); var found = false; // Loop through rows and validate for (int i = 0; i < statesTable.Rows.Count; i++) { // Check Data Type if (statesTable.Rows[i].ItemArray[0] != null && !(statesTable.Rows[i].ItemArray[0] is DBNull)) { Type dataType = statesTable.Rows[i].ItemArray[0].GetType(); Assert.AreEqual(dataType, typeof(int)); found = true; } } Assert.IsTrue(found, "Did not find any non null values. Verify the query is correct."); } /// <summary> /// Check that ToDataTable properly parses Null and Decimal values /// </summary> [TestMethod] [TestCategory(TestCategories.Database)] public void VerifyDataTableColumnsNullDecimalValue() { var states = DatabaseDriver.Query("select City.CityPopulation from States left Join Cities as City on City.CityName like 'St. Paul' and City.CityId = States.StateId").ToList(); var statesTable = DatabaseUtils.ToDataTable(states); var found = false; // Loop through rows and validate for (int i = 0; i < statesTable.Rows.Count; i++) { // Check Data Type if (statesTable.Rows[i].ItemArray[0] != null && !(statesTable.Rows[i].ItemArray[0] is DBNull)) { Type dataType = statesTable.Rows[i].ItemArray[0].GetType(); Assert.AreEqual(dataType, typeof(decimal)); found = true; } } Assert.IsTrue(found, "Did not find any non null values. Verify the query is correct."); } } }
42.163462
188
0.585177
[ "MIT" ]
CoryJHolland/MAQS
Framework/DatabaseUnitTests/DatabaseUtilsUnitTests.cs
8,772
C#
 namespace OzgeErsu.Models { public class ContactModel { public string isimSoyisim { get; set; } public string email { get; set; } public string gsm { get; set; } public string ileti { get; set; } } }
17.533333
48
0.539924
[ "MIT" ]
onurcelikeng/OzgeErsu
OzgeErsu.Models/ContactModel.cs
265
C#
using Imagin.Common.Collections; using System.Windows; namespace Imagin.Common.Controls { public delegate void SelectionEventHandler(object sender, SelectionEventArgs e); public class SelectionEventArgs : RoutedEventArgs { public readonly ICollect Selection; public SelectionEventArgs(RoutedEvent input, ICollect selection) : base(input) => Selection = selection; } }
28.785714
112
0.754342
[ "BSD-2-Clause" ]
fritzmark/Imagin.NET
Imagin.Common.WPF/Controls/Other/SelectionEvent.cs
405
C#
using System; using Microsoft.Extensions.Configuration; namespace Essentials.AspNetCore.Docker.Configuration { /// <summary> /// Extension methods for registering <see cref="DockerSecretsConfigurationProvider"/> with <see cref="IConfigurationBuilder"/>. /// </summary> public static class SecretsConfigurationBuilderExtensions { /// <summary> /// Adds an <see cref="IConfigurationProvider"/> that reads configuration values from docker secrets. /// </summary> /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param> /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> public static IConfigurationBuilder AddDockerSecrets(this IConfigurationBuilder builder) => builder.AddDockerSecrets(configureSource: null); /// <summary> /// Adds an <see cref="IConfigurationProvider"/> that reads configuration values from docker secrets. /// </summary> /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param> /// <param name="secretsPath">The path to the secrets directory.</param> /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> public static IConfigurationBuilder AddDockerSecrets(this IConfigurationBuilder builder, string secretsPath) => builder.AddDockerSecrets(source => source.SecretsDirectory = secretsPath); /// <summary> /// Adds an <see cref="IConfigurationProvider"/> that reads configuration values from docker secrets. /// </summary> /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param> /// <param name="secretsPath">The path to the secrets directory.</param> /// <param name="optional">Whether the directory is optional.</param> /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> public static IConfigurationBuilder AddDockerSecrets(this IConfigurationBuilder builder, string secretsPath, bool optional) => builder.AddDockerSecrets(source => { source.SecretsDirectory = secretsPath; source.Optional = optional; }); /// <summary> /// Adds an <see cref="IConfigurationProvider"/> that reads configuration values from docker secrets. /// </summary> /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param> /// <param name="optional">Whether the directory is optional.</param> /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> public static IConfigurationBuilder AddDockerSecrets(this IConfigurationBuilder builder, bool optional) => builder.AddDockerSecrets(source => { source.Optional = optional; }); /// <summary> /// Adds an <see cref="IConfigurationProvider"/> that reads configuration values from docker secrets. /// </summary> /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param> /// <param name="configureSource">Configures the <see cref="DockerSecretsConfigurationProvider"/>.</param> /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> public static IConfigurationBuilder AddDockerSecrets(this IConfigurationBuilder builder, Action<SecretsConfigurationSource> configureSource) => builder.Add(configureSource); } }
56.836066
148
0.669743
[ "MIT" ]
esenciadev/AspNetCore.Configuration.Docker
src/Docker/Configuration/SecretsConfigurationBuilderExtensions.cs
3,467
C#
using MOTMaster; using MOTMaster.SnippetLibrary; using System; using System.Collections.Generic; using DAQ.Pattern; using DAQ.Analog; // This script is for running grey molasses after a MOT, with a ramp on the molasses intensity, which has the same time length as the molasses pulse //Useful timescales to remember: // The coils take about 300us to switch off // The AOMs take a few tens of us to switch on/off // The units are 100us. So I have made a function to convert from seconds to the 100us units. public class Patterns : MOTMasterScript { public int ConvertFromSeconds(double inputValue) //this converts to the horrible units from seconds { return Convert.ToInt32(10000 * inputValue); } public Patterns() { Parameters = new Dictionary<string, object>(); Parameters["PatternLength"] = 100000;//in units of 100microseconds. Parameters["MOTStartTime"] = 10000; Parameters["MOTLoadEndTime"] = 68000; Parameters["MOTEndTime"] = 70000; Parameters["TopMOTCoilCurrent"] = 0.0; Parameters["BottomMOTCoilCurrent"] = 0.0; Parameters["TopVacCoilCurrent"] = 2.8; Parameters["BottomVacCoilCurrent"] = 2.82; Parameters["NumberOfFrames"] = 3; Parameters["Frame0TriggerDuration"] = 100; Parameters["Frame0Trigger"] = 70000; Parameters["ImageDelay"] = 10; Parameters["Frame1TriggerDuration"] = 100; Parameters["Frame1Trigger"] = 81100; Parameters["Frame2TriggerDuration"] = 10; Parameters["Frame2Trigger"] = 81500; Parameters["ExposureTime"] = 10; Parameters["D2RepumpSwitchOffTime"] = 1; //MOT settings Parameters["aom0amplitude"] = 6.0; Parameters["aom0Detuning"] = 196.5; //lock Parameters["aom3amplitude"] = 6.0; Parameters["aom3Detuning"] = 177.8; // MOT cooling Parameters["MotRepumpFrequency"] = 814.5; //repump detuning Parameters["MotRepumpAmplitude"] = 3.8;// repump amplitude, as voltage applied to VCA Parameters["XCoilCurrent"] = 0.9; Parameters["YCoilCurrent"] = 6.55; Parameters["ZCoilCurrent"] = 1.37; //Molasses Settings Parameters["MolassesStartTime"] = 70004; Parameters["MolassesPrincipalFrequency"]=200.0; Parameters["MolassesStartAmplitude"] = 6.0; Parameters["MolassesFinalAmplitude"] = 5.0; Parameters["MolassesStartRepumpDetuning"] = 802.0; Parameters["MolassesFinalRepumpDetuning"] = 802.3; Parameters["MolassesPulseLength"] =10; Parameters["offsetlockvcofrequency"] = 9.10;//-300MHz/V Parameters["MolassesRepumpAmplitude"] = 1.9; Parameters["DoMolassesPulse"] = true; Parameters["FieldSwitchOffTime"] = 4; //Imaging settings Parameters["absImageDetuning"] = 188.0; Parameters["absImagePower"] = 1.35; Parameters["backgroundImagePower"] = 1.25; Parameters["absImageRepumpDetuning"] = 814.2; Parameters["absImageRepumpAmplitude"] = 4.2; Parameters["TSDistance"] = 10.0; Parameters["TSVelocity"] = 10.0; Parameters["TSAcceleration"] = 10.0; Parameters["TSDeceleration"] = 10.0; Parameters["TSDistanceF"] = 0.0; Parameters["TSDistanceB"] = 0.0; } public override PatternBuilder32 GetDigitalPattern() { PatternBuilder32 p = new PatternBuilder32(); //The pattern builder assumes that digital channels are off at time zero, unless you tell them so. //Turning anything Off as a first command will cause "edge conflict error", unless it was turned On at time zero. MOTMasterScriptSnippet lm = new SHLoadMOT(p, Parameters); // This just loads the MOT, and leaves it "on". You need //turn off the MOT and Zeeman light yourself p.Pulse(0, 0, 1, "AnalogPatternTrigger"); //NEVER CHANGE THIS!!!! IT TRIGGERS THE ANALOG PATTERN! p.AddEdge("CameraTrigger", 0, true); p.AddEdge("shutterenable", 0, true); //switches off Zeeman beams after loading p.AddEdge("shutterenable", (int)Parameters["MOTLoadEndTime"], false); //Pump atoms into f=1 ground state p.AddEdge("D2EOMenable", (int)Parameters["MOTEndTime"] - (int)Parameters["D2RepumpSwitchOffTime"], false); //turn OFF the MOT AOMs, cutting off all light to the chamber p.AddEdge("aom3enable", (int)Parameters["MOTEndTime"], false); //pulse on molasses light p.PulseSwitchable((int)Parameters["MolassesStartTime"], 0, (int)Parameters["MolassesPulseLength"], "aom2enable", (bool)Parameters["DoMolassesPulse"]); //Imaging p.Pulse((int)Parameters["MolassesStartTime"] + (int)Parameters["MolassesPulseLength"] + (int)Parameters["ImageDelay"], -2, 1, "aom3enable"); p.Pulse((int)Parameters["MolassesStartTime"] + (int)Parameters["MolassesPulseLength"]+(int)Parameters["ImageDelay"], -1, 100, "aom1enable"); p.Pulse((int)Parameters["MolassesStartTime"] + (int)Parameters["MolassesPulseLength"]+(int)Parameters["ImageDelay"], -2, 100, "D2EOMenable"); p.DownPulse((int)Parameters["MolassesStartTime"] + (int)Parameters["MolassesPulseLength"]+(int)Parameters["ImageDelay"], 0, 100, "CameraTrigger"); //take an image of the cloud after D1 stage p.Pulse((int)Parameters["Frame1Trigger"], -2, 1, "aom3enable"); p.Pulse((int)Parameters["Frame1Trigger"] , -1, 100, "aom1enable"); p.Pulse((int)Parameters["Frame1Trigger"], -1, 100, "D2EOMenable"); p.DownPulse((int)Parameters["Frame1Trigger"] , 0, 100, "CameraTrigger"); //take an image without the cloud. //p.AddEdge("aom1enable", 150000, false); p.DownPulse(95000, 0, 50, "CameraTrigger"); //background image - no light. return p; } public override AnalogPatternBuilder GetAnalogPattern() { AnalogPatternBuilder p = new AnalogPatternBuilder((int)Parameters["PatternLength"]); MOTMasterScriptSnippet lm = new SHLoadMOT(p, Parameters); //loading the MOT p.AddChannel("aom1frequency"); p.AddChannel("aom2frequency"); p.AddChannel("aom3frequency"); p.AddChannel("aom1amplitude"); p.AddChannel("aom2amplitude"); p.AddChannel("aom3amplitude"); p.AddChannel("D1EOMfrequency"); p.AddChannel("D1EOMamplitude"); p.AddChannel("D2EOMfrequency"); p.AddChannel("D2EOMamplitude"); p.AddChannel("offsetlockfrequency"); p.AddAnalogValue("D2EOMfrequency", 0, (double)Parameters["MotRepumpFrequency"]); p.AddAnalogValue("D2EOMamplitude", 0, (double)Parameters["MotRepumpAmplitude"]); p.AddAnalogValue("aom3frequency", 0, (double)Parameters["aom3Detuning"]); p.AddAnalogValue("aom3amplitude", 0, 6.0); //setting up the MOT parameters p.AddAnalogValue("D1EOMfrequency", 0, (double)Parameters["MolassesStartRepumpDetuning"]); p.AddAnalogValue("D1EOMamplitude", 0, (double)Parameters["MolassesRepumpAmplitude"]); p.AddAnalogValue("aom2frequency", 0, (double)Parameters["MolassesPrincipalFrequency"]); p.AddAnalogValue("aom2amplitude", 0, (double)Parameters["MolassesStartAmplitude"]); p.AddAnalogValue("offsetlockfrequency", 0, (double)Parameters["offsetlockvcofrequency"]);//setting up molasses parameters p.AddLinearRamp("aom3amplitude", (int)Parameters["MOTEndTime"] - 10, 10, 3); p.AddLinearRamp("aom3frequency", (int)Parameters["MOTEndTime"] - 10, 10, 180.0); p.AddAnalogValue("aom3amplitude", (int)Parameters["MOTEndTime"] + 1, 6.0); p.AddAnalogValue("aom3frequency", (int)Parameters["MOTEndTime"] + 1, (double)Parameters["aom3Detuning"]); p.AddAnalogValue("TopTrappingCoilcurrent", (int)Parameters["MOTEndTime"], 0); p.AddAnalogValue("BottomTrappingCoilcurrent", (int)Parameters["MOTEndTime"], 0); //molasses power ramp p.AddLinearRamp("aom2amplitude", (int)Parameters["MolassesStartTime"], (int)Parameters["MolassesPulseLength"], (double)Parameters["MolassesFinalAmplitude"]); p.AddLinearRamp("D1EOMfrequency", (int)Parameters["MolassesStartTime"], (int)Parameters["MolassesPulseLength"], (double)Parameters["MolassesFinalRepumpDetuning"]); //Taking the pictures p.AddAnalogValue("D2EOMfrequency", (int)Parameters["MolassesStartTime"] + (int)Parameters["MolassesPulseLength"] +(int)Parameters["ImageDelay"] - 3, (double)Parameters["absImageRepumpDetuning"]); p.AddAnalogValue("D2EOMamplitude", (int)Parameters["MolassesStartTime"] + (int)Parameters["MolassesPulseLength"]+(int)Parameters["ImageDelay"] - 3, (double)Parameters["absImageRepumpAmplitude"]); p.AddAnalogValue("aom1frequency", (int)Parameters["MolassesStartTime"] + (int)Parameters["MolassesPulseLength"] + (int)Parameters["ImageDelay"] - 1, (double)Parameters["absImageDetuning"]); p.AddAnalogValue("aom1amplitude", (int)Parameters["MolassesStartTime"] + (int)Parameters["MolassesPulseLength"] + (int)Parameters["ImageDelay"] - 1, (double)Parameters["absImagePower"]); p.AddAnalogValue("aom1amplitude", (int)Parameters["Frame1Trigger"] - 1, (double)Parameters["backgroundImagePower"]); p.SwitchAllOffAtEndOfPatternExcept(new string[] { "offsetlockfrequency", "XCoilCurrent", "YCoilCurrent", "ZCoilCurrent" }); return p; } }
51.864865
203
0.66691
[ "MIT" ]
sidwright8/SidEDMSuite
SympatheticMOTMasterScripts/MolassesFromMOTPulseRampDetuningAndPower.cs
9,597
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the ssm-2014-11-06.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.SimpleSystemsManagement.Model { /// <summary> /// This is the response object from the ResumeSession operation. /// </summary> public partial class ResumeSessionResponse : AmazonWebServiceResponse { private string _sessionId; private string _streamUrl; private string _tokenValue; /// <summary> /// Gets and sets the property SessionId. /// <para> /// The ID of the session. /// </para> /// </summary> [AWSProperty(Min=1, Max=96)] public string SessionId { get { return this._sessionId; } set { this._sessionId = value; } } // Check to see if SessionId property is set internal bool IsSetSessionId() { return this._sessionId != null; } /// <summary> /// Gets and sets the property StreamUrl. /// <para> /// A URL back to SSM Agent on the instance that the Session Manager client uses to send /// commands and receive output from the instance. Format: <code>wss://ssmmessages.<b>region</b>.amazonaws.com/v1/data-channel/<b>session-id</b>?stream=(input|output)</code>. /// </para> /// /// <para> /// <b>region</b> represents the Region identifier for an AWS Region supported by AWS /// Systems Manager, such as <code>us-east-2</code> for the US East (Ohio) Region. For /// a list of supported <b>region</b> values, see the <b>Region</b> column in <a href="http://docs.aws.amazon.com/general/latest/gr/ssm.html#ssm_region">Systems /// Manager Service Endpoints</a> in the <i>AWS General Reference</i>. /// </para> /// /// <para> /// <b>session-id</b> represents the ID of a Session Manager session, such as <code>1a2b3c4dEXAMPLE</code>. /// </para> /// </summary> public string StreamUrl { get { return this._streamUrl; } set { this._streamUrl = value; } } // Check to see if StreamUrl property is set internal bool IsSetStreamUrl() { return this._streamUrl != null; } /// <summary> /// Gets and sets the property TokenValue. /// <para> /// An encrypted token value containing session and caller information. Used to authenticate /// the connection to the instance. /// </para> /// </summary> [AWSProperty(Min=0, Max=300)] public string TokenValue { get { return this._tokenValue; } set { this._tokenValue = value; } } // Check to see if TokenValue property is set internal bool IsSetTokenValue() { return this._tokenValue != null; } } }
34.165138
182
0.603115
[ "Apache-2.0" ]
UpendoVentures/aws-sdk-net
sdk/src/Services/SimpleSystemsManagement/Generated/Model/ResumeSessionResponse.cs
3,724
C#
//------------------------------------------------------------------- /*! @file QueueLogMessageHandler.cs * @brief This file provides an implementation of the QueueLogMessageHandler LMH requeuing class. * * Copyright (c) Mosaic Systems Inc. * Copyright (c) 2008 Mosaic Systems Inc. * Copyright (c) 2007 Mosaic Systems Inc. (C++ library version) * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; namespace MosaicLib { public static partial class Logging { public static partial class Handlers { /// <summary> /// This class implements a special type of LogMessageHandler. It is given another LMH instance and acts as a passthrough where messages that are given to this /// LMH are queued and then an internal thread periodically passes larger groups of the queue messages into the given target LMH thus loosely decoupling the main message /// distribution system from the per message performance of the target LMH. This also improves the performance with some types of target LMH where there is a relatively /// large cost to start writing a message but a relatively small cost two write two in a row after setting up to the write the first (file types for example). /// </summary> public class QueueLogMessageHandler : CommonLogMessageHandlerBase { /// <summary> /// Single targetLMH constructor. Derives name and LoggingConfig values from the given targetLMH. /// </summary> /// <param name="targetLMH">Gives the target LMH instance to which the queued messages will be delivered.</param> /// <param name="maxQueueSize">Defines te maximum number of messages that can be held internally before messages are lost.</param> public QueueLogMessageHandler(ILogMessageHandler targetLMH, int maxQueueSize = DefaultMesgQueueSize) : this(targetLMH.Name + ".q", new[] { targetLMH }, maxQueueSize) { } /// <summary> /// Multiple targetLMH constructor. Derives LoggingConfig values from the given targetLMH /// </summary> /// <param name="name">Gives the name of this LMH - different than the names of the target LMH instances</param> /// <param name="targetLMHArray">Gives the set of LMH instance that are to be given the dequeued LogMessages.</param> /// <param name="maxQueueSize">Defines te maximum number of messages that can be held internally before messages are lost.</param> /// <param name="allowRecordSourceStackFrame">The use of this parameter is now obsolete and will be ignored</param> public QueueLogMessageHandler(string name, ILogMessageHandler[] targetLMHArray, int maxQueueSize = DefaultMesgQueueSize, bool allowRecordSourceStackFrame = false) : base(name, LogGate.None, recordSourceStackFrame: false) { targetLMHArray = targetLMHArray ?? emptyLMHArray; LogGate logGate = LogGate.None; foreach (ILogMessageHandler targetLMH in targetLMHArray) logGate.MesgTypeMask |= targetLMH.LoggerConfig.LogGate.MesgTypeMask; loggerConfig.LogGate = logGate; this.targetLMHArray = targetLMHArray; mesgDeliveryList = new List<LogMessage>(10); // define its initial capacity mesgQueue = new MessageQueue(maxQueueSize); mesgQueue.SetEffectiveSourceInfo(logger.LoggerSourceInfo); mesgQueue.EnableQueue(); mesgQueueMutex = mesgQueue.Mutex; // create and start the thread StartIfNeeded(); } const int minQueueSizeToWakeupDeliveryThread = 100; // NOTE: neither the HandleLogMessage nor HandleLogMessages attempts to apply // the logGate to determine which messages should be passed. If they make it // here, then they will be passed to the encapsulated lmh(s) which will perform // its own message type gating. /// <summary>LogMessage Handling method API for direct call by clients which generate and distribute one message at a time.</summary> /// <param name="lm"> /// Gives the message to handle (save, write, relay, ...). /// LMH Implementation must either support Reference Counted message semenatics if method will save any reference to a this message for use beyond the scope of this call or /// LMH must flag that it does not support Reference counted semantics in LoggerConfig by clearing the SupportReferenceCountedRelease /// </param> public override void HandleLogMessage(LogMessage lm) { bool notifyThread = false; lock (mesgQueueMutex) { if (mesgQueue.EnqueueMesg(lm) >= minQueueSizeToWakeupDeliveryThread) notifyThread = true; mesgQueueSeqNumRange.lastSeqNumIn = mesgQueue.LastEnqueuedSeqNum; } if (notifyThread) threadWakeupEvent.Notify(); } /// <summary>LogMessage Handling method API for use on outputs of queued delivery engines which agregate and distribute one or more messages at a time.</summary> /// <param name="lmArray"> /// Gives an array of message to handle as a set (save, write, relay, ...). This set may be given to muliple handlers and as such may contain messages that are not relevant to this handler. /// As such Handler may additionally filter out or skip any messages from the given set as approprate. /// LMH Implementation must flag that it does not support Reference counted semantics in LoggerConfig or must support ReferenceCounting on this message if references to it are saved beyond the scope of this call. /// </param> public override void HandleLogMessages(LogMessage[] lmArray) { bool notifyThread = false; lock (mesgQueueMutex) { if (mesgQueue.EnqueueMesgs(lmArray) >= minQueueSizeToWakeupDeliveryThread) notifyThread = true; mesgQueueSeqNumRange.lastSeqNumIn = mesgQueue.LastEnqueuedSeqNum; } if (notifyThread) threadWakeupEvent.Notify(); } /// <summary>Query method that may be used to tell if message delivery for a given message is still in progress on this handler.</summary> public override bool IsMessageDeliveryInProgress(int testMesgSeqNum) { QueuedMesgSeqNumRange mesgQueueSeqNumRangeSnapshot = mesgQueueSeqNumRange; return mesgQueueSeqNumRangeSnapshot.IsMesgSeqNumInRange(testMesgSeqNum); } /// <summary>Once called, this method only returns after the handler has made a reasonable effort to verify that all outsanding, pending messages, visible at the time of the call, have been full processed before the call returns.</summary> public override void Flush() { int lastPutSeqNumSnapshot = mesgQueueSeqNumRange.lastSeqNumIn; if (NullMessageSeqNum != lastPutSeqNumSnapshot) System.Threading.Interlocked.CompareExchange(ref flushAfterSeqNum, lastPutSeqNumSnapshot, 0); else flushRequested = true; threadWakeupEvent.Notify(); // need to wait for queue to drain if (lastPutSeqNumSnapshot == NullMessageSeqNum) return; while (IsMessageDeliveryInProgress(lastPutSeqNumSnapshot)) { System.Threading.Thread.Sleep(10); } } /// <summary> /// Used to tell the handler that the LogMessageDistribution system is shuting down. /// Handler is expected to close, release and/or Dispose of any unmanged resources before returning from this call. /// Any attempt to pass messages after this point may be ignored by the handler. /// </summary> public override void Shutdown() { // stop new messages from being inserted into the queue and ask // background thread to drain queue and stop mesgQueue.DisableQueue(); // wait for the thread to exit if (mainThread != null) { mainThread.Join(); mainThread = null; } // NOTE: targetLMH is shutdown by the mainThread prior to its completion. } /// <summary> /// Re-enabled the queue and restart the mesg queue thread. /// </summary> public override void StartIfNeeded() { mesgQueue.EnableQueue(); if (mainThread == null) { mainThread = new System.Threading.Thread(MainThreadFcn) { Name = this.Name, IsBackground = true, // allow the application to shutdown even if the client code forgets to }; mainThread.Start(); } } /// <summary> /// Implementes locally adjusted version of the base classes DisposableBase.Dispose(disposeType) method. /// Calls base.Dispose(disposeType). If disposeType is CalledExplictly then it disposes of each of the contained targetLMH instances. /// </summary> /// <param name="disposeType">Indicates if this dispose call is made explicitly or by the finalizer.</param> protected override void Dispose(MosaicLib.Utils.DisposableBase.DisposeType disposeType) { base.Dispose(disposeType); if (disposeType == DisposeType.CalledExplicitly) { for (int idx = 0; idx < targetLMHArray.Length; idx++) Utils.Fcns.DisposeOfObject(ref targetLMHArray[idx]); } targetLMHArray = null; } const int maxMessagesToDequePerIteration = 500; const double minDeliveryThreadSpinWaitPeriod = 0.050; // 20 Hz /// <summary> /// This gives the method that is called by the internal service thread to pull messages from the back of the message queue and deliver them to the /// target LMH instances. /// </summary> protected void MainThreadFcn() { if (targetLMHArray == null || !mesgQueue.IsEnabled || threadWakeupEvent == null) { mesgQueue.DisableQueue(); foreach (var lmh in targetLMHArray ?? emptyLMHArray) lmh.Shutdown(); Utils.Asserts.TakeBreakpointAfterFault("QLMH thread Startup test failed"); return; } foreach (var lmh in targetLMHArray) lmh.StartIfNeeded(); while (mesgQueue.IsEnabled) { threadWakeupEvent.Reset(); bool didAnything = false; // process messages from a non-empty queue (or full) if (mesgQueue.QueueCount != 0 || mesgQueue.IsQueueFull()) { didAnything = true; ServiceQueueDelivery(maxMessagesToDequePerIteration); } // detect seqNum based flush request and ask underlying lmh to flush after // given seqNum is no longer in the mesgQueue int flushReqSeqNumSnapshot = flushAfterSeqNum; QueuedMesgSeqNumRange mesgQueueSeqNumRangeSnapshot = mesgQueueSeqNumRange; if (NullMessageSeqNum != flushReqSeqNumSnapshot && !mesgQueueSeqNumRangeSnapshot.IsMesgSeqNumInRange(flushReqSeqNumSnapshot)) { flushRequested = true; flushAfterSeqNum = NullMessageSeqNum; } if (flushRequested) // when queue is empty then process flush request { didAnything = true; flushRequested = false; foreach (var lmh in targetLMHArray) lmh.Flush(); } if (!didAnything) threadWakeupEvent.WaitSec(minDeliveryThreadSpinWaitPeriod); } // service the queue until it is empty while (mesgQueue.QueueCount != 0 || mesgQueue.IsQueueFull()) ServiceQueueDelivery(maxMessagesToDequePerIteration); uint totalDroppedMesgs = mesgQueue.TotalDroppedMesgCount; if (totalDroppedMesgs != 0) LogShutdownDroppedMessagesMesg(totalDroppedMesgs); foreach (var lmh in targetLMHArray) lmh.Shutdown(); } /// <summary> /// Intennal method that pulls messages from the queue and delivers them to the set of target handlers. /// </summary> /// <param name="maxMessagesToDeque">Gives the maxmum number of messages to pull from the queue at a time.</param> protected void ServiceQueueDelivery(int maxMessagesToDeque) { // get the next block of messages from the queue mesgQueue.DequeueMesgSet(maxMessagesToDeque, ref mesgDeliveryList); // return if we did not get any messages if (mesgDeliveryList.Count == 0) return; // delivere the messages LogMessage[] lmArray = mesgDeliveryList.ToArray(); foreach (var lmh in targetLMHArray) lmh.HandleLogMessages(lmArray); int lastDeliveredSeqNum = mesgQueueSeqNumRange.lastSeqNumOut; for (int idx = 0; idx < mesgDeliveryList.Count; idx++) { LogMessage lm = mesgDeliveryList[idx]; mesgDeliveryList[idx] = null; if (lm == null) continue; lastDeliveredSeqNum = lm.SeqNum; lm = null; } mesgDeliveryList.Clear(); mesgQueueSeqNumRange.lastSeqNumOut = lastDeliveredSeqNum; // tell any interested Notifyable objects that the queue has advanced NoteMessagesHaveBeenDelivered(); } /// <summary> /// Makes a final effort to record the number of dropped messages. /// </summary> /// <param name="totalLostMesgCount">Gives the number of messages that the queue dropped.</param> protected void LogShutdownDroppedMessagesMesg(uint totalLostMesgCount) { logger.Error.Emit("Total mesgs dropped:{0}", totalLostMesgCount); ServiceQueueDelivery(10); // attempt to allow some more mesgs to be logged (so the above message makes it out as well) } #region private variables static readonly ILogMessageHandler[] emptyLMHArray = Utils.Collections.EmptyArrayFactory<ILogMessageHandler>.Instance; ILogMessageHandler[] targetLMHArray = null; System.Threading.Thread mainThread = null; Utils.WaitEventNotifier threadWakeupEvent = new MosaicLib.Utils.WaitEventNotifier(MosaicLib.Utils.WaitEventNotifier.Behavior.WakeAllSticky); int flushAfterSeqNum = 0; volatile bool flushRequested = false; MessageQueue mesgQueue = null; object mesgQueueMutex = null; QueuedMesgSeqNumRange mesgQueueSeqNumRange = new QueuedMesgSeqNumRange(); List<LogMessage> mesgDeliveryList = null; // temporary place to put messages that are taken from the queue but that have not been delivered yet #endregion } } } } //-------------------------------------------------------------------
50.307278
256
0.54731
[ "ECL-2.0", "Apache-2.0" ]
mosaicsys/MosaicLibCS
Base/Logging/QueueLogMessageHandler.cs
18,664
C#
//RealtimeReflections for Daggerfall-Unity //http://www.reddit.com/r/dftfu //http://www.dfworkshop.net/ //Author: Michael Rauter (a.k.a. Nystul) //License: MIT License (http://www.opensource.org/licenses/mit-license.php) using UnityEngine; using UnityEngine.Rendering; using System; using System.Collections.Generic; using System.IO; using DaggerfallConnect; using DaggerfallConnect.Arena2; using DaggerfallConnect.Utility; using DaggerfallWorkshop; using DaggerfallWorkshop.Game; using DaggerfallWorkshop.Utility; using DaggerfallWorkshop.Game.Serialization; using IniParser; namespace RealtimeReflections { public class InjectReflectiveMaterialProperty : MonoBehaviour { private bool useDeferredReflections = true; // Streaming World Component public StreamingWorld streamingWorld; private UpdateReflectionTextures componentUpdateReflectionTextures = null; private Texture texReflectionGround = null; private Texture texReflectionLowerLevel = null; private bool playerInside = false; private struct InsideSpecification { public const int Building = 0, DungeonOrCastle = 1, Unknown = 2; }; private int whereInside = InsideSpecification.Unknown; private GameObject gameObjectInterior = null; private GameObject gameObjectDungeon = null; private GameObject gameObjectReflectionPlaneGroundLevel = null; private GameObject gameObjectReflectionPlaneSeaLevel = null; private GameObject gameObjectReflectionPlaneLowerLevel = null; private float extraTranslationY = 0.0f; private GameObject gameObjectStreamingTarget = null; private DaggerfallUnity dfUnity; static string GetGameObjectPath(GameObject obj) { string path = "/" + obj.name; while (obj.transform.parent != null) { obj = obj.transform.parent.gameObject; path = "/" + obj.name + path; } return path; } void Awake() { if (!componentUpdateReflectionTextures) componentUpdateReflectionTextures = GameObject.Find("RealtimeReflections").GetComponent<UpdateReflectionTextures>(); if (!componentUpdateReflectionTextures) { DaggerfallUnity.LogMessage("InjectReflectiveMaterialProperty: Could not locate UpdateReflectionTextures component.", true); if (Application.isEditor) Debug.Break(); else Application.Quit(); } StreamingWorld.OnInitWorld += InjectMaterialProperties; StreamingWorld.OnTeleportToCoordinates += InjectMaterialProperties; FloatingOrigin.OnPositionUpdate += InjectMaterialProperties; DaggerfallTerrain.OnInstantiateTerrain += InjectMaterialProperties; SaveLoadManager.OnLoad += OnLoadEvent; } void OnDestroy() { StreamingWorld.OnInitWorld -= InjectMaterialProperties; StreamingWorld.OnTeleportToCoordinates -= InjectMaterialProperties; FloatingOrigin.OnPositionUpdate -= InjectMaterialProperties; DaggerfallTerrain.OnInstantiateTerrain -= InjectMaterialProperties; SaveLoadManager.OnLoad -= OnLoadEvent; } void Start() { dfUnity = DaggerfallUnity.Instance; useDeferredReflections = (GameManager.Instance.MainCamera.renderingPath == RenderingPath.DeferredShading); if (!streamingWorld) streamingWorld = GameObject.Find("StreamingWorld").GetComponent<StreamingWorld>(); if (!streamingWorld) { DaggerfallUnity.LogMessage("InjectReflectiveMaterialProperty: Missing StreamingWorld reference.", true); if (Application.isEditor) Debug.Break(); else Application.Quit(); } if (GameObject.Find("DistantTerrain") != null) { Component[] components = GameObject.Find("DistantTerrain").GetComponents(typeof(Component)); foreach (Component component in components) { Type type = component.GetType(); if (type.Name == "DistantTerrain") { //System.Reflection.PropertyInfo pinfo = type.GetProperty("ExtraTranslationY"); System.Reflection.PropertyInfo extraTranslationYPropertyInfo = type.GetProperty("ExtraTranslationY"); extraTranslationY = (float)extraTranslationYPropertyInfo.GetValue(component, null); } } } //gameObjectReflectionPlaneGroundLevel = componentUpdateReflectionTextures.GameobjectReflectionPlaneGround; //gameObjectReflectionPlaneLowerLevel = componentUpdateReflectionTextures.GameobjectReflectionPlaneLowerLevel; //gameObjectReflectionPlaneSeaLevel = gameObjectReflectionPlaneLowerLevel; // get inactive gameobject StreamingTarget (just GameObject.Find() would fail to find inactive gameobjects) GameObject[] gameObjects = Resources.FindObjectsOfTypeAll<GameObject>(); foreach (GameObject currentGameObject in gameObjects) { string objectPathInHierarchy = GetGameObjectPath(currentGameObject); if (objectPathInHierarchy == "/Exterior/StreamingTarget") { gameObjectStreamingTarget = currentGameObject; } } } void Update() { gameObjectReflectionPlaneGroundLevel = componentUpdateReflectionTextures.GameobjectReflectionPlaneGround; gameObjectReflectionPlaneLowerLevel = componentUpdateReflectionTextures.GameobjectReflectionPlaneLowerLevel; gameObjectReflectionPlaneSeaLevel = gameObjectReflectionPlaneLowerLevel; if (!CheckAvailabilityAndUpdateReflectionTextures()) return; // mechanism implemented according to Interkarma's suggestions // transition: outside -> dungeon/castle/building if (GameManager.Instance.PlayerEnterExit.IsPlayerInside && !playerInside) { playerInside = true; // player now inside // do other stuff when player first inside if (GameManager.Instance.IsPlayerInsideBuilding) { gameObjectInterior = GameObject.Find("Interior"); whereInside = InsideSpecification.Building; } else if ((GameManager.Instance.IsPlayerInsideDungeon) || (GameManager.Instance.IsPlayerInsideCastle)) { gameObjectDungeon = GameObject.Find("Dungeon"); whereInside = InsideSpecification.DungeonOrCastle; } InjectMaterialPropertiesIndoor(); } // transition: dungeon/castle/building -> outside else if (!GameManager.Instance.PlayerEnterExit.IsPlayerInside && playerInside) { playerInside = false; // player no longer inside // do other stuff when player first not inside gameObjectInterior = null; gameObjectDungeon = null; InjectMaterialPropertiesOutdoor(); whereInside = InsideSpecification.Unknown; } // transition: dungeon/castle -> building if ((GameManager.Instance.IsPlayerInsideBuilding) && (whereInside == InsideSpecification.DungeonOrCastle)) { gameObjectInterior = GameObject.Find("Interior"); gameObjectDungeon = null; InjectMaterialPropertiesIndoor(); //injectIndoor = true; whereInside = InsideSpecification.Building; } // transition: building -> dungeon/castle else if (((GameManager.Instance.IsPlayerInsideDungeon) || (GameManager.Instance.IsPlayerInsideCastle)) && (whereInside == InsideSpecification.Building)) { gameObjectDungeon = GameObject.Find("Dungeon"); gameObjectInterior = null; InjectMaterialPropertiesIndoor(); whereInside = InsideSpecification.DungeonOrCastle; } } public void OnWillRenderObject() { if (!GameManager.Instance.IsPlayerInside) { if (!gameObjectStreamingTarget) return; foreach (Transform child in gameObjectStreamingTarget.transform) { DaggerfallTerrain dfTerrain = child.GetComponent<DaggerfallTerrain>(); if (!dfTerrain) continue; Terrain terrain = child.GetComponent<Terrain>(); if (terrain) { if (terrain.materialTemplate) { if ((terrain.materialTemplate.shader.name == "Daggerfall/RealtimeReflections/TilemapWithReflections") || (terrain.materialTemplate.shader.name == "Daggerfall/RealtimeReflections/TilemapTextureArrayWithReflections")) { terrain.materialTemplate.SetFloat("_GroundLevelHeight", gameObjectReflectionPlaneGroundLevel.transform.position.y - extraTranslationY); terrain.materialTemplate.SetFloat("_SeaLevelHeight", gameObjectReflectionPlaneSeaLevel.transform.position.y - extraTranslationY); } } } } } //else if (GameManager.Instance.IsPlayerInside) //{ // Renderer[] renderers = null; // // renderers must be aquired here and not in Update() because it seems that this function's execution can happen in parallel to Update() - so a concurrent conflict can occur (and does) // if (gameObjectInterior != null) // { // renderers = gameObjectInterior.GetComponentsInChildren<Renderer>(); // } // else if (gameObjectDungeon != null) // { // renderers = gameObjectDungeon.GetComponentsInChildren<Renderer>(); // } // //Debug.Log(String.Format("renderers: {0}", renderers.Length)); // if (renderers != null) // { // foreach (Renderer r in renderers) // { // Material[] mats = r.sharedMaterials; // foreach (Material m in mats) // { // //if (m.shader.name == "Daggerfall/RealtimeReflections/FloorMaterialWithReflections") // { // m.SetFloat("_GroundLevelHeight", gameObjectReflectionPlaneGroundLevel.transform.position.y); // m.SetFloat("_LowerLevelHeight", gameObjectReflectionPlaneLowerLevel.transform.position.y); // } // } // r.sharedMaterials = mats; // } // } //} } bool CheckAvailabilityAndUpdateReflectionTextures() { bool allNeededReflectionTexturesWereAlreadyPresent = true; if (( (componentUpdateReflectionTextures.IsEnabledOutdoorGroundReflections && componentUpdateReflectionTextures.CurrentPlayerEnvironment == UpdateReflectionTextures.PlayerEnvironment.Outdoors) || (componentUpdateReflectionTextures.IsEnabledDungeonGroundReflections && componentUpdateReflectionTextures.CurrentPlayerEnvironment == UpdateReflectionTextures.PlayerEnvironment.DungeonOrCastle) || (componentUpdateReflectionTextures.IsEnabledIndoorBuildingFloorReflections && componentUpdateReflectionTextures.CurrentPlayerEnvironment == UpdateReflectionTextures.PlayerEnvironment.Building) ) && texReflectionGround == null) { if (gameObjectReflectionPlaneGroundLevel != null) texReflectionGround = gameObjectReflectionPlaneGroundLevel.GetComponent<MirrorReflection>().m_ReflectionTexture; allNeededReflectionTexturesWereAlreadyPresent = false; } if (( (componentUpdateReflectionTextures.IsEnabledOutdoorSeaReflections && componentUpdateReflectionTextures.CurrentPlayerEnvironment == UpdateReflectionTextures.PlayerEnvironment.Outdoors) || (componentUpdateReflectionTextures.IsEnabledDungeonWaterReflections && componentUpdateReflectionTextures.CurrentPlayerEnvironment == UpdateReflectionTextures.PlayerEnvironment.DungeonOrCastle) || (componentUpdateReflectionTextures.IsEnabledIndoorBuildingLowerLevelReflection && componentUpdateReflectionTextures.CurrentPlayerEnvironment == UpdateReflectionTextures.PlayerEnvironment.Building) ) && texReflectionLowerLevel == null) { if (gameObjectReflectionPlaneLowerLevel != null) texReflectionLowerLevel = gameObjectReflectionPlaneLowerLevel.GetComponent<MirrorReflection>().m_ReflectionTexture; allNeededReflectionTexturesWereAlreadyPresent = false; } return allNeededReflectionTexturesWereAlreadyPresent; } void InjectMaterialPropertiesIndoor() { // mages guild 4 floors debuging worldpos: 704,337 if ((!GameManager.Instance.IsPlayerInsideCastle && !GameManager.Instance.IsPlayerInsideDungeon) || !componentUpdateReflectionTextures.IsEnabledDungeonWaterReflections) return; Renderer[] renderers = null; if (gameObjectDungeon != null) { renderers = gameObjectDungeon.GetComponentsInChildren<Renderer>(); } if (renderers != null) { foreach (Renderer r in renderers) { Material[] mats = r.sharedMaterials; for (int m = 0; m < mats.Length; m++) { if (mats[m].shader.name == "FX/DungeonWater (Basic)") { Material matWaterReflective = new Material(componentUpdateReflectionTextures.ShaderDungeonWaterWithReflections); matWaterReflective.CopyPropertiesFromMaterial(mats[m]); matWaterReflective.SetTexture("_ReflectionTex", texReflectionLowerLevel); mats[m] = matWaterReflective; } } r.sharedMaterials = mats; } } } void InjectMaterialPropertiesOutdoor() { if (GameManager.Instance.IsPlayerInside || (!componentUpdateReflectionTextures.IsEnabledOutdoorGroundReflections && !componentUpdateReflectionTextures.IsEnabledOutdoorSeaReflections)) return; GameObject go = GameObject.Find("StreamingTarget"); if (!go) { return; } foreach (Transform child in go.transform) { DaggerfallTerrain dfTerrain = child.GetComponent<DaggerfallTerrain>(); if (!dfTerrain) continue; PlayerGPS playerGPS = GameObject.Find("PlayerAdvanced").GetComponent<PlayerGPS>(); if (!playerGPS) continue; //if ((dfTerrain.MapPixelX != playerGPS.CurrentMapPixel.X) || (dfTerrain.MapPixelY != playerGPS.CurrentMapPixel.Y)) // continue; Terrain terrain = child.GetComponent<Terrain>(); if (terrain) { if ((terrain.materialTemplate)) //&&(terrain.materialTemplate.shader.name != "Daggerfall/TilemapWithReflections")) // uncommenting this makes initial location (after startup, not fast travelling) not receive correct shader - don't know why - so workaround is to force injecting materialshader even for unset material (not sure why it works, but it does) { if ((SystemInfo.supports2DArrayTextures) && DaggerfallUnity.Settings.EnableTextureArrays) { if (terrain.materialTemplate.HasProperty("_TileTexArr") && terrain.materialTemplate.HasProperty("_TileNormalMapTexArr") && terrain.materialTemplate.HasProperty("_TileMetallicGlossMapTexArr") && terrain.materialTemplate.HasProperty("_TilemapTex") && terrain.materialTemplate.HasProperty("_TilemapDim")) { Texture tileTextureArray = terrain.materialTemplate.GetTexture("_TileTexArr"); Texture tileNormalMapTextureArray = terrain.materialTemplate.GetTexture("_TileNormalMapTexArr"); Texture tileMetallicGlossMapTextureArray = terrain.materialTemplate.GetTexture("_TileMetallicGlossMapTexArr"); Texture tileMapTexture = terrain.materialTemplate.GetTexture("_TilemapTex"); int tileMapDim = terrain.materialTemplate.GetInt("_TilemapDim"); Material newMat = new Material(componentUpdateReflectionTextures.ShaderTilemapTextureArrayWithReflections); newMat.SetTexture("_TileTexArr", tileTextureArray); newMat.SetTexture("_TileNormalMapTexArr", tileNormalMapTextureArray); if (terrain.materialTemplate.IsKeywordEnabled("_NORMALMAP")) newMat.EnableKeyword("_NORMALMAP"); else newMat.DisableKeyword("_NORMALMAP"); newMat.SetTexture("_TileMetallicGlossMapTexArr", tileMetallicGlossMapTextureArray); newMat.SetTexture("_TilemapTex", tileMapTexture); newMat.SetInt("_TilemapDim", tileMapDim); newMat.SetTexture("_ReflectionGroundTex", texReflectionGround); newMat.SetFloat("_GroundLevelHeight", gameObjectReflectionPlaneLowerLevel.transform.position.y); newMat.SetTexture("_ReflectionSeaTex", texReflectionLowerLevel); newMat.SetFloat("_SeaLevelHeight", gameObjectReflectionPlaneSeaLevel.transform.position.y); terrain.materialTemplate = newMat; } } else { if (terrain.materialTemplate.HasProperty("_TileAtlasTex") && terrain.materialTemplate.HasProperty("_TilemapTex") && terrain.materialTemplate.HasProperty("_TilemapDim")) { Texture tileSetTexture = terrain.materialTemplate.GetTexture("_TileAtlasTex"); //Texture2D tileAtlas = dfUnity.MaterialReader.TextureReader.GetTerrainTilesetTexture(402).albedoMap; //System.IO.File.WriteAllBytes("./Assets/Daggerfall/RealtimeReflections/Resources/tileatlas_402.png", tileAtlas.EncodeToPNG()); Texture tileMapTexture = terrain.materialTemplate.GetTexture("_TilemapTex"); int tileMapDim = terrain.materialTemplate.GetInt("_TilemapDim"); Material newMat = new Material(componentUpdateReflectionTextures.ShaderTilemapWithReflections); newMat.SetTexture("_TileAtlasTex", tileSetTexture); newMat.SetTexture("_TilemapTex", tileMapTexture); newMat.SetInt("_TilemapDim", tileMapDim); newMat.SetTexture("_ReflectionGroundTex", texReflectionGround); newMat.SetFloat("_GroundLevelHeight", gameObjectReflectionPlaneLowerLevel.transform.position.y); newMat.SetTexture("_ReflectionSeaTex", texReflectionLowerLevel); newMat.SetFloat("_SeaLevelHeight", gameObjectReflectionPlaneSeaLevel.transform.position.y); WeatherManager weatherManager = GameObject.Find("WeatherManager").GetComponent<WeatherManager>(); if (!weatherManager.IsRaining) { //Texture2D tileAtlasReflectiveTexture = Resources.Load("tileatlas_reflective") as Texture2D; Texture2D tileAtlasReflectiveTexture = componentUpdateReflectionTextures.TextureTileatlasReflective; newMat.SetTexture("_TileAtlasReflectiveTex", tileAtlasReflectiveTexture); } else { //Texture2D tileAtlasReflectiveTexture = Resources.Load("tileatlas_reflective_raining") as Texture2D; Texture2D tileAtlasReflectiveTexture = componentUpdateReflectionTextures.TextureTileatlasReflectiveRaining; newMat.SetTexture("_TileAtlasReflectiveTex", tileAtlasReflectiveTexture); } terrain.materialTemplate = newMat; } } } } } } //overloaded variant void InjectMaterialProperties(DaggerfallTerrain sender) { InjectMaterialProperties(-1, -1); } //overloaded variant void InjectMaterialProperties(DFPosition worldPos) { InjectMaterialProperties(worldPos.X, worldPos.Y); } //overloaded variant void InjectMaterialProperties(Vector3 offset) { InjectMaterialProperties(); } //overloaded variant void InjectMaterialProperties() { InjectMaterialProperties(-1, -1); } void InjectMaterialProperties(int worldPosX, int worldPosY) { if (!GameManager.Instance.IsPlayerInside) { InjectMaterialPropertiesOutdoor(); } else { InjectMaterialPropertiesIndoor(); } } void OnLoadEvent(SaveData_v1 saveData) { InjectMaterialProperties(); } } }
48.362705
373
0.584975
[ "MIT" ]
GalacticChimp/dfunity-mods
RealtimeReflections/Scripts/InjectReflectiveMaterialProperty.cs
23,603
C#
using System; using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Input; namespace WPFDevelopers.Controls { /// <summary> /// TextBox 控件最好替换成可以设置最值且只能输入数字的输入框 /// </summary> [TemplatePart(Name = CountPerPageTextBoxTemplateName, Type = typeof(TextBox))] [TemplatePart(Name = JustPageTextBoxTemplateName, Type = typeof(TextBox))] [TemplatePart(Name = ListBoxTemplateName, Type = typeof(ListBox))] public class Pagination : Control { private static readonly Type _typeofSelf = typeof(Pagination); private const string CountPerPageTextBoxTemplateName = "PART_CountPerPageTextBox"; private const string JustPageTextBoxTemplateName = "PART_JumpPageTextBox"; private const string ListBoxTemplateName = "PART_ListBox"; private const string Ellipsis = "···"; private TextBox _countPerPageTextBox; private TextBox _jumpPageTextBox; private ListBox _listBox; private static RoutedCommand _prevCommand = null; private static RoutedCommand _nextCommand = null; static Pagination() { InitializeCommands(); DefaultStyleKeyProperty.OverrideMetadata(_typeofSelf, new FrameworkPropertyMetadata(_typeofSelf)); } #region Command private static void InitializeCommands() { _prevCommand = new RoutedCommand("Prev", _typeofSelf); _nextCommand = new RoutedCommand("Next", _typeofSelf); CommandManager.RegisterClassCommandBinding(_typeofSelf, new CommandBinding(_prevCommand, OnPrevCommand, OnCanPrevCommand)); CommandManager.RegisterClassCommandBinding(_typeofSelf, new CommandBinding(_nextCommand, OnNextCommand, OnCanNextCommand)); } public static RoutedCommand PrevCommand { get { return _prevCommand; } } public static RoutedCommand NextCommand { get { return _nextCommand; } } private static void OnPrevCommand(object sender, RoutedEventArgs e) { var ctrl = sender as Pagination; ctrl.Current--; } private static void OnCanPrevCommand(object sender, CanExecuteRoutedEventArgs e) { var ctrl = sender as Pagination; e.CanExecute = ctrl.Current > 1; } private static void OnNextCommand(object sender, RoutedEventArgs e) { var ctrl = sender as Pagination; ctrl.Current++; } private static void OnCanNextCommand(object sender, CanExecuteRoutedEventArgs e) { var ctrl = sender as Pagination; e.CanExecute = ctrl.Current < ctrl.PageCount; } #endregion #region Properties private static readonly DependencyPropertyKey PagesPropertyKey = DependencyProperty.RegisterReadOnly("Pages", typeof(IEnumerable<string>), _typeofSelf, new PropertyMetadata(null)); public static readonly DependencyProperty PagesProperty = PagesPropertyKey.DependencyProperty; public IEnumerable<string> Pages { get { return (IEnumerable<string>)GetValue(PagesProperty); } } private static readonly DependencyPropertyKey PageCountPropertyKey = DependencyProperty.RegisterReadOnly("PageCount", typeof(int), _typeofSelf, new PropertyMetadata(1, OnPageCountPropertyChanged)); public static readonly DependencyProperty PageCountProperty = PageCountPropertyKey.DependencyProperty; public int PageCount { get { return (int)GetValue(PageCountProperty); } } private static void OnPageCountPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var ctrl = d as Pagination; var pageCount = (int)e.NewValue; /* if (ctrl._jumpPageTextBox != null) ctrl._jumpPageTextBox.Maximum = pageCount; */ } public static readonly DependencyProperty IsLiteProperty = DependencyProperty.Register("IsLite", typeof(bool), _typeofSelf, new PropertyMetadata(false)); public bool IsLite { get { return (bool)GetValue(IsLiteProperty); } set { SetValue(IsLiteProperty, value); } } public static readonly DependencyProperty CountProperty = DependencyProperty.Register("Count", typeof(int), _typeofSelf, new PropertyMetadata(0, OnCountPropertyChanged, CoerceCount)); public int Count { get { return (int)GetValue(CountProperty); } set { SetValue(CountProperty, value); } } private static object CoerceCount(DependencyObject d, object value) { var count = (int)value; return Math.Max(count, 0); } private static void OnCountPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var ctrl = d as Pagination; var count = (int)e.NewValue; ctrl.SetValue(PageCountPropertyKey, (int)Math.Ceiling(count * 1.0 / ctrl.CountPerPage)); ctrl.UpdatePages(); } public static readonly DependencyProperty CountPerPageProperty = DependencyProperty.Register("CountPerPage", typeof(int), _typeofSelf, new PropertyMetadata(50, OnCountPerPagePropertyChanged, CoerceCountPerPage)); public int CountPerPage { get { return (int)GetValue(CountPerPageProperty); } set { SetValue(CountPerPageProperty, value); } } private static object CoerceCountPerPage(DependencyObject d, object value) { var countPerPage = (int)value; return Math.Max(countPerPage, 1); } private static void OnCountPerPagePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var ctrl = d as Pagination; var countPerPage = (int)e.NewValue; if (ctrl._countPerPageTextBox != null) ctrl._countPerPageTextBox.Text = countPerPage.ToString(); ctrl.SetValue(PageCountPropertyKey, (int)Math.Ceiling(ctrl.Count * 1.0 / countPerPage)); if (ctrl.Current != 1) ctrl.Current = 1; else ctrl.UpdatePages(); } public static readonly DependencyProperty CurrentProperty = DependencyProperty.Register("Current", typeof(int), _typeofSelf, new PropertyMetadata(1, OnCurrentPropertyChanged, CoerceCurrent)); public int Current { get { return (int)GetValue(CurrentProperty); } set { SetValue(CurrentProperty, value); } } private static object CoerceCurrent(DependencyObject d, object value) { var current = (int)value; var ctrl = d as Pagination; return Math.Max(current, 1); } private static void OnCurrentPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var ctrl = d as Pagination; var current = (int)e.NewValue; if (ctrl._listBox != null) ctrl._listBox.SelectedItem = current.ToString(); if (ctrl._jumpPageTextBox != null) ctrl._jumpPageTextBox.Text = current.ToString(); ctrl.UpdatePages(); } #endregion #region Override public override void OnApplyTemplate() { base.OnApplyTemplate(); UnsubscribeEvents(); _countPerPageTextBox = GetTemplateChild(CountPerPageTextBoxTemplateName) as TextBox; _jumpPageTextBox = GetTemplateChild(JustPageTextBoxTemplateName) as TextBox; _listBox = GetTemplateChild(ListBoxTemplateName) as ListBox; Init(); SubscribeEvents(); } #endregion #region Event /// <summary> /// 分页 /// </summary> private void OnCountPerPageTextBoxChanged(object sender, TextChangedEventArgs e) { if (int.TryParse(_countPerPageTextBox.Text, out int _ountPerPage)) CountPerPage = _ountPerPage; } /// <summary> /// 跳转页 /// </summary> private void OnJumpPageTextBoxChanged(object sender, TextChangedEventArgs e) { if (int.TryParse(_jumpPageTextBox.Text, out int _current)) Current = _current; } /// <summary> /// 选择页 /// </summary> private void OnSelectionChanged(object sender, SelectionChangedEventArgs e) { if (_listBox.SelectedItem == null) return; Current = int.Parse(_listBox.SelectedItem.ToString()); } #endregion #region Private private void Init() { SetValue(PageCountPropertyKey, (int)Math.Ceiling(Count * 1.0 / CountPerPage)); _jumpPageTextBox.Text = Current.ToString(); //_jumpPageTextBox.Maximum = PageCount; _countPerPageTextBox.Text = CountPerPage.ToString(); if (_listBox != null) _listBox.SelectedItem = Current.ToString(); } private void UnsubscribeEvents() { if (_countPerPageTextBox != null) _countPerPageTextBox.TextChanged -= OnCountPerPageTextBoxChanged; if (_jumpPageTextBox != null) _jumpPageTextBox.TextChanged -= OnJumpPageTextBoxChanged; if (_listBox != null) _listBox.SelectionChanged -= OnSelectionChanged; } private void SubscribeEvents() { if (_countPerPageTextBox != null) _countPerPageTextBox.TextChanged += OnCountPerPageTextBoxChanged; if (_jumpPageTextBox != null) _jumpPageTextBox.TextChanged += OnJumpPageTextBoxChanged; if (_listBox != null) _listBox.SelectionChanged += OnSelectionChanged; } private void UpdatePages() { SetValue(PagesPropertyKey, GetPagers(Count, Current)); if (_listBox != null && _listBox.SelectedItem == null) _listBox.SelectedItem = Current.ToString(); } private IEnumerable<string> GetPagers(int count, int current) { if (count == 0) return null; if (PageCount <= 7) return Enumerable.Range(1, PageCount).Select(p => p.ToString()).ToArray(); if (current <= 4) return new string[] { "1", "2", "3", "4", "5", Ellipsis, PageCount.ToString() }; if (current >= PageCount - 3) return new string[] { "1", Ellipsis, (PageCount - 4).ToString(), (PageCount - 3).ToString(), (PageCount - 2).ToString(), (PageCount - 1).ToString(), PageCount.ToString() }; return new string[] { "1", Ellipsis, (current - 1).ToString(), current.ToString(), (current + 1).ToString(), Ellipsis, PageCount.ToString() }; } #endregion } }
34.578462
220
0.618259
[ "MIT" ]
WPFDevelopersOrg/WPFDevelopers
src/WPFDevelopers/Controls/Pagination/Pagination.cs
11,307
C#
//------------------------------------------------------------------------------ // <auto-generated /> // // This file was automatically generated by SWIG (http://www.swig.org). // Version 3.0.12 // // Do not make changes to this file unless you know what you are doing--modify // the SWIG interface file instead. //------------------------------------------------------------------------------ namespace EliteQuant { public class RelinkableCalibratedModelHandle : CalibratedModelHandle { private global::System.Runtime.InteropServices.HandleRef swigCPtr; internal RelinkableCalibratedModelHandle(global::System.IntPtr cPtr, bool cMemoryOwn) : base(NQuantLibcPINVOKE.RelinkableCalibratedModelHandle_SWIGUpcast(cPtr), cMemoryOwn) { swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); } internal static global::System.Runtime.InteropServices.HandleRef getCPtr(RelinkableCalibratedModelHandle obj) { return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; } ~RelinkableCalibratedModelHandle() { Dispose(); } public override void Dispose() { lock(this) { if (swigCPtr.Handle != global::System.IntPtr.Zero) { if (swigCMemOwn) { swigCMemOwn = false; NQuantLibcPINVOKE.delete_RelinkableCalibratedModelHandle(swigCPtr); } swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); } global::System.GC.SuppressFinalize(this); base.Dispose(); } } public RelinkableCalibratedModelHandle(CalibratedModel arg0) : this(NQuantLibcPINVOKE.new_RelinkableCalibratedModelHandle__SWIG_0(CalibratedModel.getCPtr(arg0)), true) { if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } public RelinkableCalibratedModelHandle() : this(NQuantLibcPINVOKE.new_RelinkableCalibratedModelHandle__SWIG_1(), true) { if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } public void linkTo(CalibratedModel arg0) { NQuantLibcPINVOKE.RelinkableCalibratedModelHandle_linkTo(swigCPtr, CalibratedModel.getCPtr(arg0)); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } } }
41.155172
176
0.714286
[ "Apache-2.0" ]
qg0/EliteQuant_Excel
SwigConversionLayer/csharp/RelinkableCalibratedModelHandle.cs
2,387
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.Immutable; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars { internal partial struct VirtualCharSequence { /// <summary> /// Abstraction over a contiguous chunk of <see cref="VirtualChar"/>s. This /// is used so we can expose <see cref="VirtualChar"/>s over an <see cref="ImmutableArray{VirtualChar}"/> /// or over a <see cref="string"/>. The latter is especially useful for reducing /// memory usage in common cases of string tokens without escapes. /// </summary> private abstract partial class Chunk { protected Chunk() { } public abstract int Length { get; } public abstract VirtualChar this[int index] { get; } } /// <summary> /// Thin wrapper over an actual <see cref="ImmutableArray{VirtualChar}"/>. /// This will be the common construct we generate when getting the /// <see cref="Chunk"/> for a string token that has escapes in it. /// </summary> private class ImmutableArrayChunk : Chunk { private readonly ImmutableArray<VirtualChar> _array; public ImmutableArrayChunk(ImmutableArray<VirtualChar> array) => _array = array; public override int Length => _array.Length; public override VirtualChar this[int index] => _array[index]; } /// <summary> /// Represents a <see cref="Chunk"/> on top of a normal /// string. This is the common case of the type of the sequence we would /// create for a normal string token without any escapes in it. /// </summary> private class StringChunk : Chunk { private readonly int _firstVirtualCharPosition; /// <summary> /// The underlying string that we're returning virtual chars from. Note: /// this will commonly include things like quote characters. Clients who /// do not want that should then ask for an appropriate <see cref="VirtualCharSequence.GetSubSequence"/> /// back that does not include those characters. /// </summary> private readonly string _underlyingData; public StringChunk(int firstVirtualCharPosition, string data) { _firstVirtualCharPosition = firstVirtualCharPosition; _underlyingData = data; } public override int Length => _underlyingData.Length; public override VirtualChar this[int index] => new VirtualChar( _underlyingData[index], new TextSpan(_firstVirtualCharPosition + index, length: 1)); } } }
40.266667
161
0.613245
[ "Apache-2.0" ]
20chan/roslyn
src/Workspaces/Core/Portable/EmbeddedLanguages/VirtualChars/VirtualCharSequence.Chunks.cs
3,022
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Persistence; namespace TravelogApi { public class Program { public static void Main(string[] args) { var build = CreateHostBuilder(args).Build(); using (var scope = build.Services.CreateScope()) { var services = scope.ServiceProvider; try { var context = services.GetRequiredService<AppDbContext>(); //apply any pending migrations context.Database.Migrate(); Seed.SeedData(context).GetAwaiter().GetResult(); } catch(Exception exc) { //log here } } build.Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
26.615385
78
0.563584
[ "MIT" ]
kdeng00/travelog-webapi
TravelogApi/Program.cs
1,384
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http.Headers; using System.Net.Sockets; using System.Net.Test.Common; using System.Runtime.InteropServices; using System.Security.Authentication; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Http.Functional.Tests { using Configuration = System.Net.Test.Common.Configuration; // Note: Disposing the HttpClient object automatically disposes the handler within. So, it is not necessary // to separately Dispose (or have a 'using' statement) for the handler. public abstract class HttpClientHandlerTest : HttpClientTestBase { readonly ITestOutputHelper _output; private const string ExpectedContent = "Test content"; private const string Username = "testuser"; private const string Password = "password"; private const string HttpDefaultPort = "80"; private readonly NetworkCredential _credential = new NetworkCredential(Username, Password); public static readonly object[][] EchoServers = Configuration.Http.EchoServers; public static readonly object[][] VerifyUploadServers = Configuration.Http.VerifyUploadServers; public static readonly object[][] CompressedServers = Configuration.Http.CompressedServers; public static readonly object[][] HeaderValueAndUris = { new object[] { "X-CustomHeader", "x-value", Configuration.Http.RemoteEchoServer }, new object[] { "X-CustomHeader", "x-value", Configuration.Http.RedirectUriForDestinationUri( secure:false, statusCode:302, destinationUri:Configuration.Http.RemoteEchoServer, hops:1) }, }; public static readonly object[][] HeaderWithEmptyValueAndUris = { new object[] { "X-Cust-Header-NoValue", "" , Configuration.Http.RemoteEchoServer }, new object[] { "X-Cust-Header-NoValue", "" , Configuration.Http.RedirectUriForDestinationUri( secure:false, statusCode:302, destinationUri:Configuration.Http.RemoteEchoServer, hops:1) }, }; public static readonly object[][] Http2Servers = Configuration.Http.Http2Servers; public static readonly object[][] Http2NoPushServers = Configuration.Http.Http2NoPushServers; public static readonly object[][] RedirectStatusCodes = { new object[] { 300 }, new object[] { 301 }, new object[] { 302 }, new object[] { 303 }, new object[] { 307 } }; public static readonly object[][] RedirectStatusCodesOldMethodsNewMethods = { new object[] { 300, "GET", "GET" }, new object[] { 300, "POST", "GET" }, new object[] { 300, "HEAD", "HEAD" }, new object[] { 301, "GET", "GET" }, new object[] { 301, "POST", "GET" }, new object[] { 301, "HEAD", "HEAD" }, new object[] { 302, "GET", "GET" }, new object[] { 302, "POST", "GET" }, new object[] { 302, "HEAD", "HEAD" }, new object[] { 303, "GET", "GET" }, new object[] { 303, "POST", "GET" }, new object[] { 303, "HEAD", "HEAD" }, new object[] { 307, "GET", "GET" }, new object[] { 307, "POST", "POST" }, new object[] { 307, "HEAD", "HEAD" }, }; // Standard HTTP methods defined in RFC7231: http://tools.ietf.org/html/rfc7231#section-4.3 // "GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "TRACE" public static readonly IEnumerable<object[]> HttpMethods = GetMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "TRACE", "CUSTOM1"); public static readonly IEnumerable<object[]> HttpMethodsThatAllowContent = GetMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "CUSTOM1"); public static readonly IEnumerable<object[]> HttpMethodsThatDontAllowContent = GetMethods("HEAD", "TRACE"); private static bool IsWindows10Version1607OrGreater => PlatformDetection.IsWindows10Version1607OrGreater; private static IEnumerable<object[]> GetMethods(params string[] methods) { foreach (string method in methods) { foreach (bool secure in new[] { true, false }) { yield return new object[] { method, secure }; } } } public HttpClientHandlerTest(ITestOutputHelper output) { _output = output; if (PlatformDetection.IsFullFramework) { // On .NET Framework, the default limit for connections/server is very low (2). // On .NET Core, the default limit is higher. Since these tests run in parallel, // the limit needs to be increased to avoid timeouts when running the tests. System.Net.ServicePointManager.DefaultConnectionLimit = int.MaxValue; } } [Fact] public void Ctor_ExpectedDefaultPropertyValues_CommonPlatform() { using (HttpClientHandler handler = CreateHttpClientHandler()) { // Same as .NET Framework (Desktop). Assert.Equal(DecompressionMethods.None, handler.AutomaticDecompression); Assert.True(handler.AllowAutoRedirect); Assert.Equal(ClientCertificateOption.Manual, handler.ClientCertificateOptions); CookieContainer cookies = handler.CookieContainer; Assert.NotNull(cookies); Assert.Equal(0, cookies.Count); Assert.Null(handler.Credentials); Assert.Equal(50, handler.MaxAutomaticRedirections); Assert.NotNull(handler.Properties); Assert.Equal(null, handler.Proxy); Assert.True(handler.SupportsAutomaticDecompression); Assert.True(handler.UseCookies); Assert.False(handler.UseDefaultCredentials); Assert.True(handler.UseProxy); } } [SkipOnTargetFramework(TargetFrameworkMonikers.Uap)] [Fact] public void Ctor_ExpectedDefaultPropertyValues_NotUapPlatform() { using (HttpClientHandler handler = CreateHttpClientHandler()) { // Same as .NET Framework (Desktop). Assert.Equal(64, handler.MaxResponseHeadersLength); Assert.False(handler.PreAuthenticate); Assert.True(handler.SupportsProxy); Assert.True(handler.SupportsRedirectConfiguration); // Changes from .NET Framework (Desktop). if (!PlatformDetection.IsFullFramework) { Assert.False(handler.CheckCertificateRevocationList); Assert.Equal(0, handler.MaxRequestContentBufferSize); Assert.Equal(SslProtocols.None, handler.SslProtocols); } } } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsUap))] public void Ctor_ExpectedDefaultPropertyValues_UapPlatform() { using (HttpClientHandler handler = CreateHttpClientHandler()) { Assert.True(handler.CheckCertificateRevocationList); Assert.Equal(0, handler.MaxRequestContentBufferSize); Assert.Equal(-1, handler.MaxResponseHeadersLength); Assert.True(handler.PreAuthenticate); Assert.Equal(SslProtocols.None, handler.SslProtocols); Assert.False(handler.SupportsProxy); Assert.False(handler.SupportsRedirectConfiguration); } } [Fact] public void Credentials_SetGet_Roundtrips() { using (HttpClientHandler handler = CreateHttpClientHandler()) { var creds = new NetworkCredential("username", "password", "domain"); handler.Credentials = null; Assert.Null(handler.Credentials); handler.Credentials = creds; Assert.Same(creds, handler.Credentials); handler.Credentials = CredentialCache.DefaultCredentials; Assert.Same(CredentialCache.DefaultCredentials, handler.Credentials); } } [Theory] [InlineData(-1)] [InlineData(0)] public void MaxAutomaticRedirections_InvalidValue_Throws(int redirects) { using (HttpClientHandler handler = CreateHttpClientHandler()) { Assert.Throws<ArgumentOutOfRangeException>(() => handler.MaxAutomaticRedirections = redirects); } } [Theory] [InlineData(-1)] [InlineData((long)int.MaxValue + (long)1)] public void MaxRequestContentBufferSize_SetInvalidValue_ThrowsArgumentOutOfRangeException(long value) { using (HttpClientHandler handler = CreateHttpClientHandler()) { Assert.Throws<ArgumentOutOfRangeException>(() => handler.MaxRequestContentBufferSize = value); } } [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "UAP will send default credentials based on other criteria.")] [Theory] [InlineData(false)] [InlineData(true)] public async Task UseDefaultCredentials_SetToFalseAndServerNeedsAuth_StatusCodeUnauthorized(bool useProxy) { HttpClientHandler handler = CreateHttpClientHandler(); handler.UseProxy = useProxy; handler.UseDefaultCredentials = false; using (var client = new HttpClient(handler)) { Uri uri = Configuration.Http.NegotiateAuthUriForDefaultCreds(secure: false); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); } } } [OuterLoop] [Theory, MemberData(nameof(RedirectStatusCodes))] public async Task DefaultHeaders_SetCredentials_ClearedOnRedirect(int statusCode) { HttpClientHandler handler = CreateHttpClientHandler(); using (var client = new HttpClient(handler)) { string credentialString = _credential.UserName + ":" + _credential.Password; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentialString); Uri uri = Configuration.Http.RedirectUriForDestinationUri( secure: false, statusCode: statusCode, destinationUri: Configuration.Http.RemoteEchoServer, hops: 1); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { string responseText = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseText); Assert.False(TestHelper.JsonMessageContainsKey(responseText, "Authorization")); } } } [Fact] public void Properties_Get_CountIsZero() { using (HttpClientHandler handler = CreateHttpClientHandler()) { IDictionary<String, object> dict = handler.Properties; Assert.Same(dict, handler.Properties); Assert.Equal(0, dict.Count); } } [Fact] public void Properties_AddItemToDictionary_ItemPresent() { using (HttpClientHandler handler = CreateHttpClientHandler()) { IDictionary<String, object> dict = handler.Properties; var item = new Object(); dict.Add("item", item); object value; Assert.True(dict.TryGetValue("item", out value)); Assert.Equal(item, value); } } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(EchoServers))] public async Task SendAsync_SimpleGet_Success(Uri remoteServer) { using (HttpClient client = CreateHttpClient()) using (HttpResponseMessage response = await client.GetAsync(remoteServer)) { string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, null); } } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(false)] [InlineData(true)] public async Task SendAsync_GetWithValidHostHeader_Success(bool withPort) { var m = new HttpRequestMessage(HttpMethod.Get, Configuration.Http.SecureRemoteEchoServer); m.Headers.Host = withPort ? Configuration.Http.SecureHost + ":123" : Configuration.Http.SecureHost; using (HttpClient client = CreateHttpClient()) using (HttpResponseMessage response = await client.SendAsync(m)) { string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, null); } } [OuterLoop] // TODO: Issue #11345 [Fact] public async Task SendAsync_GetWithInvalidHostHeader_ThrowsException() { if (PlatformDetection.IsNetCore && !UseSocketsHttpHandler) { // [ActiveIssue(24862)] // WinHttpHandler and CurlHandler do not use the Host header to influence the SSL auth. // .NET Framework and SocketsHttpHandler do. return; } var m = new HttpRequestMessage(HttpMethod.Get, Configuration.Http.SecureRemoteEchoServer); m.Headers.Host = "hostheaderthatdoesnotmatch"; using (HttpClient client = CreateHttpClient()) { await Assert.ThrowsAsync<HttpRequestException>(() => client.SendAsync(m)); } } [ActiveIssue(22158, TargetFrameworkMonikers.Uap)] [OuterLoop] // TODO: Issue #11345 [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // TODO: make unconditional after #26813 and #26476 are fixed public async Task GetAsync_IPv6LinkLocalAddressUri_Success() { using (HttpClient client = CreateHttpClient()) { var options = new LoopbackServer.Options { Address = TestHelper.GetIPv6LinkLocalAddress() }; await LoopbackServer.CreateServerAsync(async (server, url) => { _output.WriteLine(url.ToString()); await TestHelper.WhenAllCompletedOrAnyFailed( server.AcceptConnectionSendResponseAndCloseAsync(), client.GetAsync(url)); }, options); } } [OuterLoop] // TODO: Issue #11345 [Theory] [MemberData(nameof(GetAsync_IPBasedUri_Success_MemberData))] public async Task GetAsync_IPBasedUri_Success(IPAddress address) { using (HttpClient client = CreateHttpClient()) { var options = new LoopbackServer.Options { Address = address }; await LoopbackServer.CreateServerAsync(async (server, url) => { _output.WriteLine(url.ToString()); await TestHelper.WhenAllCompletedOrAnyFailed( server.AcceptConnectionSendResponseAndCloseAsync(), client.GetAsync(url)); }, options); } } public static IEnumerable<object[]> GetAsync_IPBasedUri_Success_MemberData() { foreach (var addr in new[] { IPAddress.Loopback, IPAddress.IPv6Loopback }) { if (addr != null) { yield return new object[] { addr }; } } } [OuterLoop] // TODO: Issue #11345 [Fact] public async Task SendAsync_MultipleRequestsReusingSameClient_Success() { using (HttpClient client = CreateHttpClient()) { for (int i = 0; i < 3; i++) { using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } } [OuterLoop] // TODO: Issue #11345 [Fact] public async Task GetAsync_ResponseContentAfterClientAndHandlerDispose_Success() { using (HttpClient client = CreateHttpClient()) using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.SecureRemoteEchoServer)) { client.Dispose(); Assert.NotNull(response); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody(responseContent, response.Content.Headers.ContentMD5, false, null); } } [OuterLoop] // TODO: Issue #11345 [Fact] public async Task SendAsync_Cancel_CancellationTokenPropagates() { var cts = new CancellationTokenSource(); cts.Cancel(); using (HttpClient client = CreateHttpClient()) { var request = new HttpRequestMessage(HttpMethod.Post, Configuration.Http.RemoteEchoServer); TaskCanceledException ex = await Assert.ThrowsAsync<TaskCanceledException>(() => client.SendAsync(request, cts.Token)); Assert.True(cts.Token.IsCancellationRequested, "cts token IsCancellationRequested"); if (!PlatformDetection.IsFullFramework) { // .NET Framework has bug where it doesn't propagate token information. Assert.True(ex.CancellationToken.IsCancellationRequested, "exception token IsCancellationRequested"); } } } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(CompressedServers))] public async Task GetAsync_SetAutomaticDecompression_ContentDecompressed(Uri server) { HttpClientHandler handler = CreateHttpClientHandler(); handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; using (var client = new HttpClient(handler)) { using (HttpResponseMessage response = await client.GetAsync(server)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, null); } } } [Theory] [InlineData("[::1234]")] [InlineData("[::1234]:8080")] public async Task GetAsync_IPv6AddressInHostHeader_CorrectlyFormatted(string host) { string ipv6Address = "http://" + host; bool connectionAccepted = false; await LoopbackServer.CreateClientAndServerAsync(async proxyUri => { using (HttpClientHandler handler = CreateHttpClientHandler()) using (var client = new HttpClient(handler)) { handler.Proxy = new WebProxy(proxyUri); try { await client.GetAsync(ipv6Address); } catch { } } }, server => server.AcceptConnectionAsync(async connection => { connectionAccepted = true; List<string> headers = await connection.ReadRequestHeaderAndSendResponseAsync(); Assert.Contains($"Host: {host}", headers); })); Assert.True(connectionAccepted); } [Theory] [InlineData("1.2.3.4")] [InlineData("1.2.3.4:8080")] [InlineData("[::1234]")] [InlineData("[::1234]:8080")] public async Task ProxiedIPAddressRequest_NotDefaultPort_CorrectlyFormatted(string host) { string uri = "http://" + host; bool connectionAccepted = false; await LoopbackServer.CreateClientAndServerAsync(async proxyUri => { using (HttpClientHandler handler = CreateHttpClientHandler()) using (var client = new HttpClient(handler)) { handler.Proxy = new WebProxy(proxyUri); try { await client.GetAsync(uri); } catch { } } }, server => server.AcceptConnectionAsync(async connection => { connectionAccepted = true; List<string> headers = await connection.ReadRequestHeaderAndSendResponseAsync(); Assert.Contains($"GET {uri}/ HTTP/1.1", headers); })); Assert.True(connectionAccepted); } public static IEnumerable<object[]> DestinationHost_MemberData() { yield return new object[] { Configuration.Http.Host }; yield return new object[] { "1.2.3.4" }; yield return new object[] { "[::1234]" }; } [Theory] [OuterLoop] // Test uses azure endpoint. [MemberData(nameof(DestinationHost_MemberData))] public async Task ProxiedRequest_DefaultPort_PortStrippedOffInUri(string host) { string addressUri = $"http://{host}:{HttpDefaultPort}/"; string expectedAddressUri = $"http://{host}/"; bool connectionAccepted = false; await LoopbackServer.CreateClientAndServerAsync(async proxyUri => { using (HttpClientHandler handler = CreateHttpClientHandler()) using (var client = new HttpClient(handler)) { handler.Proxy = new WebProxy(proxyUri); try { await client.GetAsync(addressUri); } catch { } } }, server => server.AcceptConnectionAsync(async connection => { connectionAccepted = true; List<string> headers = await connection.ReadRequestHeaderAndSendResponseAsync(); Assert.Contains($"GET {expectedAddressUri} HTTP/1.1", headers); })); Assert.True(connectionAccepted); } [Fact] [OuterLoop] // Test uses azure endpoint. public async Task ProxyTunnelRequest_PortSpecified_NotStrippedOffInUri() { // Https proxy request will use CONNECT tunnel, even the default 443 port is specified, it will not be stripped off. string requestTarget = $"{Configuration.Http.SecureHost}:443"; string addressUri = $"https://{requestTarget}/"; bool connectionAccepted = false; await LoopbackServer.CreateClientAndServerAsync(async proxyUri => { using (HttpClientHandler handler = CreateHttpClientHandler()) using (var client = new HttpClient(handler)) { handler.Proxy = new WebProxy(proxyUri); handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates; try { await client.GetAsync(addressUri); } catch { } } }, server => server.AcceptConnectionAsync(async connection => { connectionAccepted = true; List<string> headers = await connection.ReadRequestHeaderAndSendResponseAsync(); Assert.Contains($"CONNECT {requestTarget} HTTP/1.1", headers); })); Assert.True(connectionAccepted); } public static IEnumerable<object[]> SecureAndNonSecure_IPBasedUri_MemberData() => from address in new[] { IPAddress.Loopback, IPAddress.IPv6Loopback } from useSsl in new[] { true, false } select new object[] { address, useSsl }; [Theory] [MemberData(nameof(SecureAndNonSecure_IPBasedUri_MemberData))] public async Task GetAsync_SecureAndNonSecureIPBasedUri_CorrectlyFormatted(IPAddress address, bool useSsl) { var options = new LoopbackServer.Options { Address = address, UseSsl= useSsl }; bool connectionAccepted = false; string host = ""; await LoopbackServer.CreateClientAndServerAsync(async url => { host = $"{url.Host}:{url.Port}"; using (HttpClientHandler handler = CreateHttpClientHandler()) using (var client = new HttpClient(handler)) { if (useSsl) { handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates; } try { await client.GetAsync(url); } catch { } } }, server => server.AcceptConnectionAsync(async connection => { connectionAccepted = true; List<string> headers = await connection.ReadRequestHeaderAndSendResponseAsync(); Assert.Contains($"Host: {host}", headers); }), options); Assert.True(connectionAccepted); } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(CompressedServers))] public async Task GetAsync_SetAutomaticDecompression_HeadersRemoved(Uri server) { HttpClientHandler handler = CreateHttpClientHandler(); handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; using (var client = new HttpClient(handler)) using (HttpResponseMessage response = await client.GetAsync(server, HttpCompletionOption.ResponseHeadersRead)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.False(response.Content.Headers.Contains("Content-Encoding"), "Content-Encoding unexpectedly found"); Assert.False(response.Content.Headers.Contains("Content-Length"), "Content-Length unexpectedly found"); } } [OuterLoop] // TODO: Issue #11345 [Fact] public async Task GetAsync_ServerNeedsBasicAuthAndSetDefaultCredentials_StatusCodeUnauthorized() { HttpClientHandler handler = CreateHttpClientHandler(); handler.Credentials = CredentialCache.DefaultCredentials; using (var client = new HttpClient(handler)) { Uri uri = Configuration.Http.BasicAuthUriForCreds(secure: false, userName: Username, password: Password); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); } } } [OuterLoop] // TODO: Issue #11345 [Fact] public async Task GetAsync_ServerNeedsAuthAndSetCredential_StatusCodeOK() { HttpClientHandler handler = CreateHttpClientHandler(); handler.Credentials = _credential; using (var client = new HttpClient(handler)) { Uri uri = Configuration.Http.BasicAuthUriForCreds(secure: false, userName: Username, password: Password); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } [OuterLoop] // TODO: Issue #11345 [Fact] public void GetAsync_ServerNeedsAuthAndNoCredential_StatusCodeUnauthorized() { // UAP HTTP stack caches connections per-process. This causes interference when these tests run in // the same process as the other tests. Each test needs to be isolated to its own process. // See dicussion: https://github.com/dotnet/corefx/issues/21945 RemoteInvoke(async useSocketsHttpHandlerString => { using (var client = CreateHttpClient(useSocketsHttpHandlerString)) { Uri uri = Configuration.Http.BasicAuthUriForCreds(secure: false, userName: Username, password: Password); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); } return SuccessExitCode; } }, UseSocketsHttpHandler.ToString()).Dispose(); } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData("WWW-Authenticate: CustomAuth\r\n")] [InlineData("")] // RFC7235 requires servers to send this header with 401 but some servers don't. public async Task GetAsync_ServerNeedsNonStandardAuthAndSetCredential_StatusCodeUnauthorized(string authHeaders) { await LoopbackServer.CreateServerAsync(async (server, url) => { HttpClientHandler handler = CreateHttpClientHandler(); handler.Credentials = new NetworkCredential("unused", "unused"); using (var client = new HttpClient(handler)) { Task<HttpResponseMessage> getResponseTask = client.GetAsync(url); Task<List<string>> serverTask = server.AcceptConnectionSendResponseAndCloseAsync(HttpStatusCode.Unauthorized); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); using (HttpResponseMessage response = await getResponseTask) { Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); } } }); } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(RedirectStatusCodes))] public async Task GetAsync_AllowAutoRedirectFalse_RedirectFromHttpToHttp_StatusCodeRedirect(int statusCode) { HttpClientHandler handler = CreateHttpClientHandler(); handler.AllowAutoRedirect = false; using (var client = new HttpClient(handler)) { Uri uri = Configuration.Http.RedirectUriForDestinationUri( secure: false, statusCode: statusCode, destinationUri: Configuration.Http.RemoteEchoServer, hops: 1); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(statusCode, (int)response.StatusCode); Assert.Equal(uri, response.RequestMessage.RequestUri); } } } [Theory, MemberData(nameof(RedirectStatusCodesOldMethodsNewMethods))] public async Task AllowAutoRedirect_True_ValidateNewMethodUsedOnRedirection( int statusCode, string oldMethod, string newMethod) { if (IsCurlHandler && statusCode == 300 && oldMethod == "POST") { // Known behavior: curl does not change method to "GET" // https://github.com/dotnet/corefx/issues/26434 newMethod = "POST"; } HttpClientHandler handler = CreateHttpClientHandler(); using (var client = new HttpClient(handler)) { await LoopbackServer.CreateServerAsync(async (origServer, origUrl) => { var request = new HttpRequestMessage(new HttpMethod(oldMethod), origUrl); Task<HttpResponseMessage> getResponseTask = client.SendAsync(request); await LoopbackServer.CreateServerAsync(async (redirServer, redirUrl) => { // Original URL will redirect to a different URL Task<List<string>> serverTask = origServer.AcceptConnectionSendResponseAndCloseAsync((HttpStatusCode)statusCode, $"Location: {redirUrl}\r\n"); await Task.WhenAny(getResponseTask, serverTask); Assert.False(getResponseTask.IsCompleted, $"{getResponseTask.Status}: {getResponseTask.Exception}"); await serverTask; // Redirected URL answers with success serverTask = redirServer.AcceptConnectionSendResponseAndCloseAsync(); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); List<string> receivedRequest = await serverTask; string[] statusLineParts = receivedRequest[0].Split(' '); using (HttpResponseMessage response = await getResponseTask) { Assert.Equal(200, (int)response.StatusCode); Assert.Equal(newMethod, statusLineParts[0]); } }); }); } } [Theory] [InlineData(300)] [InlineData(301)] [InlineData(302)] [InlineData(303)] public async Task AllowAutoRedirect_True_PostToGetDoesNotSendTE(int statusCode) { if (IsCurlHandler && statusCode == 300) { // ISSUE #26434: // CurlHandler doesn't change POST to GET for 300 response (see above test). return; } if (IsWinHttpHandler) { // ISSUE #27440: // This test occasionally fails on WinHttpHandler. // Likely this is due to the way the loopback server is sending the response before reading the entire request. // We should change the server behavior here. return; } HttpClientHandler handler = CreateHttpClientHandler(); using (var client = new HttpClient(handler)) { await LoopbackServer.CreateServerAsync(async (origServer, origUrl) => { var request = new HttpRequestMessage(HttpMethod.Post, origUrl); request.Content = new StringContent(ExpectedContent); request.Headers.TransferEncodingChunked = true; Task<HttpResponseMessage> getResponseTask = client.SendAsync(request); await LoopbackServer.CreateServerAsync(async (redirServer, redirUrl) => { // Original URL will redirect to a different URL Task serverTask = origServer.AcceptConnectionAsync(async connection => { // Send Connection: close so the client will close connection after request is sent, // meaning we can just read to the end to get the content await connection.ReadRequestHeaderAndSendResponseAsync((HttpStatusCode)statusCode, $"Location: {redirUrl}\r\nConnection: close\r\n"); connection.Socket.Shutdown(SocketShutdown.Send); await connection.Reader.ReadToEndAsync(); }); await Task.WhenAny(getResponseTask, serverTask); Assert.False(getResponseTask.IsCompleted, $"{getResponseTask.Status}: {getResponseTask.Exception}"); await serverTask; // Redirected URL answers with success List<string> receivedRequest = null; string receivedContent = null; Task serverTask2 = redirServer.AcceptConnectionAsync(async connection => { // Send Connection: close so the client will close connection after request is sent, // meaning we can just read to the end to get the content receivedRequest = await connection.ReadRequestHeaderAndSendResponseAsync(additionalHeaders: "Connection: close\r\n"); connection.Socket.Shutdown(SocketShutdown.Send); receivedContent = await connection.Reader.ReadToEndAsync(); }); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask2); string[] statusLineParts = receivedRequest[0].Split(' '); Assert.Equal("GET", statusLineParts[0]); Assert.DoesNotContain(receivedRequest, line => line.StartsWith("Transfer-Encoding")); Assert.DoesNotContain(receivedRequest, line => line.StartsWith("Content-Length")); using (HttpResponseMessage response = await getResponseTask) { Assert.Equal(200, (int)response.StatusCode); } }); }); } } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(RedirectStatusCodes))] public async Task GetAsync_AllowAutoRedirectTrue_RedirectFromHttpToHttp_StatusCodeOK(int statusCode) { HttpClientHandler handler = CreateHttpClientHandler(); handler.AllowAutoRedirect = true; using (var client = new HttpClient(handler)) { Uri uri = Configuration.Http.RedirectUriForDestinationUri( secure: false, statusCode: statusCode, destinationUri: Configuration.Http.RemoteEchoServer, hops: 1); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(Configuration.Http.RemoteEchoServer, response.RequestMessage.RequestUri); } } } [OuterLoop] // TODO: Issue #11345 [Fact] public async Task GetAsync_AllowAutoRedirectTrue_RedirectFromHttpToHttps_StatusCodeOK() { HttpClientHandler handler = CreateHttpClientHandler(); handler.AllowAutoRedirect = true; using (var client = new HttpClient(handler)) { Uri uri = Configuration.Http.RedirectUriForDestinationUri( secure: false, statusCode: 302, destinationUri: Configuration.Http.SecureRemoteEchoServer, hops: 1); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(Configuration.Http.SecureRemoteEchoServer, response.RequestMessage.RequestUri); } } } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Framework allows HTTPS to HTTP redirection")] [OuterLoop] // TODO: Issue #11345 [Fact] public async Task GetAsync_AllowAutoRedirectTrue_RedirectFromHttpsToHttp_StatusCodeRedirect() { HttpClientHandler handler = CreateHttpClientHandler(); handler.AllowAutoRedirect = true; using (var client = new HttpClient(handler)) { Uri uri = Configuration.Http.RedirectUriForDestinationUri( secure: true, statusCode: 302, destinationUri: Configuration.Http.RemoteEchoServer, hops: 1); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); Assert.Equal(uri, response.RequestMessage.RequestUri); } } } [Fact] public async Task GetAsync_AllowAutoRedirectTrue_RedirectWithoutLocation_ReturnsOriginalResponse() { // [ActiveIssue(24819, TestPlatforms.Windows)] if (PlatformDetection.IsWindows && PlatformDetection.IsNetCore && !UseSocketsHttpHandler) { return; } HttpClientHandler handler = CreateHttpClientHandler(); handler.AllowAutoRedirect = true; using (var client = new HttpClient(handler)) { await LoopbackServer.CreateServerAsync(async (server, url) => { Task<HttpResponseMessage> getTask = client.GetAsync(url); Task<List<string>> serverTask = server.AcceptConnectionSendResponseAndCloseAsync(HttpStatusCode.Found); await TestHelper.WhenAllCompletedOrAnyFailed(getTask, serverTask); using (HttpResponseMessage response = await getTask) { Assert.Equal(302, (int)response.StatusCode); } }); } } [OuterLoop] // TODO: Issue #11345 [Fact] public async Task GetAsync_AllowAutoRedirectTrue_RedirectToUriWithParams_RequestMsgUriSet() { HttpClientHandler handler = CreateHttpClientHandler(); handler.AllowAutoRedirect = true; Uri targetUri = Configuration.Http.BasicAuthUriForCreds(secure: false, userName: Username, password: Password); using (var client = new HttpClient(handler)) { Uri uri = Configuration.Http.RedirectUriForDestinationUri( secure: false, statusCode: 302, destinationUri: targetUri, hops: 1); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); Assert.Equal(targetUri, response.RequestMessage.RequestUri); } } } [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not currently supported on UAP")] [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(3, 2)] [InlineData(3, 3)] [InlineData(3, 4)] public async Task GetAsync_MaxAutomaticRedirectionsNServerHops_ThrowsIfTooMany(int maxHops, int hops) { if (IsWinHttpHandler && !PlatformDetection.IsWindows10Version1703OrGreater) { // Skip this test if using WinHttpHandler but on a release prior to Windows 10 Creators Update. _output.WriteLine("Skipping test due to Windows 10 version prior to Version 1703."); return; } else if (PlatformDetection.IsFullFramework) { // Skip this test if running on .NET Framework. Exceeding max redirections will not throw // exception. Instead, it simply returns the 3xx response. _output.WriteLine("Skipping test on .NET Framework due to behavior difference."); return; } HttpClientHandler handler = CreateHttpClientHandler(); handler.MaxAutomaticRedirections = maxHops; using (var client = new HttpClient(handler)) { Task<HttpResponseMessage> t = client.GetAsync(Configuration.Http.RedirectUriForDestinationUri( secure: false, statusCode: 302, destinationUri: Configuration.Http.RemoteEchoServer, hops: hops)); if (hops <= maxHops) { using (HttpResponseMessage response = await t) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(Configuration.Http.RemoteEchoServer, response.RequestMessage.RequestUri); } } else { if (UseSocketsHttpHandler) { using (HttpResponseMessage response = await t) { Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); } } else { await Assert.ThrowsAsync<HttpRequestException>(() => t); } } } } [OuterLoop] // TODO: Issue #11345 [Fact] public async Task GetAsync_AllowAutoRedirectTrue_RedirectWithRelativeLocation() { HttpClientHandler handler = CreateHttpClientHandler(); handler.AllowAutoRedirect = true; using (var client = new HttpClient(handler)) { Uri uri = Configuration.Http.RedirectUriForDestinationUri( secure: false, statusCode: 302, destinationUri: Configuration.Http.RemoteEchoServer, hops: 1, relative: true); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(Configuration.Http.RemoteEchoServer, response.RequestMessage.RequestUri); } } } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(200)] [InlineData(201)] [InlineData(400)] public async Task GetAsync_AllowAutoRedirectTrue_NonRedirectStatusCode_LocationHeader_NoRedirect(int statusCode) { HttpClientHandler handler = CreateHttpClientHandler(); handler.AllowAutoRedirect = true; using (var client = new HttpClient(handler)) { await LoopbackServer.CreateServerAsync(async (origServer, origUrl) => { await LoopbackServer.CreateServerAsync(async (redirectServer, redirectUrl) => { Task<HttpResponseMessage> getResponseTask = client.GetAsync(origUrl); Task redirectTask = redirectServer.AcceptConnectionSendResponseAndCloseAsync(); await TestHelper.WhenAllCompletedOrAnyFailed( getResponseTask, origServer.AcceptConnectionSendResponseAndCloseAsync((HttpStatusCode)statusCode, $"Location: {redirectUrl}\r\n")); using (HttpResponseMessage response = await getResponseTask) { Assert.Equal(statusCode, (int)response.StatusCode); Assert.Equal(origUrl, response.RequestMessage.RequestUri); Assert.False(redirectTask.IsCompleted, "Should not have redirected to Location"); } }); }); } } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData("#origFragment", "", "#origFragment", false)] [InlineData("#origFragment", "", "#origFragment", true)] [InlineData("", "#redirFragment", "#redirFragment", false)] [InlineData("", "#redirFragment", "#redirFragment", true)] [InlineData("#origFragment", "#redirFragment", "#redirFragment", false)] [InlineData("#origFragment", "#redirFragment", "#redirFragment", true)] public async Task GetAsync_AllowAutoRedirectTrue_RetainsOriginalFragmentIfAppropriate( string origFragment, string redirFragment, string expectedFragment, bool useRelativeRedirect) { if (IsCurlHandler) { // Starting with libcurl 7.20, "fragment part of URLs are no longer sent to the server". // So CurlHandler doesn't send fragments. return; } if (IsNetfxHandler) { // Similarly, netfx doesn't send fragments at all. return; } if (IsWinHttpHandler) { // According to https://tools.ietf.org/html/rfc7231#section-7.1.2, // "If the Location value provided in a 3xx (Redirection) response does // not have a fragment component, a user agent MUST process the // redirection as if the value inherits the fragment component of the // URI reference used to generate the request target(i.e., the // redirection inherits the original reference's fragment, if any)." // WINHTTP is not doing this, and thus neither is WinHttpHandler. // It also sometimes doesn't include the fragments for redirects // even in other cases. return; } HttpClientHandler handler = CreateHttpClientHandler(); handler.AllowAutoRedirect = true; using (var client = new HttpClient(handler)) { await LoopbackServer.CreateServerAsync(async (origServer, origUrl) => { origUrl = new UriBuilder(origUrl) { Fragment = origFragment }.Uri; Uri redirectUrl = new UriBuilder(origUrl) { Fragment = redirFragment }.Uri; if (useRelativeRedirect) { redirectUrl = new Uri(redirectUrl.GetComponents(UriComponents.PathAndQuery | UriComponents.Fragment, UriFormat.SafeUnescaped), UriKind.Relative); } Uri expectedUrl = new UriBuilder(origUrl) { Fragment = expectedFragment }.Uri; // Make and receive the first request that'll be redirected. Task<HttpResponseMessage> getResponse = client.GetAsync(origUrl); Task firstRequest = origServer.AcceptConnectionSendResponseAndCloseAsync(HttpStatusCode.Found, $"Location: {redirectUrl}\r\n"); Assert.Equal(firstRequest, await Task.WhenAny(firstRequest, getResponse)); // Receive the second request. Task<List<string>> secondRequest = origServer.AcceptConnectionSendResponseAndCloseAsync(); await TestHelper.WhenAllCompletedOrAnyFailed(secondRequest, getResponse); // Make sure the server received the second request for the right Uri. Assert.NotEmpty(secondRequest.Result); string[] statusLineParts = secondRequest.Result[0].Split(' '); Assert.Equal(3, statusLineParts.Length); Assert.Equal(expectedUrl.GetComponents(UriComponents.PathAndQuery | UriComponents.Fragment, UriFormat.SafeUnescaped), statusLineParts[1]); // Make sure the request message was updated with the correct redirected location. using (HttpResponseMessage response = await getResponse) { Assert.Equal(200, (int)response.StatusCode); Assert.Equal(expectedUrl.ToString(), response.RequestMessage.RequestUri.ToString()); } }); } } [Fact] [OuterLoop] // Test uses azure endpoint. public async Task GetAsync_CredentialIsNetworkCredentialUriRedirect_StatusCodeUnauthorized() { HttpClientHandler handler = CreateHttpClientHandler(); handler.Credentials = _credential; using (var client = new HttpClient(handler)) { Uri redirectUri = Configuration.Http.RedirectUriForCreds( secure: false, statusCode: 302, userName: Username, password: Password); using (HttpResponseMessage unAuthResponse = await client.GetAsync(redirectUri)) { Assert.Equal(HttpStatusCode.Unauthorized, unAuthResponse.StatusCode); } } } [Fact] [OuterLoop] // Test uses azure endpoint. public async Task HttpClientHandler_CredentialIsNotCredentialCacheAfterRedirect_StatusCodeOK() { HttpClientHandler handler = CreateHttpClientHandler(); handler.Credentials = _credential; using (var client = new HttpClient(handler)) { Uri redirectUri = Configuration.Http.RedirectUriForCreds( secure: false, statusCode: 302, userName: Username, password: Password); using (HttpResponseMessage unAuthResponse = await client.GetAsync(redirectUri)) { Assert.Equal(HttpStatusCode.Unauthorized, unAuthResponse.StatusCode); } // Use the same handler to perform get request, authentication should succeed after redirect. Uri uri = Configuration.Http.BasicAuthUriForCreds(secure: true, userName: Username, password: Password); using (HttpResponseMessage authResponse = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.OK, authResponse.StatusCode); } } } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(RedirectStatusCodes))] public async Task GetAsync_CredentialIsCredentialCacheUriRedirect_StatusCodeOK(int statusCode) { Uri uri = Configuration.Http.BasicAuthUriForCreds(secure: false, userName: Username, password: Password); Uri redirectUri = Configuration.Http.RedirectUriForCreds( secure: false, statusCode: statusCode, userName: Username, password: Password); _output.WriteLine(uri.AbsoluteUri); _output.WriteLine(redirectUri.AbsoluteUri); var credentialCache = new CredentialCache(); credentialCache.Add(uri, "Basic", _credential); HttpClientHandler handler = CreateHttpClientHandler(); if (PlatformDetection.IsUap) { // UAP does not support CredentialCache for Credentials. Assert.Throws<PlatformNotSupportedException>(() => handler.Credentials = credentialCache); } else { handler.Credentials = credentialCache; using (var client = new HttpClient(handler)) { using (HttpResponseMessage response = await client.GetAsync(redirectUri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(uri, response.RequestMessage.RequestUri); } } } } [OuterLoop] // TODO: Issue #11345 [SkipOnTargetFramework(TargetFrameworkMonikers.Uap)] [Theory] [MemberData(nameof(HeaderWithEmptyValueAndUris))] public async Task GetAsync_RequestHeadersAddCustomHeaders_HeaderAndEmptyValueSent(string name, string value, Uri uri) { if (IsWinHttpHandler && !PlatformDetection.IsWindows10Version1709OrGreater) { return; } using (HttpClient client = CreateHttpClient()) { _output.WriteLine($"name={name}, value={value}"); client.DefaultRequestHeaders.Add(name, value); using (HttpResponseMessage httpResponse = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode); string responseText = await httpResponse.Content.ReadAsStringAsync(); _output.WriteLine(responseText); Assert.True(TestHelper.JsonMessageContainsKeyValue(responseText, name, value)); } } } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(HeaderValueAndUris))] public async Task GetAsync_RequestHeadersAddCustomHeaders_HeaderAndValueSent(string name, string value, Uri uri) { using (HttpClient client = CreateHttpClient()) { _output.WriteLine($"name={name}, value={value}"); client.DefaultRequestHeaders.Add(name, value); using (HttpResponseMessage httpResponse = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode); string responseText = await httpResponse.Content.ReadAsStringAsync(); _output.WriteLine(responseText); Assert.True(TestHelper.JsonMessageContainsKeyValue(responseText, name, value)); } } } [Theory] [InlineData(":")] [InlineData("\x1234: \x5678")] [InlineData("nocolon")] [InlineData("no colon")] [InlineData("Content-Length ")] public async Task GetAsync_InvalidHeaderNameValue_ThrowsHttpRequestException(string invalidHeader) { if (IsCurlHandler && invalidHeader.Contains(':')) { // Issue #27172 // CurlHandler allows these headers as long as they have a colon. return; } await LoopbackServer.CreateClientAndServerAsync(async uri => { using (var client = CreateHttpClient()) { await Assert.ThrowsAsync<HttpRequestException>(() => client.GetStringAsync(uri)); } }, server => server.AcceptConnectionSendCustomResponseAndCloseAsync($"HTTP/1.1 200 OK\r\n{invalidHeader}\r\nContent-Length: 11\r\n\r\nhello world")); } [Fact] public async Task PostAsync_ManyDifferentRequestHeaders_SentCorrectly() { if (IsWinHttpHandler) { // Issue #27171 // Fails consistently with: // System.InvalidCastException: "Unable to cast object of type 'System.Object[]' to type 'System.Net.Http.WinHttpRequestState'" // This appears to be due to adding the Expect: 100-continue header, which causes winhttp // to fail with a "The parameter is incorrect" error, which in turn causes the request to // be torn down, and in doing so, we this this during disposal of the SafeWinHttpHandle. return; } // Using examples from https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Request_fields // Exercises all exposed request.Headers and request.Content.Headers strongly-typed properties await LoopbackServer.CreateClientAndServerAsync(async uri => { using (var client = CreateHttpClient()) { byte[] contentArray = Encoding.ASCII.GetBytes("hello world"); var request = new HttpRequestMessage(HttpMethod.Post, uri) { Content = new ByteArrayContent(contentArray) }; request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain")); request.Headers.AcceptCharset.Add(new StringWithQualityHeaderValue("utf-8")); request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip")); request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("deflate")); request.Headers.AcceptLanguage.Add(new StringWithQualityHeaderValue("en-US")); request.Headers.Add("Accept-Datetime", "Thu, 31 May 2007 20:35:00 GMT"); request.Headers.Add("Access-Control-Request-Method", "GET"); request.Headers.Add("Access-Control-Request-Headers", "GET"); request.Headers.Authorization = new AuthenticationHeaderValue("Basic", "QWxhZGRpbjpvcGVuIHNlc2FtZQ=="); request.Headers.CacheControl = new CacheControlHeaderValue() { NoCache = true }; request.Headers.Connection.Add("close"); request.Headers.Add("Cookie", "$Version=1; Skin=new"); request.Content.Headers.ContentLength = contentArray.Length; request.Content.Headers.ContentMD5 = MD5.Create().ComputeHash(contentArray); request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); request.Headers.Date = DateTimeOffset.Parse("Tue, 15 Nov 1994 08:12:31 GMT"); request.Headers.Expect.Add(new NameValueWithParametersHeaderValue("100-continue")); request.Headers.Add("Forwarded", "for=192.0.2.60;proto=http;by=203.0.113.43"); request.Headers.Add("From", "User Name <user@example.com>"); request.Headers.Host = "en.wikipedia.org:8080"; request.Headers.IfMatch.Add(new EntityTagHeaderValue("\"37060cd8c284d8af7ad3082f209582d\"")); request.Headers.IfModifiedSince = DateTimeOffset.Parse("Sat, 29 Oct 1994 19:43:31 GMT"); request.Headers.IfNoneMatch.Add(new EntityTagHeaderValue("\"737060cd8c284d8af7ad3082f209582d\"")); request.Headers.IfRange = new RangeConditionHeaderValue(DateTimeOffset.Parse("Wed, 21 Oct 2015 07:28:00 GMT")); request.Headers.IfUnmodifiedSince = DateTimeOffset.Parse("Sat, 29 Oct 1994 19:43:31 GMT"); request.Headers.MaxForwards = 10; request.Headers.Add("Origin", "http://www.example-social-network.com"); request.Headers.Pragma.Add(new NameValueHeaderValue("no-cache")); request.Headers.ProxyAuthorization = new AuthenticationHeaderValue("Basic", "QWxhZGRpbjpvcGVuIHNlc2FtZQ=="); request.Headers.Range = new RangeHeaderValue(500, 999); request.Headers.Referrer = new Uri("http://en.wikipedia.org/wiki/Main_Page"); request.Headers.TE.Add(new TransferCodingWithQualityHeaderValue("trailers")); request.Headers.TE.Add(new TransferCodingWithQualityHeaderValue("deflate")); request.Headers.Trailer.Add("MyTrailer"); request.Headers.TransferEncoding.Add(new TransferCodingHeaderValue("chunked")); request.Headers.UserAgent.Add(new ProductInfoHeaderValue(new ProductHeaderValue("Mozilla", "5.0"))); request.Headers.Upgrade.Add(new ProductHeaderValue("HTTPS", "1.3")); request.Headers.Upgrade.Add(new ProductHeaderValue("IRC", "6.9")); request.Headers.Upgrade.Add(new ProductHeaderValue("RTA", "x11")); request.Headers.Upgrade.Add(new ProductHeaderValue("websocket")); request.Headers.Via.Add(new ViaHeaderValue("1.0", "fred")); request.Headers.Via.Add(new ViaHeaderValue("1.1", "example.com", null, "(Apache/1.1)")); request.Headers.Warning.Add(new WarningHeaderValue(199, "-", "\"Miscellaneous warning\"")); request.Headers.Add("X-Requested-With", "XMLHttpRequest"); request.Headers.Add("DNT", "1 (Do Not Track Enabled)"); request.Headers.Add("X-Forwarded-For", "client1"); request.Headers.Add("X-Forwarded-For", "proxy1"); request.Headers.Add("X-Forwarded-For", "proxy2"); request.Headers.Add("X-Forwarded-Host", "en.wikipedia.org:8080"); request.Headers.Add("X-Forwarded-Proto", "https"); request.Headers.Add("Front-End-Https", "https"); request.Headers.Add("X-Http-Method-Override", "DELETE"); request.Headers.Add("X-ATT-DeviceId", "GT-P7320/P7320XXLPG"); request.Headers.Add("X-Wap-Profile", "http://wap.samsungmobile.com/uaprof/SGH-I777.xml"); request.Headers.Add("Proxy-Connection", "keep-alive"); request.Headers.Add("X-UIDH", "..."); request.Headers.Add("X-Csrf-Token", "i8XNjC4b8KVok4uw5RftR38Wgp2BFwql"); request.Headers.Add("X-Request-ID", "f058ebd6-02f7-4d3f-942e-904344e8cde5"); request.Headers.Add("X-Request-ID", "f058ebd6-02f7-4d3f-942e-904344e8cde5"); (await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)).Dispose(); } }, async server => { await server.AcceptConnectionAsync(async connection => { var headersSet = new HashSet<string>(); string line; while (!string.IsNullOrEmpty(line = await connection.Reader.ReadLineAsync())) { Assert.True(headersSet.Add(line)); } await connection.Writer.WriteAsync($"HTTP/1.1 200 OK\r\nDate: {DateTimeOffset.UtcNow:R}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n"); while (await connection.Socket.ReceiveAsync(new ArraySegment<byte>(new byte[1000]), SocketFlags.None) > 0); Assert.Contains("Accept-Charset: utf-8", headersSet); Assert.Contains("Accept-Encoding: gzip, deflate", headersSet); Assert.Contains("Accept-Language: en-US", headersSet); Assert.Contains("Accept-Datetime: Thu, 31 May 2007 20:35:00 GMT", headersSet); Assert.Contains("Access-Control-Request-Method: GET", headersSet); Assert.Contains("Access-Control-Request-Headers: GET", headersSet); Assert.Contains("Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", headersSet); Assert.Contains("Cache-Control: no-cache", headersSet); Assert.Contains("Connection: close", headersSet, StringComparer.OrdinalIgnoreCase); // NetFxHandler uses "Close" vs "close" if (!IsNetfxHandler) { Assert.Contains("Cookie: $Version=1; Skin=new", headersSet); } Assert.Contains("Date: Tue, 15 Nov 1994 08:12:31 GMT", headersSet); Assert.Contains("Expect: 100-continue", headersSet); Assert.Contains("Forwarded: for=192.0.2.60;proto=http;by=203.0.113.43", headersSet); Assert.Contains("From: User Name <user@example.com>", headersSet); Assert.Contains("Host: en.wikipedia.org:8080", headersSet); Assert.Contains("If-Match: \"37060cd8c284d8af7ad3082f209582d\"", headersSet); Assert.Contains("If-Modified-Since: Sat, 29 Oct 1994 19:43:31 GMT", headersSet); Assert.Contains("If-None-Match: \"737060cd8c284d8af7ad3082f209582d\"", headersSet); Assert.Contains("If-Range: Wed, 21 Oct 2015 07:28:00 GMT", headersSet); Assert.Contains("If-Unmodified-Since: Sat, 29 Oct 1994 19:43:31 GMT", headersSet); Assert.Contains("Max-Forwards: 10", headersSet); Assert.Contains("Origin: http://www.example-social-network.com", headersSet); Assert.Contains("Pragma: no-cache", headersSet); Assert.Contains("Proxy-Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", headersSet); Assert.Contains("Range: bytes=500-999", headersSet); Assert.Contains("Referer: http://en.wikipedia.org/wiki/Main_Page", headersSet); Assert.Contains("TE: trailers, deflate", headersSet); Assert.Contains("Trailer: MyTrailer", headersSet); Assert.Contains("Transfer-Encoding: chunked", headersSet); Assert.Contains("User-Agent: Mozilla/5.0", headersSet); Assert.Contains("Upgrade: HTTPS/1.3, IRC/6.9, RTA/x11, websocket", headersSet); Assert.Contains("Via: 1.0 fred, 1.1 example.com (Apache/1.1)", headersSet); Assert.Contains("Warning: 199 - \"Miscellaneous warning\"", headersSet); Assert.Contains("X-Requested-With: XMLHttpRequest", headersSet); Assert.Contains("DNT: 1 (Do Not Track Enabled)", headersSet); Assert.Contains("X-Forwarded-For: client1, proxy1, proxy2", headersSet); Assert.Contains("X-Forwarded-Host: en.wikipedia.org:8080", headersSet); Assert.Contains("X-Forwarded-Proto: https", headersSet); Assert.Contains("Front-End-Https: https", headersSet); Assert.Contains("X-Http-Method-Override: DELETE", headersSet); Assert.Contains("X-ATT-DeviceId: GT-P7320/P7320XXLPG", headersSet); Assert.Contains("X-Wap-Profile: http://wap.samsungmobile.com/uaprof/SGH-I777.xml", headersSet); if (!IsNetfxHandler) { Assert.Contains("Proxy-Connection: keep-alive", headersSet); } Assert.Contains("X-UIDH: ...", headersSet); Assert.Contains("X-Csrf-Token: i8XNjC4b8KVok4uw5RftR38Wgp2BFwql", headersSet); Assert.Contains("X-Request-ID: f058ebd6-02f7-4d3f-942e-904344e8cde5, f058ebd6-02f7-4d3f-942e-904344e8cde5", headersSet); }); }); } public static IEnumerable<object[]> GetAsync_ManyDifferentResponseHeaders_ParsedCorrectly_MemberData() => from newline in new[] { "\n", "\r\n" } from fold in new[] { "", newline + " ", newline + "\t", newline + " " } from dribble in new[] { false, true } select new object[] { newline, fold, dribble }; [Theory] [MemberData(nameof(GetAsync_ManyDifferentResponseHeaders_ParsedCorrectly_MemberData))] public async Task GetAsync_ManyDifferentResponseHeaders_ParsedCorrectly(string newline, string fold, bool dribble) { if (IsCurlHandler && !string.IsNullOrEmpty(fold)) { // CurlHandler doesn't currently support folded headers. return; } if (IsNetfxHandler && newline == "\n") { // NetFxHandler doesn't allow LF-only line endings. return; } // Using examples from https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Response_fields // Exercises all exposed response.Headers and response.Content.Headers strongly-typed properties await LoopbackServer.CreateClientAndServerAsync(async uri => { using (var client = CreateHttpClient()) using (HttpResponseMessage resp = await client.GetAsync(uri)) { Assert.Equal("1.1", resp.Version.ToString()); Assert.Equal(HttpStatusCode.OK, resp.StatusCode); Assert.Contains("*", resp.Headers.GetValues("Access-Control-Allow-Origin")); Assert.Contains("text/example;charset=utf-8", resp.Headers.GetValues("Accept-Patch")); Assert.Contains("bytes", resp.Headers.AcceptRanges); Assert.Equal(TimeSpan.FromSeconds(12), resp.Headers.Age.GetValueOrDefault()); Assert.Contains("GET", resp.Content.Headers.Allow); Assert.Contains("HEAD", resp.Content.Headers.Allow); Assert.Contains("http/1.1=\"http2.example.com:8001\"; ma=7200", resp.Headers.GetValues("Alt-Svc")); Assert.Equal(TimeSpan.FromSeconds(3600), resp.Headers.CacheControl.MaxAge.GetValueOrDefault()); Assert.Contains("close", resp.Headers.Connection); Assert.True(resp.Headers.ConnectionClose.GetValueOrDefault()); Assert.Equal("attachment", resp.Content.Headers.ContentDisposition.DispositionType); Assert.Equal("\"fname.ext\"", resp.Content.Headers.ContentDisposition.FileName); Assert.Contains("gzip", resp.Content.Headers.ContentEncoding); Assert.Contains("da", resp.Content.Headers.ContentLanguage); Assert.Equal(new Uri("/index.htm", UriKind.Relative), resp.Content.Headers.ContentLocation); Assert.Equal(Convert.FromBase64String("Q2hlY2sgSW50ZWdyaXR5IQ=="), resp.Content.Headers.ContentMD5); Assert.Equal("bytes", resp.Content.Headers.ContentRange.Unit); Assert.Equal(21010, resp.Content.Headers.ContentRange.From.GetValueOrDefault()); Assert.Equal(47021, resp.Content.Headers.ContentRange.To.GetValueOrDefault()); Assert.Equal(47022, resp.Content.Headers.ContentRange.Length.GetValueOrDefault()); Assert.Equal("text/html", resp.Content.Headers.ContentType.MediaType); Assert.Equal("utf-8", resp.Content.Headers.ContentType.CharSet); Assert.Equal(DateTimeOffset.Parse("Tue, 15 Nov 1994 08:12:31 GMT"), resp.Headers.Date.GetValueOrDefault()); Assert.Equal("\"737060cd8c284d8af7ad3082f209582d\"", resp.Headers.ETag.Tag); Assert.Equal(DateTimeOffset.Parse("Thu, 01 Dec 1994 16:00:00 GMT"), resp.Content.Headers.Expires.GetValueOrDefault()); Assert.Equal(DateTimeOffset.Parse("Tue, 15 Nov 1994 12:45:26 GMT"), resp.Content.Headers.LastModified.GetValueOrDefault()); Assert.Contains("</feed>; rel=\"alternate\"", resp.Headers.GetValues("Link")); Assert.Equal(new Uri("http://www.w3.org/pub/WWW/People.html"), resp.Headers.Location); Assert.Contains("CP=\"This is not a P3P policy!\"", resp.Headers.GetValues("P3P")); Assert.Contains(new NameValueHeaderValue("no-cache"), resp.Headers.Pragma); Assert.Contains(new AuthenticationHeaderValue("basic"), resp.Headers.ProxyAuthenticate); Assert.Contains("max-age=2592000; pin-sha256=\"E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=\"", resp.Headers.GetValues("Public-Key-Pins")); Assert.Equal(TimeSpan.FromSeconds(120), resp.Headers.RetryAfter.Delta.GetValueOrDefault()); Assert.Contains(new ProductInfoHeaderValue("Apache", "2.4.1"), resp.Headers.Server); Assert.Contains("UserID=JohnDoe; Max-Age=3600; Version=1", resp.Headers.GetValues("Set-Cookie")); Assert.Contains("max-age=16070400; includeSubDomains", resp.Headers.GetValues("Strict-Transport-Security")); Assert.Contains("Max-Forwards", resp.Headers.Trailer); Assert.Contains("?", resp.Headers.GetValues("Tk")); Assert.Contains(new ProductHeaderValue("HTTPS", "1.3"), resp.Headers.Upgrade); Assert.Contains(new ProductHeaderValue("IRC", "6.9"), resp.Headers.Upgrade); Assert.Contains(new ProductHeaderValue("websocket"), resp.Headers.Upgrade); Assert.Contains("Accept-Language", resp.Headers.Vary); Assert.Contains(new ViaHeaderValue("1.0", "fred"), resp.Headers.Via); Assert.Contains(new ViaHeaderValue("1.1", "example.com", null, "(Apache/1.1)"), resp.Headers.Via); Assert.Contains(new WarningHeaderValue(199, "-", "\"Miscellaneous warning\"", DateTimeOffset.Parse("Wed, 21 Oct 2015 07:28:00 GMT")), resp.Headers.Warning); Assert.Contains(new AuthenticationHeaderValue("Basic"), resp.Headers.WwwAuthenticate); Assert.Contains("deny", resp.Headers.GetValues("X-Frame-Options")); Assert.Contains("default-src 'self'", resp.Headers.GetValues("X-WebKit-CSP")); Assert.Contains("5; url=http://www.w3.org/pub/WWW/People.html", resp.Headers.GetValues("Refresh")); Assert.Contains("200 OK", resp.Headers.GetValues("Status")); Assert.Contains("<origin>[, <origin>]*", resp.Headers.GetValues("Timing-Allow-Origin")); Assert.Contains("42.666", resp.Headers.GetValues("X-Content-Duration")); Assert.Contains("nosniff", resp.Headers.GetValues("X-Content-Type-Options")); Assert.Contains("PHP/5.4.0", resp.Headers.GetValues("X-Powered-By")); Assert.Contains("f058ebd6-02f7-4d3f-942e-904344e8cde5", resp.Headers.GetValues("X-Request-ID")); Assert.Contains("IE=EmulateIE7", resp.Headers.GetValues("X-UA-Compatible")); Assert.Contains("1; mode=block", resp.Headers.GetValues("X-XSS-Protection")); } }, server => server.AcceptConnectionSendCustomResponseAndCloseAsync( $"HTTP/1.1 200 OK{newline}" + $"Access-Control-Allow-Origin:{fold} *{newline}" + $"Accept-Patch:{fold} text/example;charset=utf-8{newline}" + $"Accept-Ranges:{fold} bytes{newline}" + $"Age: {fold}12{newline}" + $"Allow: {fold}GET, HEAD{newline}" + $"Alt-Svc:{fold} http/1.1=\"http2.example.com:8001\"; ma=7200{newline}" + $"Cache-Control: {fold}max-age=3600{newline}" + $"Connection:{fold} close{newline}" + $"Content-Disposition: {fold}attachment;{fold} filename=\"fname.ext\"{newline}" + $"Content-Encoding: {fold}gzip{newline}" + $"Content-Language:{fold} da{newline}" + $"Content-Location: {fold}/index.htm{newline}" + $"Content-MD5:{fold} Q2hlY2sgSW50ZWdyaXR5IQ=={newline}" + $"Content-Range: {fold}bytes {fold}21010-47021/47022{newline}" + $"Content-Type: text/html;{fold} charset=utf-8{newline}" + $"Date: Tue, 15 Nov 1994{fold} 08:12:31 GMT{newline}" + $"ETag: {fold}\"737060cd8c284d8af7ad3082f209582d\"{newline}" + $"Expires: Thu,{fold} 01 Dec 1994 16:00:00 GMT{newline}" + $"Last-Modified:{fold} Tue, 15 Nov 1994 12:45:26 GMT{newline}" + $"Link:{fold} </feed>; rel=\"alternate\"{newline}" + $"Location:{fold} http://www.w3.org/pub/WWW/People.html{newline}" + $"P3P: {fold}CP=\"This is not a P3P policy!\"{newline}" + $"Pragma: {fold}no-cache{newline}" + $"Proxy-Authenticate:{fold} Basic{newline}" + $"Public-Key-Pins:{fold} max-age=2592000; pin-sha256=\"E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=\"{newline}" + $"Retry-After: {fold}120{newline}" + $"Server: {fold}Apache/2.4.1{fold} (Unix){newline}" + $"Set-Cookie: {fold}UserID=JohnDoe; Max-Age=3600; Version=1{newline}" + $"Strict-Transport-Security: {fold}max-age=16070400; includeSubDomains{newline}" + $"Trailer: {fold}Max-Forwards{newline}" + $"Tk: {fold}?{newline}" + $"Upgrade: HTTPS/1.3,{fold} IRC/6.9,{fold} RTA/x11, {fold}websocket{newline}" + $"Vary:{fold} Accept-Language{newline}" + $"Via:{fold} 1.0 fred, 1.1 example.com{fold} (Apache/1.1){newline}" + $"Warning:{fold} 199 - \"Miscellaneous warning\" \"Wed, 21 Oct 2015 07:28:00 GMT\"{newline}" + $"WWW-Authenticate: {fold}Basic{newline}" + $"X-Frame-Options: {fold}deny{newline}" + $"X-WebKit-CSP: default-src 'self'{newline}" + $"Refresh: {fold}5; url=http://www.w3.org/pub/WWW/People.html{newline}" + $"Status: {fold}200 OK{newline}" + $"Timing-Allow-Origin: {fold}<origin>[, <origin>]*{newline}" + $"Upgrade-Insecure-Requests:{fold} 1{newline}" + $"X-Content-Duration:{fold} 42.666{newline}" + $"X-Content-Type-Options: {fold}nosniff{newline}" + $"X-Powered-By: {fold}PHP/5.4.0{newline}" + $"X-Request-ID:{fold} f058ebd6-02f7-4d3f-942e-904344e8cde5{newline}" + $"X-UA-Compatible: {fold}IE=EmulateIE7{newline}" + $"X-XSS-Protection:{fold} 1; mode=block{newline}" + $"{newline}"), dribble ? new LoopbackServer.Options { StreamWrapper = s => new DribbleStream(s) } : null); } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(false)] [InlineData(true)] public async Task GetAsync_TrailingHeaders_Ignored(bool includeTrailerHeader) { if (IsCurlHandler) { // ActiveIssue #17174: CurlHandler has a problem here // https://github.com/curl/curl/issues/1354 return; } await LoopbackServer.CreateServerAsync(async (server, url) => { using (HttpClientHandler handler = CreateHttpClientHandler()) using (var client = new HttpClient(handler)) { Task<HttpResponseMessage> getResponseTask = client.GetAsync(url); await TestHelper.WhenAllCompletedOrAnyFailed( getResponseTask, server.AcceptConnectionSendCustomResponseAndCloseAsync( "HTTP/1.1 200 OK\r\n" + "Transfer-Encoding: chunked\r\n" + (includeTrailerHeader ? "Trailer: MyCoolTrailerHeader\r\n" : "") + "\r\n" + "4\r\n" + "data\r\n" + "0\r\n" + "MyCoolTrailerHeader: amazingtrailer\r\n" + "\r\n")); using (HttpResponseMessage response = await getResponseTask) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); if (includeTrailerHeader) { Assert.Contains("MyCoolTrailerHeader", response.Headers.GetValues("Trailer")); } Assert.False(response.Headers.Contains("MyCoolTrailerHeader"), "Trailer should have been ignored"); string data = await response.Content.ReadAsStringAsync(); Assert.Contains("data", data); Assert.DoesNotContain("MyCoolTrailerHeader", data); Assert.DoesNotContain("amazingtrailer", data); } } }); } [OuterLoop] // TODO: Issue #11345 [Fact] public async Task GetAsync_NonTraditionalChunkSizes_Accepted() { await LoopbackServer.CreateServerAsync(async (server, url) => { using (HttpClientHandler handler = CreateHttpClientHandler()) using (var client = new HttpClient(handler)) { Task<HttpResponseMessage> getResponseTask = client.GetAsync(url); await TestHelper.WhenAllCompletedOrAnyFailed( getResponseTask, server.AcceptConnectionSendCustomResponseAndCloseAsync( "HTTP/1.1 200 OK\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + "4 \r\n" + // whitespace after size "data\r\n" + "5;somekey=somevalue\r\n" + // chunk extension "hello\r\n" + "7\t ;chunkextension\r\n" + // tabs/spaces then chunk extension "netcore\r\n" + "0\r\n" + "\r\n")); using (HttpResponseMessage response = await getResponseTask) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string data = await response.Content.ReadAsStringAsync(); Assert.Contains("data", data); Assert.Contains("hello", data); Assert.Contains("netcore", data); Assert.DoesNotContain("somekey", data); Assert.DoesNotContain("somevalue", data); Assert.DoesNotContain("chunkextension", data); } } }); } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData("")] // missing size [InlineData(" ")] // missing size [InlineData("10000000000000000")] // overflowing size [InlineData("xyz")] // non-hex [InlineData("7gibberish")] // valid size then gibberish [InlineData("7\v\f")] // unacceptable whitespace public async Task GetAsync_InvalidChunkSize_ThrowsHttpRequestException(string chunkSize) { if (IsCurlHandler) { // libcurl allows any arbitrary characters after the hex value return; } await LoopbackServer.CreateServerAsync(async (server, url) => { using (HttpClient client = CreateHttpClient()) { string partialResponse = "HTTP/1.1 200 OK\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + $"{chunkSize}\r\n"; var tcs = new TaskCompletionSource<bool>(); Task serverTask = server.AcceptConnectionAsync(async connection => { await connection.ReadRequestHeaderAndSendCustomResponseAsync(partialResponse); await tcs.Task; }); await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url)); tcs.SetResult(true); await serverTask; } }); } [Fact] public async Task GetAsync_InvalidChunkTerminator_ThrowsHttpRequestException() { await LoopbackServer.CreateClientAndServerAsync(async url => { using (HttpClient client = CreateHttpClient()) { await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url)); } }, server => server.AcceptConnectionSendCustomResponseAndCloseAsync( "HTTP/1.1 200 OK\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + "5\r\n" + "hello" + // missing \r\n terminator //"5\r\n" + //"world" + // missing \r\n terminator "0\r\n" + "\r\n")); } [OuterLoop] // TODO: Issue #11345 [Fact] public async Task GetAsync_InfiniteChunkSize_ThrowsHttpRequestException() { await LoopbackServer.CreateServerAsync(async (server, url) => { using (HttpClient client = CreateHttpClient()) { client.Timeout = Timeout.InfiniteTimeSpan; var cts = new CancellationTokenSource(); var tcs = new TaskCompletionSource<bool>(); Task serverTask = server.AcceptConnectionAsync(async connection => { await connection.ReadRequestHeaderAndSendCustomResponseAsync("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n"); TextWriter writer = connection.Writer; try { while (!cts.IsCancellationRequested) // infinite to make sure implementation doesn't OOM { await writer.WriteAsync(new string(' ', 10000)); await Task.Delay(1); } } catch { } }); await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url)); cts.Cancel(); await serverTask; } }); } [Fact] public async Task SendAsync_TransferEncodingSetButNoRequestContent_Throws() { if (IsNetfxHandler) { // no exception thrown return; } var req = new HttpRequestMessage(HttpMethod.Post, "http://bing.com"); req.Headers.TransferEncodingChunked = true; using (HttpClient c = CreateHttpClient()) { HttpRequestException error = await Assert.ThrowsAsync<HttpRequestException>(() => c.SendAsync(req)); Assert.IsType<InvalidOperationException>(error.InnerException); } } [OuterLoop] // TODO: Issue #11345 [Fact] public async Task GetAsync_ResponseHeadersRead_ReadFromEachIterativelyDoesntDeadlock() { using (HttpClient client = CreateHttpClient()) { const int NumGets = 5; Task<HttpResponseMessage>[] responseTasks = (from _ in Enumerable.Range(0, NumGets) select client.GetAsync(Configuration.Http.RemoteEchoServer, HttpCompletionOption.ResponseHeadersRead)).ToArray(); for (int i = responseTasks.Length - 1; i >= 0; i--) // read backwards to increase likelihood that we wait on a different task than has data available { using (HttpResponseMessage response = await responseTasks[i]) { string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, null); } } } } [OuterLoop] // TODO: Issue #11345 [Fact] public async Task SendAsync_HttpRequestMsgResponseHeadersRead_StatusCodeOK() { HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, Configuration.Http.SecureRemoteEchoServer); using (HttpClient client = CreateHttpClient()) { using (HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)) { string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, null); } } } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "netfx's ConnectStream.ReadAsync tries to read beyond data already buffered, causing hangs #18864")] [OuterLoop] // TODO: Issue #11345 [Fact] public async Task SendAsync_ReadFromSlowStreamingServer_PartialDataReturned() { await LoopbackServer.CreateServerAsync(async (server, url) => { using (HttpClient client = CreateHttpClient()) { Task<HttpResponseMessage> getResponse = client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead); await server.AcceptConnectionAsync(async connection => { await connection.ReadRequestHeaderAndSendCustomResponseAsync( "HTTP/1.1 200 OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + "Content-Length: 16000\r\n" + "\r\n" + "less than 16000 bytes"); using (HttpResponseMessage response = await getResponse) { var buffer = new byte[8000]; using (Stream clientStream = await response.Content.ReadAsStreamAsync()) { int bytesRead = await clientStream.ReadAsync(buffer, 0, buffer.Length); _output.WriteLine($"Bytes read from stream: {bytesRead}"); Assert.True(bytesRead < buffer.Length, "bytesRead should be less than buffer.Length"); } } }); } }); } [Theory] [InlineData(true)] [InlineData(false)] [InlineData(null)] public async Task ReadAsStreamAsync_HandlerProducesWellBehavedResponseStream(bool? chunked) { await LoopbackServer.CreateClientAndServerAsync(async uri => { var request = new HttpRequestMessage(HttpMethod.Get, uri); using (var client = new HttpMessageInvoker(CreateHttpClientHandler())) using (HttpResponseMessage response = await client.SendAsync(request, CancellationToken.None)) { using (Stream responseStream = await response.Content.ReadAsStreamAsync()) { Assert.Same(responseStream, await response.Content.ReadAsStreamAsync()); // Boolean properties returning correct values Assert.True(responseStream.CanRead); Assert.False(responseStream.CanWrite); Assert.False(responseStream.CanSeek); // Not supported operations Assert.Throws<NotSupportedException>(() => responseStream.BeginWrite(new byte[1], 0, 1, null, null)); Assert.Throws<NotSupportedException>(() => responseStream.Length); Assert.Throws<NotSupportedException>(() => responseStream.Position); Assert.Throws<NotSupportedException>(() => responseStream.Position = 0); Assert.Throws<NotSupportedException>(() => responseStream.Seek(0, SeekOrigin.Begin)); Assert.Throws<NotSupportedException>(() => responseStream.SetLength(0)); Assert.Throws<NotSupportedException>(() => responseStream.Write(new byte[1], 0, 1)); Assert.Throws<NotSupportedException>(() => responseStream.Write(new Span<byte>(new byte[1]))); Assert.Throws<NotSupportedException>(() => { responseStream.WriteAsync(new Memory<byte>(new byte[1])); }); Assert.Throws<NotSupportedException>(() => { responseStream.WriteAsync(new byte[1], 0, 1); }); Assert.Throws<NotSupportedException>(() => responseStream.WriteByte(1)); // Invalid arguments var nonWritableStream = new MemoryStream(new byte[1], false); var disposedStream = new MemoryStream(); disposedStream.Dispose(); Assert.Throws<ArgumentNullException>(() => responseStream.CopyTo(null)); Assert.Throws<ArgumentOutOfRangeException>(() => responseStream.CopyTo(Stream.Null, 0)); Assert.Throws<ArgumentNullException>(() => { responseStream.CopyToAsync(null, 100, default); }); Assert.Throws<ArgumentOutOfRangeException>(() => { responseStream.CopyToAsync(Stream.Null, 0, default); }); Assert.Throws<ArgumentOutOfRangeException>(() => { responseStream.CopyToAsync(Stream.Null, -1, default); }); Assert.Throws<NotSupportedException>(() => { responseStream.CopyToAsync(nonWritableStream, 100, default); }); Assert.Throws<ObjectDisposedException>(() => { responseStream.CopyToAsync(disposedStream, 100, default); }); Assert.Throws<ArgumentNullException>(() => responseStream.Read(null, 0, 100)); Assert.Throws<ArgumentOutOfRangeException>(() => responseStream.Read(new byte[1], -1, 1)); Assert.ThrowsAny<ArgumentException>(() => responseStream.Read(new byte[1], 2, 1)); Assert.Throws<ArgumentOutOfRangeException>(() => responseStream.Read(new byte[1], 0, -1)); Assert.ThrowsAny<ArgumentException>(() => responseStream.Read(new byte[1], 0, 2)); Assert.Throws<ArgumentNullException>(() => responseStream.BeginRead(null, 0, 100, null, null)); Assert.Throws<ArgumentOutOfRangeException>(() => responseStream.BeginRead(new byte[1], -1, 1, null, null)); Assert.ThrowsAny<ArgumentException>(() => responseStream.BeginRead(new byte[1], 2, 1, null, null)); Assert.Throws<ArgumentOutOfRangeException>(() => responseStream.BeginRead(new byte[1], 0, -1, null, null)); Assert.ThrowsAny<ArgumentException>(() => responseStream.BeginRead(new byte[1], 0, 2, null, null)); Assert.Throws<ArgumentNullException>(() => responseStream.EndRead(null)); if (IsNetfxHandler) { // Argument exceptions on netfx are thrown out of these asynchronously rather than synchronously await Assert.ThrowsAsync<ArgumentNullException>(() => responseStream.ReadAsync(null, 0, 100, default)); await Assert.ThrowsAsync<ArgumentOutOfRangeException>(() => responseStream.ReadAsync(new byte[1], -1, 1, default)); await Assert.ThrowsAsync<ArgumentOutOfRangeException>(() => responseStream.ReadAsync(new byte[1], 2, 1, default)); await Assert.ThrowsAsync<ArgumentOutOfRangeException>(() => responseStream.ReadAsync(new byte[1], 0, -1, default)); await Assert.ThrowsAsync<ArgumentOutOfRangeException>(() => responseStream.ReadAsync(new byte[1], 0, 2, default)); } else { Assert.Throws<ArgumentNullException>(() => { responseStream.ReadAsync(null, 0, 100, default); }); Assert.Throws<ArgumentOutOfRangeException>(() => { responseStream.ReadAsync(new byte[1], -1, 1, default); }); Assert.ThrowsAny<ArgumentException>(() => { responseStream.ReadAsync(new byte[1], 2, 1, default); }); Assert.Throws<ArgumentOutOfRangeException>(() => { responseStream.ReadAsync(new byte[1], 0, -1, default); }); Assert.ThrowsAny<ArgumentException>(() => { responseStream.ReadAsync(new byte[1], 0, 2, default); }); } // Various forms of reading var buffer = new byte[1]; Assert.Equal('h', responseStream.ReadByte()); Assert.Equal(1, await Task.Factory.FromAsync(responseStream.BeginRead, responseStream.EndRead, buffer, 0, 1, null)); Assert.Equal((byte)'e', buffer[0]); Assert.Equal(1, await responseStream.ReadAsync(new Memory<byte>(buffer))); Assert.Equal((byte)'l', buffer[0]); Assert.Equal(1, await responseStream.ReadAsync(buffer, 0, 1)); Assert.Equal((byte)'l', buffer[0]); Assert.Equal(1, responseStream.Read(new Span<byte>(buffer))); Assert.Equal((byte)'o', buffer[0]); Assert.Equal(1, responseStream.Read(buffer, 0, 1)); Assert.Equal((byte)' ', buffer[0]); if (!IsNetfxHandler) { // Doing any of these 0-byte reads causes the connection to fail. Assert.Equal(0, await Task.Factory.FromAsync(responseStream.BeginRead, responseStream.EndRead, Array.Empty<byte>(), 0, 0, null)); Assert.Equal(0, await responseStream.ReadAsync(Memory<byte>.Empty)); Assert.Equal(0, await responseStream.ReadAsync(Array.Empty<byte>(), 0, 0)); Assert.Equal(0, responseStream.Read(Span<byte>.Empty)); Assert.Equal(0, responseStream.Read(Array.Empty<byte>(), 0, 0)); } // And copying var ms = new MemoryStream(); await responseStream.CopyToAsync(ms); Assert.Equal("world", Encoding.ASCII.GetString(ms.ToArray())); // Read and copy again once we've exhausted all data ms = new MemoryStream(); await responseStream.CopyToAsync(ms); responseStream.CopyTo(ms); Assert.Equal(0, ms.Length); Assert.Equal(-1, responseStream.ReadByte()); Assert.Equal(0, responseStream.Read(buffer, 0, 1)); Assert.Equal(0, responseStream.Read(new Span<byte>(buffer))); Assert.Equal(0, await responseStream.ReadAsync(buffer, 0, 1)); Assert.Equal(0, await responseStream.ReadAsync(new Memory<byte>(buffer))); Assert.Equal(0, await Task.Factory.FromAsync(responseStream.BeginRead, responseStream.EndRead, buffer, 0, 1, null)); } } }, async server => { await server.AcceptConnectionAsync(async connection => { await connection.ReadRequestHeaderAsync(); await connection.Writer.WriteAsync("HTTP/1.1 200 OK\r\n"); switch (chunked) { case true: await connection.Writer.WriteAsync("Transfer-Encoding: chunked\r\n\r\n3\r\nhel\r\n8\r\nlo world\r\n0\r\n\r\n"); break; case false: await connection.Writer.WriteAsync("Content-Length: 11\r\n\r\nhello world"); break; case null: await connection.Writer.WriteAsync("\r\nhello world"); break; } }); }); } [Fact] public async Task ReadAsStreamAsync_EmptyResponseBody_HandlerProducesWellBehavedResponseStream() { await LoopbackServer.CreateClientAndServerAsync(async uri => { using (var client = new HttpMessageInvoker(CreateHttpClientHandler())) { var request = new HttpRequestMessage(HttpMethod.Get, uri); using (HttpResponseMessage response = await client.SendAsync(request, CancellationToken.None)) using (Stream responseStream = await response.Content.ReadAsStreamAsync()) { // Boolean properties returning correct values Assert.True(responseStream.CanRead); Assert.False(responseStream.CanWrite); Assert.False(responseStream.CanSeek); // Not supported operations Assert.Throws<NotSupportedException>(() => responseStream.BeginWrite(new byte[1], 0, 1, null, null)); Assert.Throws<NotSupportedException>(() => responseStream.Length); Assert.Throws<NotSupportedException>(() => responseStream.Position); Assert.Throws<NotSupportedException>(() => responseStream.Position = 0); Assert.Throws<NotSupportedException>(() => responseStream.Seek(0, SeekOrigin.Begin)); Assert.Throws<NotSupportedException>(() => responseStream.SetLength(0)); Assert.Throws<NotSupportedException>(() => responseStream.Write(new byte[1], 0, 1)); Assert.Throws<NotSupportedException>(() => responseStream.Write(new Span<byte>(new byte[1]))); await Assert.ThrowsAsync<NotSupportedException>(async () => await responseStream.WriteAsync(new Memory<byte>(new byte[1]))); await Assert.ThrowsAsync<NotSupportedException>(async () => await responseStream.WriteAsync(new byte[1], 0, 1)); Assert.Throws<NotSupportedException>(() => responseStream.WriteByte(1)); // Invalid arguments var nonWritableStream = new MemoryStream(new byte[1], false); var disposedStream = new MemoryStream(); disposedStream.Dispose(); Assert.Throws<ArgumentNullException>(() => responseStream.CopyTo(null)); Assert.Throws<ArgumentOutOfRangeException>(() => responseStream.CopyTo(Stream.Null, 0)); Assert.Throws<ArgumentNullException>(() => { responseStream.CopyToAsync(null, 100, default); }); Assert.Throws<ArgumentOutOfRangeException>(() => { responseStream.CopyToAsync(Stream.Null, 0, default); }); Assert.Throws<ArgumentOutOfRangeException>(() => { responseStream.CopyToAsync(Stream.Null, -1, default); }); Assert.Throws<NotSupportedException>(() => { responseStream.CopyToAsync(nonWritableStream, 100, default); }); Assert.Throws<ObjectDisposedException>(() => { responseStream.CopyToAsync(disposedStream, 100, default); }); Assert.Throws<ArgumentNullException>(() => responseStream.Read(null, 0, 100)); Assert.Throws<ArgumentOutOfRangeException>(() => responseStream.Read(new byte[1], -1, 1)); Assert.ThrowsAny<ArgumentException>(() => responseStream.Read(new byte[1], 2, 1)); Assert.Throws<ArgumentOutOfRangeException>(() => responseStream.Read(new byte[1], 0, -1)); Assert.ThrowsAny<ArgumentException>(() => responseStream.Read(new byte[1], 0, 2)); Assert.Throws<ArgumentNullException>(() => responseStream.BeginRead(null, 0, 100, null, null)); Assert.Throws<ArgumentOutOfRangeException>(() => responseStream.BeginRead(new byte[1], -1, 1, null, null)); Assert.ThrowsAny<ArgumentException>(() => responseStream.BeginRead(new byte[1], 2, 1, null, null)); Assert.Throws<ArgumentOutOfRangeException>(() => responseStream.BeginRead(new byte[1], 0, -1, null, null)); Assert.ThrowsAny<ArgumentException>(() => responseStream.BeginRead(new byte[1], 0, 2, null, null)); Assert.Throws<ArgumentNullException>(() => responseStream.EndRead(null)); if (!IsNetfxHandler) { // The netfx handler doesn't validate these arguments. Assert.Throws<ArgumentNullException>(() => { responseStream.CopyTo(null); }); Assert.Throws<ArgumentNullException>(() => { responseStream.CopyToAsync(null, 100, default); }); Assert.Throws<ArgumentNullException>(() => { responseStream.CopyToAsync(null, 100, default); }); Assert.Throws<ArgumentNullException>(() => { responseStream.Read(null, 0, 100); }); Assert.Throws<ArgumentNullException>(() => { responseStream.ReadAsync(null, 0, 100, default); }); Assert.Throws<ArgumentNullException>(() => { responseStream.BeginRead(null, 0, 100, null, null); }); } // Empty reads var buffer = new byte[1]; Assert.Equal(-1, responseStream.ReadByte()); Assert.Equal(0, await Task.Factory.FromAsync(responseStream.BeginRead, responseStream.EndRead, buffer, 0, 1, null)); Assert.Equal(0, await responseStream.ReadAsync(new Memory<byte>(buffer))); Assert.Equal(0, await responseStream.ReadAsync(buffer, 0, 1)); Assert.Equal(0, responseStream.Read(new Span<byte>(buffer))); Assert.Equal(0, responseStream.Read(buffer, 0, 1)); // Empty copies var ms = new MemoryStream(); await responseStream.CopyToAsync(ms); Assert.Equal(0, ms.Length); responseStream.CopyTo(ms); Assert.Equal(0, ms.Length); } } }, server => server.AcceptConnectionSendResponseAndCloseAsync()); } [OuterLoop] // TODO: Issue #11345 [Fact] public async Task Dispose_DisposingHandlerCancelsActiveOperationsWithoutResponses() { if (UseSocketsHttpHandler) { // TODO #23131: The SocketsHttpHandler isn't correctly handling disposal of the handler. // It should cause the outstanding requests to be canceled with OperationCanceledExceptions, // whereas currently it's resulting in ObjectDisposedExceptions. return; } await LoopbackServer.CreateServerAsync(async (server1, url1) => { await LoopbackServer.CreateServerAsync(async (server2, url2) => { await LoopbackServer.CreateServerAsync(async (server3, url3) => { var unblockServers = new TaskCompletionSource<bool>(TaskContinuationOptions.RunContinuationsAsynchronously); // First server connects but doesn't send any response yet Task serverTask1 = server1.AcceptConnectionAsync(async connection1 => { await unblockServers.Task; }); // Second server connects and sends some but not all headers Task serverTask2 = server2.AcceptConnectionAsync(async connection2 => { await connection2.ReadRequestHeaderAndSendCustomResponseAsync($"HTTP/1.1 200 OK\r\n"); await unblockServers.Task; }); // Third server connects and sends all headers and some but not all of the body Task serverTask3 = server3.AcceptConnectionAsync(async connection3 => { await connection3.ReadRequestHeaderAndSendCustomResponseAsync($"HTTP/1.1 200 OK\r\nDate: {DateTimeOffset.UtcNow:R}\r\nContent-Length: 20\r\n\r\n"); await connection3.Writer.WriteAsync("1234567890"); await unblockServers.Task; await connection3.Writer.WriteAsync("1234567890"); connection3.Socket.Shutdown(SocketShutdown.Send); }); // Make three requests Task<HttpResponseMessage> get1, get2; HttpResponseMessage response3; using (HttpClient client = CreateHttpClient()) { get1 = client.GetAsync(url1, HttpCompletionOption.ResponseHeadersRead); get2 = client.GetAsync(url2, HttpCompletionOption.ResponseHeadersRead); response3 = await client.GetAsync(url3, HttpCompletionOption.ResponseHeadersRead); } // Dispose the handler while requests are still outstanding // Requests 1 and 2 should be canceled as we haven't finished receiving their headers await Assert.ThrowsAsync<TaskCanceledException>(() => get1); await Assert.ThrowsAsync<TaskCanceledException>(() => get2); // Request 3 should still be active, and we should be able to receive all of the data. unblockServers.SetResult(true); using (response3) { Assert.Equal("12345678901234567890", await response3.Content.ReadAsStringAsync()); } }); }); }); } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(99)] [InlineData(1000)] public async Task GetAsync_StatusCodeOutOfRange_ExpectedException(int statusCode) { if (PlatformDetection.IsUap && statusCode == 99) { // UAP platform allows this status code due to historical reasons. return; } await LoopbackServer.CreateServerAsync(async (server, url) => { using (HttpClient client = CreateHttpClient()) { Task<HttpResponseMessage> getResponseTask = client.GetAsync(url); await server.AcceptConnectionSendCustomResponseAndCloseAsync( $"HTTP/1.1 {statusCode}\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + "\r\n"); await Assert.ThrowsAsync<HttpRequestException>(() => getResponseTask); } }); } #region Post Methods Tests [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(VerifyUploadServers))] public async Task PostAsync_CallMethodTwice_StringContent(Uri remoteServer) { using (HttpClient client = CreateHttpClient()) { string data = "Test String"; var content = new StringContent(data, Encoding.UTF8); content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(data); HttpResponseMessage response; using (response = await client.PostAsync(remoteServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } // Repeat call. content = new StringContent(data, Encoding.UTF8); content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(data); using (response = await client.PostAsync(remoteServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(VerifyUploadServers))] public async Task PostAsync_CallMethod_UnicodeStringContent(Uri remoteServer) { using (HttpClient client = CreateHttpClient()) { string data = "\ub4f1\uffc7\u4e82\u67ab4\uc6d4\ud1a0\uc694\uc77c\uffda3\u3155\uc218\uffdb"; var content = new StringContent(data, Encoding.UTF8); content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(data); using (HttpResponseMessage response = await client.PostAsync(remoteServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(VerifyUploadServersStreamsAndExpectedData))] public async Task PostAsync_CallMethod_StreamContent(Uri remoteServer, HttpContent content, byte[] expectedData) { using (HttpClient client = CreateHttpClient()) { content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(expectedData); using (HttpResponseMessage response = await client.PostAsync(remoteServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } private sealed class StreamContentWithSyncAsyncCopy : StreamContent { private readonly Stream _stream; private readonly bool _syncCopy; public StreamContentWithSyncAsyncCopy(Stream stream, bool syncCopy) : base(stream) { _stream = stream; _syncCopy = syncCopy; } protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) { if (_syncCopy) { try { _stream.CopyTo(stream, 128); // arbitrary size likely to require multiple read/writes return Task.CompletedTask; } catch (Exception exc) { return Task.FromException(exc); } } return base.SerializeToStreamAsync(stream, context); } } public static IEnumerable<object[]> VerifyUploadServersStreamsAndExpectedData { get { foreach (object[] serverArr in VerifyUploadServers) // target server foreach (bool syncCopy in new[] { true, false }) // force the content copy to happen via Read/Write or ReadAsync/WriteAsync { Uri server = (Uri)serverArr[0]; byte[] data = new byte[1234]; new Random(42).NextBytes(data); // A MemoryStream { var memStream = new MemoryStream(data, writable: false); yield return new object[] { server, new StreamContentWithSyncAsyncCopy(memStream, syncCopy: syncCopy), data }; } // A multipart content that provides its own stream from CreateContentReadStreamAsync { var mc = new MultipartContent(); mc.Add(new ByteArrayContent(data)); var memStream = new MemoryStream(); mc.CopyToAsync(memStream).GetAwaiter().GetResult(); yield return new object[] { server, mc, memStream.ToArray() }; } // A stream that provides the data synchronously and has a known length { var wrappedMemStream = new MemoryStream(data, writable: false); var syncKnownLengthStream = new DelegateStream( canReadFunc: () => wrappedMemStream.CanRead, canSeekFunc: () => wrappedMemStream.CanSeek, lengthFunc: () => wrappedMemStream.Length, positionGetFunc: () => wrappedMemStream.Position, positionSetFunc: p => wrappedMemStream.Position = p, readFunc: (buffer, offset, count) => wrappedMemStream.Read(buffer, offset, count), readAsyncFunc: (buffer, offset, count, token) => wrappedMemStream.ReadAsync(buffer, offset, count, token)); yield return new object[] { server, new StreamContentWithSyncAsyncCopy(syncKnownLengthStream, syncCopy: syncCopy), data }; } // A stream that provides the data synchronously and has an unknown length { int syncUnknownLengthStreamOffset = 0; Func<byte[], int, int, int> readFunc = (buffer, offset, count) => { int bytesRemaining = data.Length - syncUnknownLengthStreamOffset; int bytesToCopy = Math.Min(bytesRemaining, count); Array.Copy(data, syncUnknownLengthStreamOffset, buffer, offset, bytesToCopy); syncUnknownLengthStreamOffset += bytesToCopy; return bytesToCopy; }; var syncUnknownLengthStream = new DelegateStream( canReadFunc: () => true, canSeekFunc: () => false, readFunc: readFunc, readAsyncFunc: (buffer, offset, count, token) => Task.FromResult(readFunc(buffer, offset, count))); yield return new object[] { server, new StreamContentWithSyncAsyncCopy(syncUnknownLengthStream, syncCopy: syncCopy), data }; } // A stream that provides the data asynchronously { int asyncStreamOffset = 0, maxDataPerRead = 100; Func<byte[], int, int, int> readFunc = (buffer, offset, count) => { int bytesRemaining = data.Length - asyncStreamOffset; int bytesToCopy = Math.Min(bytesRemaining, Math.Min(maxDataPerRead, count)); Array.Copy(data, asyncStreamOffset, buffer, offset, bytesToCopy); asyncStreamOffset += bytesToCopy; return bytesToCopy; }; var asyncStream = new DelegateStream( canReadFunc: () => true, canSeekFunc: () => false, readFunc: readFunc, readAsyncFunc: async (buffer, offset, count, token) => { await Task.Delay(1).ConfigureAwait(false); return readFunc(buffer, offset, count); }); yield return new object[] { server, new StreamContentWithSyncAsyncCopy(asyncStream, syncCopy: syncCopy), data }; } // Providing data from a FormUrlEncodedContent's stream { var formContent = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("key", "val") }); yield return new object[] { server, formContent, Encoding.GetEncoding("iso-8859-1").GetBytes("key=val") }; } } } } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(EchoServers))] public async Task PostAsync_CallMethod_NullContent(Uri remoteServer) { using (HttpClient client = CreateHttpClient()) { using (HttpResponseMessage response = await client.PostAsync(remoteServer, null)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, string.Empty); } } } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(EchoServers))] public async Task PostAsync_CallMethod_EmptyContent(Uri remoteServer) { using (HttpClient client = CreateHttpClient()) { var content = new StringContent(string.Empty); using (HttpResponseMessage response = await client.PostAsync(remoteServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, string.Empty); } } } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(false, "1.0")] [InlineData(true, "1.0")] [InlineData(null, "1.0")] [InlineData(false, "1.1")] [InlineData(true, "1.1")] [InlineData(null, "1.1")] public async Task PostAsync_ExpectContinue_Success(bool? expectContinue, string version) { using (HttpClient client = CreateHttpClient()) { var req = new HttpRequestMessage(HttpMethod.Post, Configuration.Http.RemoteEchoServer) { Content = new StringContent("Test String", Encoding.UTF8) }; req.Headers.ExpectContinue = expectContinue; req.Version = new Version(version); using (HttpResponseMessage response = await client.SendAsync(req)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); if (UseSocketsHttpHandler) { const string ExpectedReqHeader = "\"Expect\": \"100-continue\""; if (expectContinue == true && version == "1.1") { Assert.Contains(ExpectedReqHeader, await response.Content.ReadAsStringAsync()); } else { Assert.DoesNotContain(ExpectedReqHeader, await response.Content.ReadAsStringAsync()); } } } } } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Doesn't send content for get requests")] [ActiveIssue(29802, TargetFrameworkMonikers.Uap)] [Fact] public async Task GetAsync_ExpectContinueTrue_NoContent_StillSendsHeader() { const string ExpectedContent = "Hello, expecting and continuing world."; var clientCompleted = new TaskCompletionSource<bool>(); await LoopbackServer.CreateClientAndServerAsync(async uri => { using (var client = CreateHttpClient()) { client.DefaultRequestHeaders.ExpectContinue = true; Assert.Equal(ExpectedContent, await client.GetStringAsync(uri)); clientCompleted.SetResult(true); } }, async server => { await server.AcceptConnectionAsync(async connection => { List<string> headers = await connection.ReadRequestHeaderAsync(); Assert.Contains("Expect: 100-continue", headers); await connection.Writer.WriteAsync("HTTP/1.1 100 Continue\r\n\r\n"); await connection.SendResponseAsync(content: ExpectedContent); await clientCompleted.Task; // make sure server closing the connection isn't what let the client complete }); }); } [OuterLoop] [Theory] [InlineData(false)] [InlineData(true)] public async Task PostAsync_ThrowFromContentCopy_RequestFails(bool syncFailure) { await LoopbackServer.CreateServerAsync(async (server, uri) => { Task responseTask = server.AcceptConnectionAsync(async connection => { var buffer = new byte[1000]; while (await connection.Socket.ReceiveAsync(new ArraySegment<byte>(buffer, 0, buffer.Length), SocketFlags.None) != 0); }); using (var client = CreateHttpClient()) { Exception error = new FormatException(); var content = new StreamContent(new DelegateStream( canSeekFunc: () => true, lengthFunc: () => 12345678, positionGetFunc: () => 0, canReadFunc: () => true, readAsyncFunc: (buffer, offset, count, cancellationToken) => syncFailure ? throw error : Task.Delay(1).ContinueWith<int>(_ => throw error))); if (PlatformDetection.IsUap) { HttpRequestException requestException = await Assert.ThrowsAsync<HttpRequestException>(() => client.PostAsync(uri, content)); Assert.Same(error, requestException.InnerException); } else { Assert.Same(error, await Assert.ThrowsAsync<FormatException>(() => client.PostAsync(uri, content))); } } }); } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(false)] [InlineData(true)] public async Task PostAsync_Redirect_ResultingGetFormattedCorrectly(bool secure) { const string ContentString = "This is the content string."; var content = new StringContent(ContentString); Uri redirectUri = Configuration.Http.RedirectUriForDestinationUri( secure, 302, secure ? Configuration.Http.SecureRemoteEchoServer : Configuration.Http.RemoteEchoServer, 1); using (HttpClient client = CreateHttpClient()) using (HttpResponseMessage response = await client.PostAsync(redirectUri, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseContent = await response.Content.ReadAsStringAsync(); Assert.DoesNotContain(ContentString, responseContent); Assert.DoesNotContain("Content-Length", responseContent); } } [ActiveIssue(22191, TargetFrameworkMonikers.Uap)] [OuterLoop] // takes several seconds [Fact] public async Task PostAsync_RedirectWith307_LargePayload() { await PostAsync_Redirect_LargePayload_Helper(307, true); } [OuterLoop] // takes several seconds [Fact] public async Task PostAsync_RedirectWith302_LargePayload() { await PostAsync_Redirect_LargePayload_Helper(302, false); } public async Task PostAsync_Redirect_LargePayload_Helper(int statusCode, bool expectRedirectToPost) { using (var fs = new FileStream(Path.Combine(Path.GetTempPath(), Path.GetTempFileName()), FileMode.Create, FileAccess.ReadWrite, FileShare.None, 0x1000, FileOptions.DeleteOnClose)) { string contentString = string.Join("", Enumerable.Repeat("Content", 100000)); byte[] contentBytes = Encoding.UTF32.GetBytes(contentString); fs.Write(contentBytes, 0, contentBytes.Length); fs.Flush(flushToDisk: true); fs.Position = 0; Uri redirectUri = Configuration.Http.RedirectUriForDestinationUri(false, statusCode, Configuration.Http.SecureRemoteEchoServer, 1); using (HttpClient client = CreateHttpClient()) using (HttpResponseMessage response = await client.PostAsync(redirectUri, new StreamContent(fs))) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); if (expectRedirectToPost) { Assert.InRange(response.Content.Headers.ContentLength.GetValueOrDefault(), contentBytes.Length, int.MaxValue); } } } } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(EchoServers))] // NOTE: will not work for in-box System.Net.Http.dll due to disposal of request content public async Task PostAsync_ReuseRequestContent_Success(Uri remoteServer) { const string ContentString = "This is the content string."; using (HttpClient client = CreateHttpClient()) { var content = new StringContent(ContentString); for (int i = 0; i < 2; i++) { using (HttpResponseMessage response = await client.PostAsync(remoteServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Contains(ContentString, await response.Content.ReadAsStringAsync()); } } } } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(HttpStatusCode.MethodNotAllowed, "Custom description")] [InlineData(HttpStatusCode.MethodNotAllowed, "")] public async Task GetAsync_CallMethod_ExpectedStatusLine(HttpStatusCode statusCode, string reasonPhrase) { await LoopbackServer.CreateClientAndServerAsync(async uri => { using (HttpClient client = CreateHttpClient()) using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(statusCode, response.StatusCode); Assert.Equal(reasonPhrase, response.ReasonPhrase); } }, server => server.AcceptConnectionSendCustomResponseAndCloseAsync( $"HTTP/1.1 {(int)statusCode} {reasonPhrase}\r\nContent-Length: 0\r\n\r\n")); } #endregion #region Various HTTP Method Tests [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(HttpMethods))] public async Task SendAsync_SendRequestUsingMethodToEchoServerWithNoContent_MethodCorrectlySent( string method, bool secureServer) { using (HttpClient client = CreateHttpClient()) { var request = new HttpRequestMessage( new HttpMethod(method), secureServer ? Configuration.Http.SecureRemoteEchoServer : Configuration.Http.RemoteEchoServer); if (PlatformDetection.IsUap && method == "TRACE") { HttpRequestException ex = await Assert.ThrowsAsync<HttpRequestException>(() => client.SendAsync(request)); Assert.IsType<PlatformNotSupportedException>(ex.InnerException); } else { using (HttpResponseMessage response = await client.SendAsync(request)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); TestHelper.VerifyRequestMethod(response, method); } } } } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(HttpMethodsThatAllowContent))] public async Task SendAsync_SendRequestUsingMethodToEchoServerWithContent_Success( string method, bool secureServer) { if (PlatformDetection.IsFullFramework && method == "GET") { // .NET Framework doesn't allow a content body with this HTTP verb. // It will throw a System.Net.ProtocolViolation exception. return; } using (HttpClient client = CreateHttpClient()) { var request = new HttpRequestMessage( new HttpMethod(method), secureServer ? Configuration.Http.SecureRemoteEchoServer : Configuration.Http.RemoteEchoServer); request.Content = new StringContent(ExpectedContent); using (HttpResponseMessage response = await client.SendAsync(request)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); TestHelper.VerifyRequestMethod(response, method); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); Assert.Contains($"\"Content-Length\": \"{request.Content.Headers.ContentLength.Value}\"", responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, ExpectedContent); } } } [ActiveIssue(20010, TargetFrameworkMonikers.Uap)] // Test hangs. But this test seems invalid. An HttpRequestMessage can only be sent once. [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData("12345678910", 0)] [InlineData("12345678910", 5)] public async Task SendAsync_SendSameRequestMultipleTimesDirectlyOnHandler_Success(string stringContent, int startingPosition) { using (var handler = new HttpMessageInvoker(CreateHttpClientHandler())) { byte[] byteContent = Encoding.ASCII.GetBytes(stringContent); var content = new MemoryStream(); content.Write(byteContent, 0, byteContent.Length); content.Position = startingPosition; var request = new HttpRequestMessage(HttpMethod.Post, Configuration.Http.RemoteEchoServer) { Content = new StreamContent(content) }; for (int iter = 0; iter < 2; iter++) { using (HttpResponseMessage response = await handler.SendAsync(request, CancellationToken.None)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseContent = await response.Content.ReadAsStringAsync(); Assert.Contains($"\"Content-Length\": \"{request.Content.Headers.ContentLength.Value}\"", responseContent); Assert.Contains(stringContent.Substring(startingPosition), responseContent); if (startingPosition != 0) { Assert.DoesNotContain(stringContent.Substring(0, startingPosition), responseContent); } } } } } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(HttpMethodsThatDontAllowContent))] public async Task SendAsync_SendRequestUsingNoBodyMethodToEchoServerWithContent_NoBodySent( string method, bool secureServer) { if (PlatformDetection.IsFullFramework && method == "HEAD") { // .NET Framework doesn't allow a content body with this HTTP verb. // It will throw a System.Net.ProtocolViolation exception. return; } if (PlatformDetection.IsUap && method == "TRACE") { // UAP platform doesn't allow a content body with this HTTP verb. // It will throw an exception HttpRequestException/COMException // with "The requested operation is invalid" message. return; } using (HttpClient client = CreateHttpClient()) { var request = new HttpRequestMessage( new HttpMethod(method), secureServer ? Configuration.Http.SecureRemoteEchoServer : Configuration.Http.RemoteEchoServer) { Content = new StringContent(ExpectedContent) }; using (HttpResponseMessage response = await client.SendAsync(request)) { if (method == "TRACE" && (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || UseSocketsHttpHandler)) { // .NET Framework also allows the HttpWebRequest and HttpClient APIs to send a request using 'TRACE' // verb and a request body. The usual response from a server is "400 Bad Request". // See here for more info: https://github.com/dotnet/corefx/issues/9023 Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); } else { Assert.Equal(HttpStatusCode.OK, response.StatusCode); TestHelper.VerifyRequestMethod(response, method); string responseContent = await response.Content.ReadAsStringAsync(); Assert.False(responseContent.Contains(ExpectedContent)); } } } } #endregion #region Version tests [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "UAP does not allow HTTP/1.0 requests.")] [OuterLoop] // TODO: Issue #11345 [Fact] public async Task SendAsync_RequestVersion10_ServerReceivesVersion10Request() { Version receivedRequestVersion = await SendRequestAndGetRequestVersionAsync(new Version(1, 0)); Assert.Equal(new Version(1, 0), receivedRequestVersion); } [OuterLoop] // TODO: Issue #11345 [Fact] public async Task SendAsync_RequestVersion11_ServerReceivesVersion11Request() { Version receivedRequestVersion = await SendRequestAndGetRequestVersionAsync(new Version(1, 1)); Assert.Equal(new Version(1, 1), receivedRequestVersion); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Throws exception sending request using Version(0,0)")] [OuterLoop] // TODO: Issue #11345 [Fact] public async Task SendAsync_RequestVersionNotSpecified_ServerReceivesVersion11Request() { // SocketsHttpHandler treats 0.0 as a bad version, and throws. if (UseSocketsHttpHandler) { return; } // The default value for HttpRequestMessage.Version is Version(1,1). // So, we need to set something different (0,0), to test the "unknown" version. Version receivedRequestVersion = await SendRequestAndGetRequestVersionAsync(new Version(0, 0)); Assert.Equal(new Version(1, 1), receivedRequestVersion); } [ActiveIssue(23037, TestPlatforms.AnyUnix)] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Specifying Version(2,0) throws exception on netfx")] [OuterLoop] // TODO: Issue #11345 [Theory] [MemberData(nameof(Http2Servers))] public async Task SendAsync_RequestVersion20_ResponseVersion20IfHttp2Supported(Uri server) { if (PlatformDetection.IsWindows && !PlatformDetection.IsWindows10Version1703OrGreater) { // Skip this test if running on Windows but on a release prior to Windows 10 Creators Update. _output.WriteLine("Skipping test due to Windows 10 version prior to Version 1703."); return; } if (UseSocketsHttpHandler) { // TODO #23134: SocketsHttpHandler doesn't yet support HTTP/2. return; } // We don't currently have a good way to test whether HTTP/2 is supported without // using the same mechanism we're trying to test, so for now we allow both 2.0 and 1.1 responses. var request = new HttpRequestMessage(HttpMethod.Get, server); request.Version = new Version(2, 0); using (HttpClientHandler handler = CreateHttpClientHandler()) using (var client = new HttpClient(handler, false)) { // It is generally expected that the test hosts will be trusted, so we don't register a validation // callback in the usual case. // // However, on our Debian 8 test machines, a combination of a server side TLS chain, // the client chain processor, and the distribution's CA bundle results in an incomplete/untrusted // certificate chain. See https://github.com/dotnet/corefx/issues/9244 for more details. if (PlatformDetection.IsDebian8) { // Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> handler.ServerCertificateCustomValidationCallback = (msg, cert, chain, errors) => { Assert.InRange(chain.ChainStatus.Length, 0, 1); if (chain.ChainStatus.Length > 0) { Assert.Equal(X509ChainStatusFlags.PartialChain, chain.ChainStatus[0].Status); } return true; }; } using (HttpResponseMessage response = await client.SendAsync(request)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.True( response.Version == new Version(2, 0) || response.Version == new Version(1, 1), "Response version " + response.Version); } } } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Specifying Version(2,0) throws exception on netfx")] [Fact] public async Task SendAsync_RequestVersion20_HttpNotHttps_NoUpgradeRequest() { await LoopbackServer.CreateClientAndServerAsync(async uri => { using (HttpClient client = CreateHttpClient()) { (await client.SendAsync(new HttpRequestMessage(HttpMethod.Get, uri) { Version = new Version(2, 0) })).Dispose(); } }, async server => { List<string> headers = await server.AcceptConnectionSendResponseAndCloseAsync(); Assert.All(headers, header => Assert.DoesNotContain("Upgrade", header, StringComparison.OrdinalIgnoreCase)); }); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Specifying Version(2,0) throws exception on netfx")] [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(IsWindows10Version1607OrGreater)), MemberData(nameof(Http2NoPushServers))] public async Task SendAsync_RequestVersion20_ResponseVersion20(Uri server) { if (UseSocketsHttpHandler) { // TODO #23134: SocketsHttpHandler doesn't yet support HTTP/2. return; } _output.WriteLine(server.AbsoluteUri.ToString()); var request = new HttpRequestMessage(HttpMethod.Get, server); request.Version = new Version(2, 0); HttpClientHandler handler = CreateHttpClientHandler(); using (var client = new HttpClient(handler)) { using (HttpResponseMessage response = await client.SendAsync(request)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(new Version(2, 0), response.Version); } } } private async Task<Version> SendRequestAndGetRequestVersionAsync(Version requestVersion) { Version receivedRequestVersion = null; await LoopbackServer.CreateServerAsync(async (server, url) => { var request = new HttpRequestMessage(HttpMethod.Get, url); request.Version = requestVersion; using (HttpClient client = CreateHttpClient()) { Task<HttpResponseMessage> getResponse = client.SendAsync(request); Task<List<string>> serverTask = server.AcceptConnectionSendResponseAndCloseAsync(); await TestHelper.WhenAllCompletedOrAnyFailed(getResponse, serverTask); List<string> receivedRequest = await serverTask; using (HttpResponseMessage response = await getResponse) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } string statusLine = receivedRequest[0]; if (statusLine.Contains("/1.0")) { receivedRequestVersion = new Version(1, 0); } else if (statusLine.Contains("/1.1")) { receivedRequestVersion = new Version(1, 1); } else { Assert.True(false, "Invalid HTTP request version"); } } }); return receivedRequestVersion; } #endregion #region Uri wire transmission encoding tests [OuterLoop] // TODO: Issue #11345 [Fact] public async Task SendRequest_UriPathHasReservedChars_ServerReceivedExpectedPath() { await LoopbackServer.CreateServerAsync(async (server, rootUrl) => { var uri = new Uri($"http://{rootUrl.Host}:{rootUrl.Port}/test[]"); _output.WriteLine(uri.AbsoluteUri.ToString()); var request = new HttpRequestMessage(HttpMethod.Get, uri); string statusLine = string.Empty; using (HttpClient client = CreateHttpClient()) { Task<HttpResponseMessage> getResponseTask = client.SendAsync(request); Task<List<string>> serverTask = server.AcceptConnectionSendResponseAndCloseAsync(); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); List<string> receivedRequest = await serverTask; using (HttpResponseMessage response = await getResponseTask) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.True(receivedRequest[0].Contains(uri.PathAndQuery), $"statusLine should contain {uri.PathAndQuery}"); } } }); } #endregion } }
51.304592
191
0.558374
[ "MIT" ]
chuckbeasley/corefx
src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.cs
155,299
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Mono.Cecil; using Mono.Cecil.Cil; namespace NRoles.Engine { sealed partial class MemberComposer { private MethodDefinition RoleMethod { get { return (MethodDefinition)_roleMember.Definition; } } private MethodDefinition ImplementPropertyAccessor() { if (_backingField != null) { return ImplementAutoPropertyAccessor(); } else { return ImplementMethodCallingCodeClass(); } } private MethodDefinition ImplementMethodCallingCodeClass() { return ImplementMethod(CreateCodeToCallCodeClass); } private MethodDefinition ImplementAutoPropertyAccessor() { return ImplementMethod(CreateCodeForAutoPropertyAccessor); } private MethodDefinition ImplementMethod(Action<MethodDefinition> createMethodCode) { var implementedMethod = ComposeMethod(createMethodCode); AddOverrides(implementedMethod, _overrides); return implementedMethod; } private void AddOverrides(MethodDefinition method, IEnumerable<RoleCompositionMember> overrides) { overrides.ForEach(overriddenMember => { var overrideReference = ResolveMethodReference( overriddenMember.Role, (MethodDefinition)overriddenMember.Definition, @override: true); Tracer.TraceVerbose("Overrides: {0}", overrideReference); method.Overrides.Add(overrideReference); }); } private MethodReference ResolveMethodReference(TypeReference role, MethodDefinition methodDefinition, bool @override = false) { // TODO: create class field for "new MemberResolver(Role, Module)" return new MemberResolver(role, Module).ResolveMethodReference(methodDefinition, @override); } private MethodDefinition ComposeMethod(Action<MethodDefinition> createMethodCode) { Tracer.TraceVerbose("Compose method: {0}", _name); var placeholder = ((MethodDefinition)Group.Placeholder); // TODO: create class field for "new MemberResolver(Role)" var implementedMethod = placeholder ?? new MemberResolver(Role, Module).ResolveMethodDefinition( RoleMethod, _name, _accessSpecifier); implementedMethod.Attributes |= MethodAttributes.HideBySig | // TODO: what about HideByName? //MethodAttributes.Final | // TODO? MethodAttributes.NewSlot | MethodAttributes.Virtual; implementedMethod.SemanticsAttributes = RoleMethod.SemanticsAttributes; createMethodCode(implementedMethod); if (placeholder == null) { TargetType.Methods.Add(implementedMethod); } return implementedMethod; } private void PushParameters(MethodDefinition implementedMethod) { // push all parameters on the stack var worker = implementedMethod.Body.GetILProcessor(); worker.Emit(OpCodes.Ldarg_0); // push "this" for (int paramIndex = 1; paramIndex <= implementedMethod.Parameters.Count; ++paramIndex) { var paramReference = implementedMethod.Parameters[paramIndex - 1]; Instruction paramPushInstruction; switch (paramIndex) { case 1: paramPushInstruction = worker.Create(OpCodes.Ldarg_1); break; case 2: paramPushInstruction = worker.Create(OpCodes.Ldarg_2); break; case 3: paramPushInstruction = worker.Create(OpCodes.Ldarg_3); break; default: paramPushInstruction = worker.Create(OpCodes.Ldarg_S, paramReference); break; // TODO: Ldarg_S or Ldarg? } worker.Append(paramPushInstruction); } } #region Calling code class method private void CreateCodeToCallCodeClass(MethodDefinition implementedMethod) { var companionClassMethod = ResolveCompanionMethod(); implementedMethod.Body = new MethodBody(implementedMethod); PushParameters(implementedMethod); EmitCodeToCallMethod(implementedMethod, companionClassMethod); implementedMethod.Body.GetILProcessor().Emit(OpCodes.Ret); } private void EmitCodeToCallMethod(MethodDefinition caller, MethodReference callee) { var worker = caller.Body.GetILProcessor(); //worker.Emit(OpCodes.Tail); // TODO: cannot pass ByRef to a tail call worker.Emit(OpCodes.Call, callee); } private MethodReference ResolveCompanionMethod() { var correspondingMethod = Role.Resolve().ResolveCorrespondingMethod(RoleMethod); if (correspondingMethod == null) throw new InvalidOperationException(); var methodReference = ResolveMethodReference(Role, correspondingMethod); return methodReference; } #endregion #region Auto property methods private void CreateCodeForAutoPropertyAccessor(MethodDefinition implementedMethod) { if (implementedMethod.IsAbstract) return; if (implementedMethod.IsPropertyGetter()) { EmitGetterCode(implementedMethod); } else if (implementedMethod.IsPropertySetter()) { EmitSetterCode(implementedMethod); } } private void EmitGetterCode(MethodDefinition implementedMethod) { if (_backingField == null) throw new InvalidOperationException(); var IL = implementedMethod.Body.GetILProcessor(); IL.Emit(OpCodes.Ldarg_0); IL.Emit(OpCodes.Ldfld, ResolveFieldReference(_backingField)); IL.Emit(OpCodes.Ret); } private void EmitSetterCode(MethodDefinition implementedMethod) { if (_backingField == null) throw new InvalidOperationException(); var IL = implementedMethod.Body.GetILProcessor(); IL.Emit(OpCodes.Ldarg_0); IL.Emit(OpCodes.Ldarg_1); IL.Emit(OpCodes.Stfld, ResolveFieldReference(_backingField)); IL.Emit(OpCodes.Ret); } private FieldReference ResolveFieldReference(FieldDefinition fieldDefinition) { return new FieldReference( fieldDefinition.Name, fieldDefinition.FieldType) { DeclaringType = fieldDefinition.DeclaringType.ResolveGenericArguments() }; } #endregion } }
37.089286
132
0.696036
[ "MIT" ]
xingh/nroles
src/NRoles.Engine/Composition/MemberComposer.MethodComposer.cs
6,233
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the greengrass-2017-06-07.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Greengrass.Model { /// <summary> /// This is the response object from the GetSubscriptionDefinition operation. /// </summary> public partial class GetSubscriptionDefinitionResponse : AmazonWebServiceResponse { private string _arn; private string _creationTimestamp; private string _id; private string _lastUpdatedTimestamp; private string _latestVersion; private string _latestVersionArn; private string _name; /// <summary> /// Gets and sets the property Arn. The ARN of the definition. /// </summary> public string Arn { get { return this._arn; } set { this._arn = value; } } // Check to see if Arn property is set internal bool IsSetArn() { return this._arn != null; } /// <summary> /// Gets and sets the property CreationTimestamp. The time, in milliseconds since the /// epoch, when the definition was created. /// </summary> public string CreationTimestamp { get { return this._creationTimestamp; } set { this._creationTimestamp = value; } } // Check to see if CreationTimestamp property is set internal bool IsSetCreationTimestamp() { return this._creationTimestamp != null; } /// <summary> /// Gets and sets the property Id. The ID of the definition. /// </summary> public string Id { get { return this._id; } set { this._id = value; } } // Check to see if Id property is set internal bool IsSetId() { return this._id != null; } /// <summary> /// Gets and sets the property LastUpdatedTimestamp. The time, in milliseconds since the /// epoch, when the definition was last updated. /// </summary> public string LastUpdatedTimestamp { get { return this._lastUpdatedTimestamp; } set { this._lastUpdatedTimestamp = value; } } // Check to see if LastUpdatedTimestamp property is set internal bool IsSetLastUpdatedTimestamp() { return this._lastUpdatedTimestamp != null; } /// <summary> /// Gets and sets the property LatestVersion. The latest version of the definition. /// </summary> public string LatestVersion { get { return this._latestVersion; } set { this._latestVersion = value; } } // Check to see if LatestVersion property is set internal bool IsSetLatestVersion() { return this._latestVersion != null; } /// <summary> /// Gets and sets the property LatestVersionArn. The ARN of the latest version of the /// definition. /// </summary> public string LatestVersionArn { get { return this._latestVersionArn; } set { this._latestVersionArn = value; } } // Check to see if LatestVersionArn property is set internal bool IsSetLatestVersionArn() { return this._latestVersionArn != null; } /// <summary> /// Gets and sets the property Name. The name of the definition. /// </summary> public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } } }
30.203947
108
0.59181
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/Greengrass/Generated/Model/GetSubscriptionDefinitionResponse.cs
4,591
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; namespace Nop.Plugin.Feed.Salidzini.Models { [XmlRoot(ElementName = "root", Namespace = null)] public class SalidziniProductList : List<SalidziniProductItem> { } [XmlType(TypeName = "item")] public class SalidziniProductItem { public string name { get; set; } public string link { get; set; } public string price { get; set; } public string image { get; set; } public string category_full { get; set; } public string category_link { get; set; } public string manufacturer { get; set; } public string model { get; set; } public string in_stock { get; set; } public string delivery_cost_riga { get; set; } public string delivery_latvija { get; set; } public string delivery_latvijas_pasts { get; set; } public string delivery_dpd_paku_bode { get; set; } public string delivery_pasta_stacija { get; set; } public string delivery_omniva { get; set; } public string delivery_statoil { get; set; } public string delivery_days_riga { get; set; } public string delivery_days_latvija { get; set; } public string used { get; set; } } }
34.897436
66
0.650257
[ "Apache-2.0" ]
jitt-lv/salidzini-plugin-for-nopcommerce
Models/SalidziniItemList.cs
1,363
C#
//////////////////////////////////////////// // CameraFilterPack - by VETASOFT 2016 ///// //////////////////////////////////////////// using UnityEngine; using System.Collections; [ExecuteInEditMode] [AddComponentMenu ("Camera Filter Pack/FX/Earth Quake")] public class CameraFilterPack_FX_EarthQuake : MonoBehaviour { #region Variables public Shader SCShader; private float TimeX = 1.0f; private Vector4 ScreenResolution; private Material SCMaterial; [Range(0f, 100f)] public float Speed = 15f; [Range(0f, 0.2f)] public float X = 0.008f; [Range(0f, 0.2f)] public float Y = 0.008f; [Range(0f, 0.2f)] private float Value4 = 1f; #endregion #region Properties Material material { get { if(SCMaterial == null) { SCMaterial = new Material(SCShader); SCMaterial.hideFlags = HideFlags.HideAndDontSave; } return SCMaterial; } } #endregion void Start () { SCShader = Shader.Find("CameraFilterPack/FX_EarthQuake"); if(!SystemInfo.supportsImageEffects) { enabled = false; return; } } void OnRenderImage (RenderTexture sourceTexture, RenderTexture destTexture) { if(SCShader != null) { TimeX+=Time.deltaTime; if (TimeX>100) TimeX=0; material.SetFloat("_TimeX", TimeX); material.SetFloat("_Value", Speed); material.SetFloat("_Value2", X); material.SetFloat("_Value3", Y); material.SetFloat("_Value4", Value4); material.SetVector("_ScreenResolution",new Vector4(sourceTexture.width,sourceTexture.height,0.0f,0.0f)); Graphics.Blit(sourceTexture, destTexture, material); } else { Graphics.Blit(sourceTexture, destTexture); } } void Update () { #if UNITY_EDITOR if (Application.isPlaying!=true) { SCShader = Shader.Find("CameraFilterPack/FX_EarthQuake"); } #endif } void OnDisable () { if(SCMaterial) { DestroyImmediate(SCMaterial); } } }
21.259259
104
0.720093
[ "MIT" ]
Crew7Studio/02_Pixel_Swords
Assets/Camera Filter Pack/Scripts/CameraFilterPack_FX_EarthQuake.cs
1,722
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Globalization; using Xunit; namespace System.Tests { public class TimeSpanTests { [Fact] public static void MaxValue() { VerifyTimeSpan(TimeSpan.MaxValue, 10675199, 2, 48, 5, 477); } [Fact] public static void MinValue() { VerifyTimeSpan(TimeSpan.MinValue, -10675199, -2, -48, -5, -477); } [Fact] public static void Zero() { VerifyTimeSpan(TimeSpan.Zero, 0, 0, 0, 0, 0); } [Fact] public static void Ctor_Empty() { VerifyTimeSpan(new TimeSpan(), 0, 0, 0, 0, 0); VerifyTimeSpan(default(TimeSpan), 0, 0, 0, 0, 0); } [Fact] public static void Ctor_Long() { VerifyTimeSpan(new TimeSpan(999999999999999999), 1157407, 9, 46, 39, 999); } [Fact] public static void Ctor_Int_Int_Int() { var timeSpan = new TimeSpan(10, 9, 8); VerifyTimeSpan(timeSpan, 0, 10, 9, 8, 0); } [Fact] public static void Ctor_Int_Int_Int_Invalid() { AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan((int)TimeSpan.MinValue.TotalHours - 1, 0, 0)); // TimeSpan < TimeSpan.MinValue AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan((int)TimeSpan.MaxValue.TotalHours + 1, 0, 0)); // TimeSpan > TimeSpan.MaxValue } [Fact] public static void Ctor_Int_Int_Int_Int_Int() { var timeSpan = new TimeSpan(10, 9, 8, 7, 6); VerifyTimeSpan(timeSpan, 10, 9, 8, 7, 6); } [Fact] public static void Ctor_Int_Int_Int_Int_Int_Invalid() { // TimeSpan > TimeSpan.MinValue TimeSpan min = TimeSpan.MinValue; AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan(min.Days - 1, min.Hours, min.Minutes, min.Seconds, min.Milliseconds)); AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan(min.Days, min.Hours - 1, min.Minutes, min.Seconds, min.Milliseconds)); AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan(min.Days, min.Hours, min.Minutes - 1, min.Seconds, min.Milliseconds)); AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan(min.Days, min.Hours, min.Minutes, min.Seconds - 1, min.Milliseconds)); AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan(min.Days, min.Hours, min.Minutes, min.Seconds, min.Milliseconds - 1)); // TimeSpan > TimeSpan.MaxValue TimeSpan max = TimeSpan.MaxValue; AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan(max.Days + 1, max.Hours, max.Minutes, max.Seconds, max.Milliseconds)); AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan(max.Days, max.Hours + 1, max.Minutes, max.Seconds, max.Milliseconds)); AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan(max.Days, max.Hours, max.Minutes + 1, max.Seconds, max.Milliseconds)); AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan(max.Days, max.Hours, max.Minutes, max.Seconds + 1, max.Milliseconds)); AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan(max.Days, max.Hours, max.Minutes, max.Seconds, max.Milliseconds + 1)); } [Fact] public static void Ctor_Int_Int_Int_Int_Int_Int() { var timeSpan = new TimeSpan(10, 9, 8, 7, 6, 5); VerifyTimeSpan(timeSpan, 10, 9, 8, 7, 6, 5); } [Fact] public static void Ctor_Int_Int_Int_Int_Int_Int_Invalid() { // TimeSpan > TimeSpan.MinValue TimeSpan min = TimeSpan.MinValue; AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan(min.Days - 1, min.Hours, min.Minutes, min.Seconds, min.Milliseconds, min.Microseconds)); AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan(min.Days, min.Hours - 1, min.Minutes, min.Seconds, min.Milliseconds, min.Microseconds)); AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan(min.Days, min.Hours, min.Minutes - 1, min.Seconds, min.Milliseconds, min.Microseconds)); AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan(min.Days, min.Hours, min.Minutes, min.Seconds - 1, min.Milliseconds, min.Microseconds)); AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan(min.Days, min.Hours, min.Minutes, min.Seconds, min.Milliseconds, min.Microseconds - 1)); // TimeSpan > TimeSpan.MaxValue TimeSpan max = TimeSpan.MaxValue; AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan(max.Days + 1, max.Hours, max.Minutes, max.Seconds, max.Milliseconds, max.Microseconds)); AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan(max.Days, max.Hours + 1, max.Minutes, max.Seconds, max.Milliseconds, max.Microseconds)); AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan(max.Days, max.Hours, max.Minutes + 1, max.Seconds, max.Milliseconds, max.Microseconds)); AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan(max.Days, max.Hours, max.Minutes, max.Seconds + 1, max.Milliseconds, max.Microseconds)); AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan(max.Days, max.Hours, max.Minutes, max.Seconds, max.Milliseconds, max.Microseconds + 1)); } [Theory] [InlineData(100)] [InlineData(300)] [InlineData(900)] public static void Ctor_Int_Int_Int_Int_Int_Int_WithNanosecond(int nanoseconds) { var timeSpan = new TimeSpan(10, 9, 8, 7, 6, 5); timeSpan = new TimeSpan(timeSpan.Ticks + nanoseconds / 100); VerifyTimeSpan(timeSpan, 10, 9, 8, 7, 6, 5, nanoseconds); } public static IEnumerable<object[]> Total_Days_Hours_Minutes_Seconds_Milliseconds_TestData() { yield return new object[] { new TimeSpan(0, 0, 0, 0, 0), 0.0, 0.0, 0.0, 0.0, 0.0 }; yield return new object[] { new TimeSpan(0, 0, 0, 0, 500), 0.5 / 60.0 / 60.0 / 24.0, 0.5 / 60.0 / 60.0, 0.5 / 60.0, 0.5, 500.0 }; yield return new object[] { new TimeSpan(0, 1, 0, 0, 0), 1 / 24.0, 1, 60, 3600, 3600000 }; yield return new object[] { new TimeSpan(1, 0, 0, 0, 0), 1, 24, 1440, 86400, 86400000 }; yield return new object[] { new TimeSpan(1, 1, 0, 0, 0), 25.0 / 24.0, 25, 1500, 90000, 90000000 }; } [Theory] [MemberData(nameof(Total_Days_Hours_Minutes_Seconds_Milliseconds_TestData))] public static void Total_Days_Hours_Minutes_Seconds_Milliseconds(TimeSpan timeSpan, double expectedDays, double expectedHours, double expectedMinutes, double expectedSeconds, double expectedMilliseconds) { // Use ToString() to prevent any rounding errors when comparing Assert.Equal(expectedDays.ToString("G15"), timeSpan.TotalDays.ToString("G15")); Assert.Equal(expectedHours, timeSpan.TotalHours); Assert.Equal(expectedMinutes, timeSpan.TotalMinutes); Assert.Equal(expectedSeconds, timeSpan.TotalSeconds); Assert.Equal(expectedMilliseconds, timeSpan.TotalMilliseconds); } [Fact] public static void TotalMilliseconds_Invalid() { long maxMilliseconds = long.MaxValue / 10000; long minMilliseconds = long.MinValue / 10000; Assert.Equal(maxMilliseconds, TimeSpan.MaxValue.TotalMilliseconds); Assert.Equal(minMilliseconds, TimeSpan.MinValue.TotalMilliseconds); } public static IEnumerable<object[]> Add_TestData() { yield return new object[] { new TimeSpan(0, 0, 0), new TimeSpan(1, 2, 3), new TimeSpan(1, 2, 3) }; yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(4, 5, 6), new TimeSpan(5, 7, 9) }; yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(-4, -5, -6), new TimeSpan(-3, -3, -3) }; yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 3), new TimeSpan(1, 3, 5, 7, 5) }; yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(10, 12, 13, 14, 15), new TimeSpan(11, 14, 16, 18, 20) }; yield return new object[] { new TimeSpan(10000), new TimeSpan(200000), new TimeSpan(210000) }; } [Theory] [MemberData(nameof(Add_TestData))] public static void Add(TimeSpan timeSpan1, TimeSpan timeSpan2, TimeSpan expected) { Assert.Equal(expected, timeSpan1.Add(timeSpan2)); Assert.Equal(expected, timeSpan1 + timeSpan2); } [Fact] public static void Add_Invalid() { Assert.Throws<OverflowException>(() => TimeSpan.MaxValue.Add(new TimeSpan(1))); // Result > TimeSpan.MaxValue Assert.Throws<OverflowException>(() => TimeSpan.MinValue.Add(new TimeSpan(-1))); // Result < TimeSpan.MinValue Assert.Throws<OverflowException>(() => TimeSpan.MaxValue + new TimeSpan(1)); // Result > TimeSpan.MaxValue Assert.Throws<OverflowException>(() => TimeSpan.MinValue + new TimeSpan(-1)); // Result < TimeSpan.MinValue } [Fact] public static void FromMinMaxValue_DoesNotThrow() { TimeSpan maxTimeSpan = TimeSpan.FromDays(TimeSpan.MaxValue.TotalDays); TimeSpan minTimeSpan = TimeSpan.FromDays(TimeSpan.MinValue.TotalDays); Assert.Equal(TimeSpan.MaxValue, maxTimeSpan); Assert.Equal(TimeSpan.MinValue, minTimeSpan); } public static IEnumerable<object[]> CompareTo_TestData() { yield return new object[] { new TimeSpan(10000), new TimeSpan(10000), 0 }; yield return new object[] { new TimeSpan(20000), new TimeSpan(10000), 1 }; yield return new object[] { new TimeSpan(10000), new TimeSpan(20000), -1 }; yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(1, 2, 3), 0 }; yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(1, 2, 4), -1 }; yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(1, 2, 2), 1 }; yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(1, 3, 3), -1 }; yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(1, 1, 3), 1 }; yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(2, 2, 3), -1 }; yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(0, 2, 3), 1 }; yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(1, 2, 3, 4), 0 }; yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(1, 2, 3, 5), -1 }; yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(1, 2, 3, 3), 1 }; yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(1, 2, 4, 4), -1 }; yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(1, 2, 2, 4), 1 }; yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(1, 3, 3, 4), -1 }; yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(1, 1, 3, 4), 1 }; yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(2, 2, 3, 4), -1 }; yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(0, 2, 3, 4), 1 }; yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 3, 4, 5), 0 }; yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 3, 4, 6), -1 }; yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 3, 4, 4), 1 }; yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 3, 5, 5), -1 }; yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 3, 3, 5), 1 }; yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 4, 4, 5), -1 }; yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 2, 4, 5), 1 }; yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 3, 3, 4, 5), -1 }; yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 1, 3, 4, 5), 1 }; yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(2, 2, 3, 4, 5), -1 }; yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(0, 2, 3, 4, 5), 1 }; yield return new object[] { new TimeSpan(10000), null, 1 }; } [Theory] [MemberData(nameof(CompareTo_TestData))] public static void CompareTo(TimeSpan timeSpan1, object obj, int expected) { if (obj is TimeSpan) { TimeSpan timeSpan2 = (TimeSpan)obj; Assert.Equal(expected, Math.Sign(timeSpan1.CompareTo(timeSpan2))); Assert.Equal(expected, Math.Sign(TimeSpan.Compare(timeSpan1, timeSpan2))); if (expected >= 0) { Assert.True(timeSpan1 >= timeSpan2); Assert.False(timeSpan1 < timeSpan2); } if (expected > 0) { Assert.True(timeSpan1 > timeSpan2); Assert.False(timeSpan1 <= timeSpan2); } if (expected <= 0) { Assert.True(timeSpan1 <= timeSpan2); Assert.False(timeSpan1 > timeSpan2); } if (expected < 0) { Assert.True(timeSpan1 < timeSpan2); Assert.False(timeSpan1 >= timeSpan2); } } IComparable comparable = timeSpan1; Assert.Equal(expected, Math.Sign(comparable.CompareTo(obj))); } [Fact] public static void CompareTo_ObjectNotTimeSpan_ThrowsArgumentException() { IComparable comparable = new TimeSpan(10000); AssertExtensions.Throws<ArgumentException>(null, () => comparable.CompareTo("10000")); // Obj is not a time span } public static IEnumerable<object[]> Duration_TestData() { yield return new object[] { new TimeSpan(0, 0, 0), new TimeSpan(0, 0, 0) }; yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(1, 2, 3) }; yield return new object[] { new TimeSpan(-1, -2, -3), new TimeSpan(1, 2, 3) }; yield return new object[] { new TimeSpan(12345), new TimeSpan(12345) }; yield return new object[] { new TimeSpan(-12345), new TimeSpan(12345) }; } [Theory] [MemberData(nameof(Duration_TestData))] public static void Duration(TimeSpan timeSpan, TimeSpan expected) { Assert.Equal(expected, timeSpan.Duration()); } [Fact] public static void Duration_Invalid() { Assert.Throws<OverflowException>(() => TimeSpan.MinValue.Duration()); // TimeSpan.Ticks == TimeSpan.MinValue.Ticks Assert.Throws<OverflowException>(() => new TimeSpan(TimeSpan.MinValue.Ticks).Duration()); // TimeSpan.Ticks == TimeSpan.MinValue.Ticks } public static IEnumerable<object[]> Equals_TestData() { yield return new object[] { new TimeSpan(0, 0, 0), new TimeSpan(0, 0, 0), true }; yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(1, 2, 3), true }; yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(1, 2, 4), false }; yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(1, 3, 3), false }; yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(2, 2, 3), false }; yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(0, 1, 2, 3), true }; yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(0, 1, 2, 3, 0), true }; yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(1, 2, 3, 4), true }; yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(1, 2, 3, 5), false }; yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(1, 2, 4, 4), false }; yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(1, 3, 3, 4), false }; yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(2, 2, 3, 4), false }; yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(2, 3, 4), false }; yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 3, 4, 5), true }; yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 3, 4, 6), false }; yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 3, 5, 5), false }; yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 4, 4, 5), false }; yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 3, 3, 4, 5), false }; yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(2, 2, 3, 4, 5), false }; yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 3, 4), false }; yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(2, 2, 3), false }; yield return new object[] { new TimeSpan(10000), new TimeSpan(10000), true }; yield return new object[] { new TimeSpan(10000), new TimeSpan(20000), false }; yield return new object[] { new TimeSpan(10000), "20000", false }; yield return new object[] { new TimeSpan(10000), null, false }; } [Theory] [MemberData(nameof(Equals_TestData))] public static void EqualsTest(TimeSpan timeSpan1, object obj, bool expected) { if (obj is TimeSpan) { TimeSpan timeSpan2 = (TimeSpan)obj; Assert.Equal(expected, TimeSpan.Equals(timeSpan1, timeSpan2)); Assert.Equal(expected, timeSpan1.Equals(timeSpan2)); Assert.Equal(expected, timeSpan1 == timeSpan2); Assert.Equal(!expected, timeSpan1 != timeSpan2); Assert.Equal(expected, timeSpan1.GetHashCode().Equals(timeSpan2.GetHashCode())); } Assert.Equal(expected, timeSpan1.Equals(obj)); } public static IEnumerable<object[]> FromDays_TestData() { yield return new object[] { 100.5, new TimeSpan(100, 12, 0, 0) }; yield return new object[] { 2.5, new TimeSpan(2, 12, 0, 0) }; yield return new object[] { 1.0, new TimeSpan(1, 0, 0, 0) }; yield return new object[] { 0.0, new TimeSpan(0, 0, 0, 0) }; yield return new object[] { -1.0, new TimeSpan(-1, 0, 0, 0) }; yield return new object[] { -2.5, new TimeSpan(-2, -12, 0, 0) }; yield return new object[] { -100.5, new TimeSpan(-100, -12, 0, 0) }; } [Theory] [MemberData(nameof(FromDays_TestData))] public static void FromDays(double value, TimeSpan expected) { Assert.Equal(expected, TimeSpan.FromDays(value)); } [Fact] public static void FromDays_Invalid() { double maxDays = long.MaxValue / (TimeSpan.TicksPerMillisecond / 1000.0 / 60.0 / 60.0 / 24.0); Assert.Throws<OverflowException>(() => TimeSpan.FromDays(double.PositiveInfinity)); // Value is positive infinity Assert.Throws<OverflowException>(() => TimeSpan.FromDays(double.NegativeInfinity)); // Value is positive infinity Assert.Throws<OverflowException>(() => TimeSpan.FromDays(maxDays)); // Value > TimeSpan.MaxValue Assert.Throws<OverflowException>(() => TimeSpan.FromDays(-maxDays)); // Value < TimeSpan.MinValue AssertExtensions.Throws<ArgumentException>(null, () => TimeSpan.FromMinutes(double.NaN)); // Value is NaN } public static IEnumerable<object[]> FromHours_TestData() { yield return new object[] { 100.5, new TimeSpan(4, 4, 30, 0) }; yield return new object[] { 2.5, new TimeSpan(2, 30, 0) }; yield return new object[] { 1.0, new TimeSpan(1, 0, 0) }; yield return new object[] { 0.0, new TimeSpan(0, 0, 0) }; yield return new object[] { -1.0, new TimeSpan(-1, 0, 0) }; yield return new object[] { -2.5, new TimeSpan(-2, -30, 0) }; yield return new object[] { -100.5, new TimeSpan(-4, -4, -30, 0) }; } [Theory] [MemberData(nameof(FromHours_TestData))] public static void FromHours(double value, TimeSpan expected) { Assert.Equal(expected, TimeSpan.FromHours(value)); } [Fact] public static void FromHours_Invalid() { double maxHours = long.MaxValue / (TimeSpan.TicksPerMillisecond / 1000.0 / 60.0 / 60.0); Assert.Throws<OverflowException>(() => TimeSpan.FromHours(double.PositiveInfinity)); // Value is positive infinity Assert.Throws<OverflowException>(() => TimeSpan.FromHours(double.NegativeInfinity)); // Value is positive infinity Assert.Throws<OverflowException>(() => TimeSpan.FromHours(maxHours)); // Value > TimeSpan.MaxValue Assert.Throws<OverflowException>(() => TimeSpan.FromHours(-maxHours)); // Value < TimeSpan.MinValue AssertExtensions.Throws<ArgumentException>(null, () => TimeSpan.FromMinutes(double.NaN)); // Value is NaN } public static IEnumerable<object[]> FromMinutes_TestData() { yield return new object[] { 100.5, new TimeSpan(1, 40, 30) }; yield return new object[] { 2.5, new TimeSpan(0, 2, 30) }; yield return new object[] { 1.0, new TimeSpan(0, 1, 0) }; yield return new object[] { 0.0, new TimeSpan(0, 0, 0) }; yield return new object[] { -1.0, new TimeSpan(0, -1, 0) }; yield return new object[] { -2.5, new TimeSpan(0, -2, -30) }; yield return new object[] { -100.5, new TimeSpan(-1, -40, -30) }; } [Theory] [MemberData(nameof(FromMinutes_TestData))] public static void FromMinutes(double value, TimeSpan expected) { Assert.Equal(expected, TimeSpan.FromMinutes(value)); } [Fact] public static void FromMinutes_Invalid() { double maxMinutes = long.MaxValue / (TimeSpan.TicksPerMillisecond / 1000.0 / 60.0); Assert.Throws<OverflowException>(() => TimeSpan.FromMinutes(double.PositiveInfinity)); // Value is positive infinity Assert.Throws<OverflowException>(() => TimeSpan.FromMinutes(double.NegativeInfinity)); // Value is positive infinity Assert.Throws<OverflowException>(() => TimeSpan.FromMinutes(maxMinutes)); // Value > TimeSpan.MaxValue Assert.Throws<OverflowException>(() => TimeSpan.FromMinutes(-maxMinutes)); // Value < TimeSpan.MinValue AssertExtensions.Throws<ArgumentException>(null, () => TimeSpan.FromMinutes(double.NaN)); // Value is NaN } public static IEnumerable<object[]> FromSeconds_TestData() { yield return new object[] { 100.5, new TimeSpan(0, 0, 1, 40, 500) }; yield return new object[] { 2.5, new TimeSpan(0, 0, 0, 2, 500) }; yield return new object[] { 1.0, new TimeSpan(0, 0, 0, 1, 0) }; yield return new object[] { 0.0, new TimeSpan(0, 0, 0, 0, 0) }; yield return new object[] { -1.0, new TimeSpan(0, 0, 0, -1, 0) }; yield return new object[] { -2.5, new TimeSpan(0, 0, 0, -2, -500) }; yield return new object[] { -100.5, new TimeSpan(0, 0, -1, -40, -500) }; } [Theory] [MemberData(nameof(FromSeconds_TestData))] public static void FromSeconds(double value, TimeSpan expected) { Assert.Equal(expected, TimeSpan.FromSeconds(value)); } [Fact] public static void FromSeconds_Invalid() { double maxSeconds = long.MaxValue / (TimeSpan.TicksPerMillisecond / 1000.0); Assert.Throws<OverflowException>(() => TimeSpan.FromSeconds(double.PositiveInfinity)); // Value is positive infinity Assert.Throws<OverflowException>(() => TimeSpan.FromSeconds(double.NegativeInfinity)); // Value is positive infinity Assert.Throws<OverflowException>(() => TimeSpan.FromSeconds(maxSeconds)); // Value > TimeSpan.MaxValue Assert.Throws<OverflowException>(() => TimeSpan.FromSeconds(-maxSeconds)); // Value < TimeSpan.MinValue AssertExtensions.Throws<ArgumentException>(null, () => TimeSpan.FromSeconds(double.NaN)); // Value is NaN } public static IEnumerable<object[]> FromMilliseconds_TestData_NetCore() { yield return new object[] { 1500.5, new TimeSpan(15005000) }; yield return new object[] { 2.5, new TimeSpan(25000) }; yield return new object[] { 1.0, new TimeSpan(10000) }; yield return new object[] { 0.0, new TimeSpan(0) }; yield return new object[] { -1.0, new TimeSpan(-10000) }; yield return new object[] { -2.5, new TimeSpan(-25000) }; yield return new object[] { -1500.5, new TimeSpan(-15005000) }; } [Theory] [MemberData(nameof(FromMilliseconds_TestData_NetCore))] public static void FromMilliseconds_Netcore(double value, TimeSpan expected) { Assert.Equal(expected, TimeSpan.FromMilliseconds(value)); } public static IEnumerable<object[]> FromMilliseconds_TestData_Desktop() { yield return new object[] { 1500.5, new TimeSpan(15010000) }; yield return new object[] { 2.5, new TimeSpan(30000) }; yield return new object[] { 1.0, new TimeSpan(10000) }; yield return new object[] { 0.0, new TimeSpan(0) }; yield return new object[] { -1.0, new TimeSpan(-10000) }; yield return new object[] { -2.5, new TimeSpan(-30000) }; yield return new object[] { -1500.5, new TimeSpan(-15010000) }; } [Fact] public static void FromMilliseconds_Invalid() { double maxMilliseconds = (double)TimeSpan.MaxValue.Ticks / (double)TimeSpan.TicksPerMillisecond + 1; Assert.Throws<OverflowException>(() => TimeSpan.FromMilliseconds(double.PositiveInfinity)); // Value is positive infinity Assert.Throws<OverflowException>(() => TimeSpan.FromMilliseconds(double.NegativeInfinity)); // Value is positive infinity Assert.Throws<OverflowException>(() => TimeSpan.FromMilliseconds(maxMilliseconds)); // Value > TimeSpan.MaxValue Assert.Throws<OverflowException>(() => TimeSpan.FromMilliseconds(-maxMilliseconds)); // Value < TimeSpan.MinValue AssertExtensions.Throws<ArgumentException>(null, () => TimeSpan.FromMilliseconds(double.NaN)); // Value is NaN } public static IEnumerable<object[]> FromTicks_TestData() { yield return new object[] { TimeSpan.TicksPerMillisecond, new TimeSpan(0, 0, 0, 0, 1) }; yield return new object[] { TimeSpan.TicksPerSecond, new TimeSpan(0, 0, 0, 1, 0) }; yield return new object[] { TimeSpan.TicksPerMinute, new TimeSpan(0, 0, 1, 0, 0) }; yield return new object[] { TimeSpan.TicksPerHour, new TimeSpan(0, 1, 0, 0, 0) }; yield return new object[] { TimeSpan.TicksPerDay, new TimeSpan(1, 0, 0, 0, 0) }; yield return new object[] { 1.0, new TimeSpan(1) }; yield return new object[] { 0.0, new TimeSpan(0, 0, 0) }; yield return new object[] { -1.0, new TimeSpan(-1) }; yield return new object[] { -TimeSpan.TicksPerMillisecond, new TimeSpan(0, 0, 0, 0, -1) }; yield return new object[] { -TimeSpan.TicksPerSecond, new TimeSpan(0, 0, 0, -1, 0) }; yield return new object[] { -TimeSpan.TicksPerMinute, new TimeSpan(0, 0, -1, 0, 0) }; yield return new object[] { -TimeSpan.TicksPerHour, new TimeSpan(0, -1, 0, 0, 0) }; yield return new object[] { -TimeSpan.TicksPerDay, new TimeSpan(-1, 0, 0, 0, 0) }; } [Theory] [MemberData(nameof(FromTicks_TestData))] public static void FromTicks(long value, TimeSpan expected) { Assert.Equal(expected, TimeSpan.FromTicks(value)); } public static IEnumerable<object[]> TotalSeconds_ExactRepresentation_TestData() { yield return new object[] { new TimeSpan(0, 0, 0, 0, 0) }; yield return new object[] { new TimeSpan(0, 0, 0, 1, 0) }; yield return new object[] { new TimeSpan(0, 0, 0, 1, 100) }; yield return new object[] { new TimeSpan(0, 0, 0, 0, -100) }; yield return new object[] { new TimeSpan(0, 0, 0, 0, 34967800) }; } [Theory] [MemberData(nameof(TotalSeconds_ExactRepresentation_TestData))] public static void TotalSeconds_ExactRepresentation(TimeSpan value) { Assert.Equal(value, TimeSpan.FromSeconds(value.TotalSeconds)); } public static IEnumerable<object[]> Negate_TestData() { yield return new object[] { new TimeSpan(0, 0, 0), new TimeSpan(0, 0, 0) }; yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(-1, -2, -3) }; yield return new object[] { new TimeSpan(-1, -2, -3), new TimeSpan(1, 2, 3) }; yield return new object[] { new TimeSpan(12345), new TimeSpan(-12345) }; yield return new object[] { new TimeSpan(-12345), new TimeSpan(12345) }; } [Theory] [MemberData(nameof(Negate_TestData))] public static void Negate(TimeSpan timeSpan, TimeSpan expected) { Assert.Equal(expected, timeSpan.Negate()); Assert.Equal(expected, -timeSpan); } [Fact] public static void Negate_Invalid() { Assert.Throws<OverflowException>(() => TimeSpan.MinValue.Negate()); // TimeSpan.MinValue cannot be negated Assert.Throws<OverflowException>(() => -TimeSpan.MinValue); // TimeSpan.MinValue cannot be negated } public static IEnumerable<object[]> Parse_Valid_TestData() { // Space is trimmed before and after yield return new object[] { " 12:24:02", null, new TimeSpan(0, 12, 24, 2, 0) }; yield return new object[] { "12:24:02 ", null, new TimeSpan(0, 12, 24, 2, 0) }; yield return new object[] { " 12:24:02 ", null, new TimeSpan(0, 12, 24, 2, 0) }; // Positive and negative 0 are both valid yield return new object[] { "0", null, new TimeSpan(0, 0, 0, 0, 0) }; // HH:MM yield return new object[] { "12:24", null, new TimeSpan(0, 12, 24, 0, 0) }; // HH:MM:SS yield return new object[] { "12:24:02", null, new TimeSpan(0, 12, 24, 2, 0) }; // DD.HH:MM yield return new object[] { "12.03:04", null, new TimeSpan(12, 3, 4, 0, 0) }; // HH:MM:SS.FF yield return new object[] { "12:24:02.01", CultureInfo.InvariantCulture, new TimeSpan(0, 12, 24, 2, 10) }; // HH:MM:SS.FF w/ varying length zero prefixes on the fraction yield return new object[] { "1:1:1.0", CultureInfo.InvariantCulture, new TimeSpan(1, 1, 1) }; yield return new object[] { "1:1:1.0000000", CultureInfo.InvariantCulture, new TimeSpan(1, 1, 1) }; yield return new object[] { "1:1:1.1", CultureInfo.InvariantCulture, new TimeSpan(0, 1, 1, 1, 100) }; yield return new object[] { "1:1:1.01", CultureInfo.InvariantCulture, new TimeSpan(0, 1, 1, 1, 10) }; yield return new object[] { "1:1:1.001", CultureInfo.InvariantCulture, new TimeSpan(0, 1, 1, 1, 1) }; yield return new object[] { "1:1:1.0001", CultureInfo.InvariantCulture, new TimeSpan(36610001000) }; yield return new object[] { "1:1:1.00001", CultureInfo.InvariantCulture, new TimeSpan(36610000100) }; yield return new object[] { "1:1:1.000001", CultureInfo.InvariantCulture, new TimeSpan(36610000010) }; yield return new object[] { "1:1:1.0000001", CultureInfo.InvariantCulture, new TimeSpan(36610000001) }; // DD.HH:MM:SS yield return new object[] { "1.12:24:02", null, new TimeSpan(1, 12, 24, 2, 0) }; // DD:HH:MM:SS yield return new object[] { "1:12:24:02", null, new TimeSpan(1, 12, 24, 2, 0) }; // DD.HH:MM:.FF yield return new object[] { "01.23:45:.67", CultureInfo.InvariantCulture, new TimeSpan(1, 23, 45, 0, 670) }; // DD.HH.MM:SS.FFF yield return new object[] { "1.12:24:02.999", CultureInfo.InvariantCulture, new TimeSpan(1, 12, 24, 2, 999) }; // HH:MM::.FF w/ varying length zero prefixes on the fraction yield return new object[] { "1:1:.1", CultureInfo.InvariantCulture, new TimeSpan(36601000000) }; yield return new object[] { "1:1:.01", CultureInfo.InvariantCulture, new TimeSpan(36600100000) }; yield return new object[] { "1:1:.001", CultureInfo.InvariantCulture, new TimeSpan(36600010000) }; yield return new object[] { "1:1:.0001", CultureInfo.InvariantCulture, new TimeSpan(36600001000) }; yield return new object[] { "1:1:.00001", CultureInfo.InvariantCulture, new TimeSpan(36600000100) }; yield return new object[] { "1:1:.000001", CultureInfo.InvariantCulture, new TimeSpan(36600000010) }; yield return new object[] { "1:1:.0000001", CultureInfo.InvariantCulture, new TimeSpan(36600000001) }; // Just below overflow on various components yield return new object[] { "10675199", null, new TimeSpan(9223371936000000000) }; yield return new object[] { "10675199:00:00", null, new TimeSpan(9223371936000000000) }; yield return new object[] { "10675199:02:00:00", null, new TimeSpan(9223372008000000000) }; yield return new object[] { "10675199:02:48:00", null, new TimeSpan(9223372036800000000) }; yield return new object[] { "10675199:02:48:05", null, new TimeSpan(9223372036850000000) }; yield return new object[] { "10675199:02:48:05.4775", CultureInfo.InvariantCulture, new TimeSpan(9223372036854775000) }; yield return new object[] { "00:00:59", null, new TimeSpan(0, 0, 59) }; yield return new object[] { "00:59:00", null, new TimeSpan(0, 59, 0) }; yield return new object[] { "23:00:00", null, new TimeSpan(23, 0, 0) }; yield return new object[] { "24:00:00", null, new TimeSpan(24, 0, 0, 0) }; if (PlatformDetection.IsNotInvariantGlobalization) { // Croatia uses ',' in place of '.' CultureInfo croatianCulture = new CultureInfo("hr-HR"); yield return new object[] { "6:12:14:45,348", croatianCulture, new TimeSpan(6, 12, 14, 45, 348) }; } } [Theory] [MemberData(nameof(Parse_Valid_TestData))] public static void Parse(string input, IFormatProvider provider, TimeSpan expected) { TimeSpan result; if (provider == null) { Assert.True(TimeSpan.TryParse(input, out result)); Assert.Equal(expected, result); Assert.Equal(expected, TimeSpan.Parse(input)); } Assert.True(TimeSpan.TryParse(input, provider, out result)); Assert.Equal(expected, result); Assert.Equal(expected, TimeSpan.Parse(input, provider)); // Also negate if (!char.IsWhiteSpace(input[0])) { Assert.Equal(-expected, TimeSpan.Parse("-" + input, provider)); Assert.True(TimeSpan.TryParse("-" + input, provider, out result)); Assert.Equal(-expected, result); } } public static IEnumerable<object[]> Parse_Invalid_TestData() { // FormatExceptions yield return new object[] { null, null, typeof(ArgumentNullException) }; // null input yield return new object[] { "", null, typeof(FormatException) }; // empty input yield return new object[] { "-", null, typeof(FormatException) }; // invalid sole separator yield return new object[] { "garbage", null, typeof(FormatException) }; // garbage input yield return new object[] { "12/12/12", null, typeof(FormatException) }; // unexpected separators yield return new object[] { "00:", null, typeof(FormatException) }; // missing number at end yield return new object[] { "00:00:-01", null, typeof(FormatException) }; // misplaced negative yield return new object[] { "\012:34:56", null, typeof(FormatException) }; // null char at front yield return new object[] { "1\02:34:56", null, typeof(FormatException) }; // null char in HH yield return new object[] { "12\0:34:56", null, typeof(FormatException) }; // null char at end of component yield return new object[] { "00:00::00", null, typeof(FormatException) }; // duplicated separator yield return new object[] { "00:00:00:", null, typeof(FormatException) }; // extra separator at end yield return new object[] { "00:00:00:00:00:00:00:00", null, typeof(FormatException) }; // too many components if (PlatformDetection.IsNotInvariantGlobalization) yield return new object[] { "6:12:14:45.3448", new CultureInfo("hr-HR"), typeof(FormatException) }; // culture that uses ',' rather than '.' // OverflowExceptions yield return new object[] { "1:1:1.99999999", null, typeof(OverflowException) }; // overflowing fraction yield return new object[] { "2147483647", null, typeof(OverflowException) }; // overflowing value == int.MaxValue yield return new object[] { "2147483648", null, typeof(OverflowException) }; // overflowing value == int.MaxValue + 1 yield return new object[] { "10675200", null, typeof(OverflowException) }; // overflowing number of days yield return new object[] { "10675200:00:00", null, typeof(OverflowException) }; // overflowing number of hours yield return new object[] { "10675199:03:00:00", null, typeof(OverflowException) }; // overflowing number of days + hours yield return new object[] { "10675199:02:49:00", null, typeof(OverflowException) }; // overflowing number of days + hours + minutes yield return new object[] { "10675199:02:48:06", null, typeof(OverflowException) }; // overflowing number of days + hours + minutes + seconds yield return new object[] { "-10675199:02:48:06", null, typeof(OverflowException) }; // negative overflowing d + h + m + s yield return new object[] { "10675199:02:48:05.4776", CultureInfo.InvariantCulture, typeof(OverflowException) }; // overflowing days + hours + minutes + seconds + fraction yield return new object[] { "-10675199:02:48:05.4776", CultureInfo.InvariantCulture, typeof(OverflowException) }; // negative overflowing d + h + m + s +f yield return new object[] { "00:00:60", null, typeof(OverflowException) }; // overflowing seconds yield return new object[] { "00:60:00", null, typeof(OverflowException) }; // overflowing minutes yield return new object[] { "24:00", null, typeof(OverflowException) }; // overflowing hours } [Theory] [MemberData(nameof(Parse_Invalid_TestData))] public static void Parse_Invalid(string input, IFormatProvider provider, Type exceptionType) { TimeSpan result; if (provider == null) { Assert.False(TimeSpan.TryParse(input, out result)); Assert.Equal(TimeSpan.Zero, result); Assert.Throws(exceptionType, () => TimeSpan.Parse(input)); } Assert.False(TimeSpan.TryParse(input, provider, out result)); Assert.Equal(TimeSpan.Zero, result); Assert.Throws(exceptionType, () => TimeSpan.Parse(input, provider)); } public static IEnumerable<object[]> ParseExact_Valid_TestData() { // Standard timespan formats 'c', 'g', 'G' foreach (string constFormat in new[] { "c", "t", "T" }) // "t" and "T" are the same as "c" { yield return new object[] { "12:24:02", constFormat, new TimeSpan(0, 12, 24, 2) }; // HH:MM:SS yield return new object[] { "1.12:24:02", constFormat, new TimeSpan(1, 12, 24, 2) }; // DD.HH:MM:SS yield return new object[] { "-01.07:45:16.999", constFormat, -new TimeSpan(1, 7, 45, 16, 999) }; // -DD.HH:MM:SS.FFF } // "g" yield return new object[] { "12", "g", new TimeSpan(12, 0, 0, 0) }; // days yield return new object[] { "-12", "g", new TimeSpan(-12, 0, 0, 0) }; // negative days yield return new object[] { "12:34", "g", new TimeSpan(12, 34, 00) }; // HH:MM yield return new object[] { "-12:34", "g", -new TimeSpan(12, 34, 00) }; // -HH:MM yield return new object[] { "1:2:.3", "g", new TimeSpan(0, 1, 2, 0, 300) }; // HH:MM:.FF yield return new object[] { "-1:2:.3", "g", -new TimeSpan(0, 1, 2, 0, 300) }; // -HH:MM:.FF yield return new object[] { "12:24:02", "g", new TimeSpan(0, 12, 24, 2) }; // HH:MM:SS yield return new object[] { "12:24:02.123", "g", new TimeSpan(0, 12, 24, 2, 123) }; // HH:MM:SS.FFF yield return new object[] { "-12:24:02.123", "g", -new TimeSpan(0, 12, 24, 2, 123) }; // -HH:MM:SS.FFF yield return new object[] { "1:2:3:.4", "g", new TimeSpan(1, 2, 3, 0, 400) }; // DD:HH:MM:.FF yield return new object[] { "-1:2:3:.4", "g", -new TimeSpan(1, 2, 3, 0, 400) }; // -DD:HH:MM:.FF yield return new object[] { "1:12:24:02", "g", new TimeSpan(1, 12, 24, 2) }; // DD:HH:MM:SS yield return new object[] { "-01:07:45:16.999", "g", -new TimeSpan(1, 7, 45, 16, 999) }; // -DD:HH:MM:SS.FFF // "G" yield return new object[] { "1:12:24:02.243", "G", new TimeSpan(1, 12, 24, 2, 243) }; // DD:MM:HH:SS.FFF yield return new object[] { "-01:07:45:16.999", "G", -new TimeSpan(1, 7, 45, 16, 999) }; // -DD:MM:HH:SS.FFF // Custom timespan formats yield return new object[] { "12.23:32:43", @"dd\.h\:m\:s", new TimeSpan(12, 23, 32, 43) }; yield return new object[] { "012.23:32:43.893", @"ddd\.h\:m\:s\.fff", new TimeSpan(12, 23, 32, 43, 893) }; yield return new object[] { "12.05:02:03", @"d\.hh\:mm\:ss", new TimeSpan(12, 5, 2, 3) }; yield return new object[] { "12:34 minutes", @"mm\:ss\ \m\i\n\u\t\e\s", new TimeSpan(0, 12, 34) }; yield return new object[] { "12:34 minutes", @"mm\:ss\ ""minutes""", new TimeSpan(0, 12, 34) }; yield return new object[] { "12:34 minutes", @"mm\:ss\ 'minutes'", new TimeSpan(0, 12, 34) }; yield return new object[] { "678", "fff", new TimeSpan(0, 0, 0, 0, 678) }; yield return new object[] { "678", "FFF", new TimeSpan(0, 0, 0, 0, 678) }; yield return new object[] { "3", "%d", new TimeSpan(3, 0, 0, 0, 0) }; yield return new object[] { "3", "%h", new TimeSpan(3, 0, 0) }; yield return new object[] { "3", "%m", new TimeSpan(0, 3, 0) }; yield return new object[] { "3", "%s", new TimeSpan(0, 0, 3) }; yield return new object[] { "3", "%f", new TimeSpan(0, 0, 0, 0, 300) }; yield return new object[] { "3", "%F", new TimeSpan(0, 0, 0, 0, 300) }; } [Theory] [MemberData(nameof(ParseExact_Valid_TestData))] public static void ParseExact(string input, string format, TimeSpan expected) { TimeSpan result; Assert.Equal(expected, TimeSpan.ParseExact(input, format, new CultureInfo("en-US"))); Assert.Equal(expected, TimeSpan.ParseExact(input, format, new CultureInfo("en-US"), TimeSpanStyles.None)); Assert.Equal(expected, TimeSpan.ParseExact(input, new[] { format }, new CultureInfo("en-US"))); Assert.Equal(expected, TimeSpan.ParseExact(input, new[] { format }, new CultureInfo("en-US"), TimeSpanStyles.None)); Assert.True(TimeSpan.TryParseExact(input, format, new CultureInfo("en-US"), out result)); Assert.Equal(expected, result); Assert.True(TimeSpan.TryParseExact(input, format, new CultureInfo("en-US"), TimeSpanStyles.None, out result)); Assert.Equal(expected, result); Assert.True(TimeSpan.TryParseExact(input, new[] { format }, new CultureInfo("en-US"), out result)); Assert.Equal(expected, result); Assert.True(TimeSpan.TryParseExact(input, new[] { format }, new CultureInfo("en-US"), TimeSpanStyles.None, out result)); Assert.Equal(expected, result); if (format != "c" && format != "t" && format != "T" && format != "g" && format != "G") { // TimeSpanStyles is interpreted only for custom formats Assert.Equal(expected.Negate(), TimeSpan.ParseExact(input, format, new CultureInfo("en-US"), TimeSpanStyles.AssumeNegative)); Assert.Equal(expected.Negate(), TimeSpan.ParseExact(input, new string[] { format }, new CultureInfo("en-US"), TimeSpanStyles.AssumeNegative)); Assert.True(TimeSpan.TryParseExact(input, format, new CultureInfo("en-US"), TimeSpanStyles.AssumeNegative, out result)); Assert.Equal(expected.Negate(), result); Assert.True(TimeSpan.TryParseExact(input, new string[] { format }, new CultureInfo("en-US"), TimeSpanStyles.AssumeNegative, out result)); Assert.Equal(expected.Negate(), result); } else { // Inputs that can be parsed in standard formats with ParseExact should also be parsable with Parse Assert.Equal(expected, TimeSpan.Parse(input, CultureInfo.InvariantCulture)); Assert.True(TimeSpan.TryParse(input, CultureInfo.InvariantCulture, out result)); Assert.Equal(expected, result); } } public static IEnumerable<object[]> ParseExact_Invalid_TestData() { yield return new object[] { null, "c", typeof(ArgumentNullException) }; yield return new object[] { "00:00:00", null, typeof(ArgumentNullException) }; yield return new object[] { "", "c", typeof(FormatException) }; yield return new object[] { "-", "c", typeof(FormatException) }; yield return new object[] { "garbage", "c", typeof(FormatException) }; // Standard timespan formats 'c', 'g', 'G' yield return new object[] { "24:24:02", "c", typeof(OverflowException) }; yield return new object[] { "1:60:02", "c", typeof(OverflowException) }; yield return new object[] { "1:59:60", "c", typeof(OverflowException) }; yield return new object[] { "1.24:59:02", "c", typeof(OverflowException) }; yield return new object[] { "1.2:60:02", "c", typeof(OverflowException) }; yield return new object[] { "1?59:02", "c", typeof(FormatException) }; yield return new object[] { "1:59?02", "c", typeof(FormatException) }; yield return new object[] { "1:59:02?123", "c", typeof(FormatException) }; yield return new object[] { "1:12:24:02", "c", typeof(FormatException) }; yield return new object[] { "12:61:02", "g", typeof(OverflowException) }; yield return new object[] { "1.12:24:02", "g", typeof(FormatException) }; yield return new object[] { "1:07:45:16.99999999", "G", typeof(OverflowException) }; yield return new object[] { "1:12:24:02", "G", typeof(FormatException) }; // Custom timespan formats yield return new object[] { "12.35:32:43", @"dd\.h\:m\:s", typeof(OverflowException) }; yield return new object[] { "12.5:2:3", @"d\.hh\:mm\:ss", typeof(FormatException) }; yield return new object[] { "12.5:2", @"d\.hh\:mm\:ss", typeof(FormatException) }; yield return new object[] { "678", @"ffff", typeof(FormatException) }; yield return new object[] { "00000012", @"FFFFFFFF", typeof(FormatException) }; yield return new object[] { "12:034:56", @"hh\mm\ss", typeof(FormatException) }; yield return new object[] { "12:34:056", @"hh\mm\ss", typeof(FormatException) }; yield return new object[] { "12:34 minutes", @"mm\:ss\ ""minutes", typeof(FormatException) }; yield return new object[] { "12:34 minutes", @"mm\:ss\ 'minutes", typeof(FormatException) }; yield return new object[] { "12:34 mints", @"mm\:ss\ ""minutes""", typeof(FormatException) }; yield return new object[] { "12:34 mints", @"mm\:ss\ 'minutes'", typeof(FormatException) }; yield return new object[] { "1", @"d%", typeof(FormatException) }; yield return new object[] { "1", @"%%d", typeof(FormatException) }; yield return new object[] { "12:34:56", @"hhh\:mm\:ss", typeof(FormatException) }; yield return new object[] { "12:34:56", @"hh\:hh\:ss", typeof(FormatException) }; yield return new object[] { "123:34:56", @"hh\:mm\:ss", typeof(FormatException) }; yield return new object[] { "12:34:56", @"hh\:mmm\:ss", typeof(FormatException) }; yield return new object[] { "12:34:56", @"hh\:mm\:mm", typeof(FormatException) }; yield return new object[] { "12:345:56", @"hh\:mm\:ss", typeof(FormatException) }; yield return new object[] { "12:34:56", @"hh\:mm\:sss", typeof(FormatException) }; yield return new object[] { "12:34:56", @"hh\:ss\:ss", typeof(FormatException) }; yield return new object[] { "12:45", @"ff:ff", typeof(FormatException) }; yield return new object[] { "000000123", @"ddddddddd", typeof(FormatException) }; yield return new object[] { "12:34:56", @"dd:dd:hh", typeof(FormatException) }; yield return new object[] { "123:45", @"dd:hh", typeof(FormatException) }; yield return new object[] { "12:34", @"dd:vv", typeof(FormatException) }; yield return new object[] { "00:00:00", "", typeof(FormatException) }; yield return new object[] { "12.5:2", @"V", typeof(FormatException) }; } [Theory] [MemberData(nameof(ParseExact_Invalid_TestData))] public static void ParseExactTest_Invalid(string input, string format, Type exceptionType) { Assert.Throws(exceptionType, () => TimeSpan.ParseExact(input, format, new CultureInfo("en-US"))); Assert.Throws(exceptionType, () => TimeSpan.ParseExact(input, format, new CultureInfo("en-US"), TimeSpanStyles.None)); Type exceptionTypeMultiple = exceptionType == typeof(OverflowException) || string.IsNullOrEmpty(format) ? typeof(FormatException) : exceptionType; Assert.Throws(exceptionTypeMultiple, () => TimeSpan.ParseExact(input, new string[] { format }, new CultureInfo("en-US"))); Assert.Throws(exceptionTypeMultiple, () => TimeSpan.ParseExact(input, new string[] { format }, new CultureInfo("en-US"), TimeSpanStyles.None)); TimeSpan result; Assert.False(TimeSpan.TryParseExact(input, format, new CultureInfo("en-US"), out result)); Assert.Equal(TimeSpan.Zero, result); Assert.False(TimeSpan.TryParseExact(input, format, new CultureInfo("en-US"), TimeSpanStyles.None, out result)); Assert.Equal(TimeSpan.Zero, result); Assert.False(TimeSpan.TryParseExact(input, new[] { format }, new CultureInfo("en-US"), out result)); Assert.Equal(TimeSpan.Zero, result); Assert.False(TimeSpan.TryParseExact(input, new[] { format }, new CultureInfo("en-US"), TimeSpanStyles.None, out result)); Assert.Equal(TimeSpan.Zero, result); } [Fact] public static void ParseExactMultiple_InvalidNullEmptyFormats() { TimeSpan result; AssertExtensions.Throws<ArgumentNullException>("formats", () => TimeSpan.ParseExact("12:34:56", (string[])null, null)); Assert.False(TimeSpan.TryParseExact("12:34:56", (string[])null, null, out result)); Assert.Throws<FormatException>(() => TimeSpan.ParseExact("12:34:56", new string[0], null)); Assert.False(TimeSpan.TryParseExact("12:34:56", new string[0], null, out result)); } public static IEnumerable<object[]> ParseExact_InvalidStyles_TestData() { yield return new object[] { TimeSpanStyles.None - 1 }; yield return new object[] { TimeSpanStyles.AssumeNegative + 1 }; } [Theory] [MemberData(nameof(ParseExact_InvalidStyles_TestData))] public void ParseExact_InvalidStyles_ThrowsArgumentException(TimeSpanStyles styles) { TimeSpan result; string inputString = "00:00:00"; AssertExtensions.Throws<ArgumentException>("styles", () => TimeSpan.ParseExact(inputString, "s", new CultureInfo("en-US"), styles)); AssertExtensions.Throws<ArgumentException>("styles", () => TimeSpan.ParseExact(inputString, new string[] { "s" }, new CultureInfo("en-US"), styles)); AssertExtensions.Throws<ArgumentException>("styles", () => TimeSpan.TryParseExact(inputString, "s", new CultureInfo("en-US"), styles, out result)); AssertExtensions.Throws<ArgumentException>("styles", () => TimeSpan.TryParseExact(inputString, new string[] { "s" }, new CultureInfo("en-US"), styles, out result)); } public static IEnumerable<object[]> Parse_ValidWithOffsetCount_TestData() { foreach (object[] inputs in Parse_Valid_TestData()) { yield return new object[] { inputs[0], 0, ((string)inputs[0]).Length, inputs[1], inputs[2] }; } yield return new object[] { " 12:24:02 ", 5, 8, null, new TimeSpan(0, 12, 24, 2, 0) }; yield return new object[] { " 12:24:02 ", 6, 7, null, new TimeSpan(0, 2, 24, 2, 0) }; yield return new object[] { " 12:24:02 ", 6, 6, null, new TimeSpan(0, 2, 24, 0, 0) }; yield return new object[] { "12:24:02.01", 0, 8, CultureInfo.InvariantCulture, new TimeSpan(0, 12, 24, 2, 0) }; yield return new object[] { "1:1:1.00000001", 0, 7, CultureInfo.InvariantCulture, new TimeSpan(1, 1, 1) }; yield return new object[] { "1:1:.00000001", 0, 6, CultureInfo.InvariantCulture, new TimeSpan(36600000000) }; yield return new object[] { "24:00:00", 1, 7, null, new TimeSpan(4, 0, 0) }; } [Theory] [MemberData(nameof(Parse_ValidWithOffsetCount_TestData))] public static void Parse_Span(string inputString, int offset, int count, IFormatProvider provider, TimeSpan expected) { ReadOnlySpan<char> input = inputString.AsSpan(offset, count); TimeSpan result; // Default provider. if (provider == null) { Assert.True(TimeSpan.TryParse(input, out result)); Assert.Equal(expected, result); } Assert.Equal(expected, TimeSpan.Parse(input, provider)); Assert.True(TimeSpan.TryParse(input, provider, out result)); Assert.Equal(expected, result); // Also negate if (!char.IsWhiteSpace(input[0])) { input = ("-" + inputString.Substring(offset, count)).AsSpan(); expected = -expected; Assert.Equal(expected, TimeSpan.Parse(input, provider)); Assert.True(TimeSpan.TryParse(input, provider, out result)); Assert.Equal(expected, result); } } [Theory] [MemberData(nameof(Parse_Invalid_TestData))] public static void Parse_Span_Invalid(string inputString, IFormatProvider provider, Type exceptionType) { if (inputString != null) { Assert.Throws(exceptionType, () => TimeSpan.Parse(inputString.AsSpan(), provider)); Assert.False(TimeSpan.TryParse(inputString.AsSpan(), provider, out TimeSpan result)); Assert.Equal(TimeSpan.Zero, result); } } [Theory] [MemberData(nameof(ParseExact_Valid_TestData))] public static void ParseExact_Span_Valid(string inputString, string format, TimeSpan expected) { ReadOnlySpan<char> input = inputString.AsSpan(); TimeSpan result; Assert.Equal(expected, TimeSpan.ParseExact(input, format, new CultureInfo("en-US"))); Assert.Equal(expected, TimeSpan.ParseExact(input, format, new CultureInfo("en-US"), TimeSpanStyles.None)); Assert.Equal(expected, TimeSpan.ParseExact(input, new[] { format }, new CultureInfo("en-US"))); Assert.Equal(expected, TimeSpan.ParseExact(input, new[] { format }, new CultureInfo("en-US"), TimeSpanStyles.None)); Assert.True(TimeSpan.TryParseExact(input, format, new CultureInfo("en-US"), out result)); Assert.Equal(expected, result); Assert.True(TimeSpan.TryParseExact(input, format, new CultureInfo("en-US"), TimeSpanStyles.None, out result)); Assert.Equal(expected, result); Assert.True(TimeSpan.TryParseExact(input, new[] { format }, new CultureInfo("en-US"), out result)); Assert.Equal(expected, result); Assert.True(TimeSpan.TryParseExact(input, new[] { format }, new CultureInfo("en-US"), TimeSpanStyles.None, out result)); Assert.Equal(expected, result); if (format != "c" && format != "t" && format != "T" && format != "g" && format != "G") { // TimeSpanStyles is interpreted only for custom formats Assert.Equal(expected.Negate(), TimeSpan.ParseExact(input, format, new CultureInfo("en-US"), TimeSpanStyles.AssumeNegative)); Assert.True(TimeSpan.TryParseExact(input, format, new CultureInfo("en-US"), TimeSpanStyles.AssumeNegative, out result)); Assert.Equal(expected.Negate(), result); } else { // Inputs that can be parsed in standard formats with ParseExact should also be parsable with Parse Assert.Equal(expected, TimeSpan.Parse(input, CultureInfo.InvariantCulture)); Assert.True(TimeSpan.TryParse(input, CultureInfo.InvariantCulture, out result)); Assert.Equal(expected, result); } } [Theory] [MemberData(nameof(ParseExact_Invalid_TestData))] public static void ParseExactTest_Span_Invalid(string inputString, string format, Type exceptionType) { if (inputString != null && format != null) { Assert.Throws(exceptionType, () => TimeSpan.ParseExact(inputString.AsSpan(), format, new CultureInfo("en-US"))); TimeSpan result; Assert.False(TimeSpan.TryParseExact(inputString.AsSpan(), format, new CultureInfo("en-US"), out result)); Assert.Equal(TimeSpan.Zero, result); Assert.False(TimeSpan.TryParseExact(inputString.AsSpan(), format, new CultureInfo("en-US"), TimeSpanStyles.None, out result)); Assert.Equal(TimeSpan.Zero, result); Assert.False(TimeSpan.TryParseExact(inputString.AsSpan(), new[] { format }, new CultureInfo("en-US"), out result)); Assert.Equal(TimeSpan.Zero, result); Assert.False(TimeSpan.TryParseExact(inputString.AsSpan(), new[] { format }, new CultureInfo("en-US"), TimeSpanStyles.None, out result)); Assert.Equal(TimeSpan.Zero, result); } } [Fact] public static void ParseExactMultiple_Span_InvalidNullEmptyFormats() { TimeSpan result; AssertExtensions.Throws<ArgumentNullException>("formats", () => TimeSpan.ParseExact("12:34:56".AsSpan(), (string[])null, null)); Assert.False(TimeSpan.TryParseExact("12:34:56".AsSpan(), (string[])null, null, out result)); Assert.Throws<FormatException>(() => TimeSpan.ParseExact("12:34:56".AsSpan(), new string[0], null)); Assert.False(TimeSpan.TryParseExact("12:34:56".AsSpan(), new string[0], null, out result)); } [Theory] [MemberData(nameof(ParseExact_InvalidStyles_TestData))] public void ParseExact_InvalidStylesSpan_ThrowsArgumentException(TimeSpanStyles styles) { TimeSpan result; string inputString = "00:00:00"; AssertExtensions.Throws<ArgumentException>("styles", () => TimeSpan.ParseExact(inputString.AsSpan(), "s", new CultureInfo("en-US"), styles)); AssertExtensions.Throws<ArgumentException>("styles", () => TimeSpan.ParseExact(inputString.AsSpan(), new string[] { "s" }, new CultureInfo("en-US"), styles)); AssertExtensions.Throws<ArgumentException>("styles", () => TimeSpan.TryParseExact(inputString.AsSpan(), "s", new CultureInfo("en-US"), styles, out result)); AssertExtensions.Throws<ArgumentException>("styles", () => TimeSpan.TryParseExact(inputString.AsSpan(), new string[] { "s" }, new CultureInfo("en-US"), styles, out result)); } public static IEnumerable<object[]> Subtract_TestData() { yield return new object[] { new TimeSpan(0, 0, 0), new TimeSpan(1, 2, 3), new TimeSpan(-1, -2, -3) }; yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(4, 5, 6), new TimeSpan(-3, -3, -3) }; yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(-4, -5, -6), new TimeSpan(5, 7, 9) }; yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 3), new TimeSpan(1, 1, 1, 1, 5) }; yield return new object[] { new TimeSpan(10, 11, 12, 13, 14), new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(9, 9, 9, 9, 9) }; yield return new object[] { new TimeSpan(200000), new TimeSpan(10000), new TimeSpan(190000) }; } [Theory] [MemberData(nameof(Subtract_TestData))] public static void Subtract(TimeSpan ts1, TimeSpan ts2, TimeSpan expected) { Assert.Equal(expected, ts1.Subtract(ts2)); Assert.Equal(expected, ts1 - ts2); } [Fact] public static void Subtract_Invalid() { Assert.Throws<OverflowException>(() => TimeSpan.MaxValue.Subtract(new TimeSpan(-1))); // Result > TimeSpan.MaxValue Assert.Throws<OverflowException>(() => TimeSpan.MinValue.Subtract(new TimeSpan(1))); // Result < TimeSpan.MinValue Assert.Throws<OverflowException>(() => TimeSpan.MaxValue - new TimeSpan(-1)); // Result > TimeSpan.MaxValue Assert.Throws<OverflowException>(() => TimeSpan.MinValue - new TimeSpan(1)); // Result < TimeSpan.MinValue } public static IEnumerable<object[]> ToString_TestData() { CultureInfo invariantInfo = CultureInfo.InvariantCulture; CultureInfo commaSeparatorInfo = new CultureInfo("fr-FR"); commaSeparatorInfo.NumberFormat.NegativeSign = "!@#!@#"; // validate this is ignored var input = new TimeSpan(123456789101112); yield return new object[] { input, "%d", invariantInfo, "142" }; yield return new object[] { input, "dd", invariantInfo, "142" }; yield return new object[] { input, "%h", invariantInfo, "21" }; yield return new object[] { input, "hh", invariantInfo, "21" }; yield return new object[] { input, "%m", invariantInfo, "21" }; yield return new object[] { input, "mm", invariantInfo, "21" }; yield return new object[] { input, "%s", invariantInfo, "18" }; yield return new object[] { input, "ss", invariantInfo, "18" }; yield return new object[] { input, "%f", invariantInfo, "9" }; yield return new object[] { input, "ff", invariantInfo, "91" }; yield return new object[] { input, "fff", invariantInfo, "910" }; yield return new object[] { input, "ffff", invariantInfo, "9101" }; yield return new object[] { input, "fffff", invariantInfo, "91011" }; yield return new object[] { input, "ffffff", invariantInfo, "910111" }; yield return new object[] { input, "fffffff", invariantInfo, "9101112" }; yield return new object[] { input, "%F", invariantInfo, "9" }; yield return new object[] { input, "FF", invariantInfo, "91" }; yield return new object[] { input, "FFF", invariantInfo, "91" }; yield return new object[] { input, "FFFF", invariantInfo, "9101" }; yield return new object[] { input, "FFFFF", invariantInfo, "91011" }; yield return new object[] { input, "FFFFFF", invariantInfo, "910111" }; yield return new object[] { input, "FFFFFFF", invariantInfo, "9101112" }; yield return new object[] { input, "dd\\.ss", invariantInfo, "142.18" }; yield return new object[] { input, "dd\\.ss", commaSeparatorInfo, "142.18" }; yield return new object[] { input, "dddddd\\.ss", invariantInfo, "000142.18" }; // constant/invariant format CultureInfo[] cultureInfos = PlatformDetection.IsInvariantGlobalization ? new[] { (CultureInfo)null } : new[] { null, invariantInfo, commaSeparatorInfo }; foreach (CultureInfo info in cultureInfos) // validate that culture is ignored { foreach (string constFormat in new[] { null, "c", "t", "T" }) { yield return new object[] { input, constFormat, info, "142.21:21:18.9101112" }; yield return new object[] { TimeSpan.Zero, constFormat, info, "00:00:00" }; yield return new object[] { new TimeSpan(1), constFormat, info, "00:00:00.0000001" }; yield return new object[] { new TimeSpan(-1), constFormat, info, "-00:00:00.0000001" }; yield return new object[] { TimeSpan.MaxValue, constFormat, info, "10675199.02:48:05.4775807" }; yield return new object[] { TimeSpan.MinValue, constFormat, info, "-10675199.02:48:05.4775808" }; yield return new object[] { new TimeSpan(1, 2, 3), constFormat, info, "01:02:03" }; yield return new object[] { -new TimeSpan(1, 2, 3), constFormat, info, "-01:02:03" }; yield return new object[] { new TimeSpan(12, 34, 56), constFormat, info, "12:34:56" }; yield return new object[] { new TimeSpan(12, 34, 56, 23), constFormat, info, "13.10:56:23" }; yield return new object[] { new TimeSpan(12, 34, 56, 23, 45), constFormat, info, "13.10:56:23.0450000" }; yield return new object[] { new TimeSpan(0, 23, 59, 59, 999), constFormat, info, "23:59:59.9990000" }; } } // general short format, invariant culture yield return new object[] { input, "g", invariantInfo, "142:21:21:18.9101112" }; yield return new object[] { TimeSpan.Zero, "g", invariantInfo, "0:00:00" }; yield return new object[] { new TimeSpan(1), "g", invariantInfo, "0:00:00.0000001" }; yield return new object[] { new TimeSpan(-1), "g", invariantInfo, "-0:00:00.0000001" }; yield return new object[] { TimeSpan.MaxValue, "g", invariantInfo, "10675199:2:48:05.4775807" }; yield return new object[] { TimeSpan.MinValue, "g", invariantInfo, "-10675199:2:48:05.4775808" }; yield return new object[] { new TimeSpan(1, 2, 3), "g", invariantInfo, "1:02:03" }; yield return new object[] { -new TimeSpan(1, 2, 3), "g", invariantInfo, "-1:02:03" }; yield return new object[] { new TimeSpan(12, 34, 56), "g", invariantInfo, "12:34:56" }; yield return new object[] { new TimeSpan(12, 34, 56, 23), "g", invariantInfo, "13:10:56:23" }; yield return new object[] { new TimeSpan(12, 34, 56, 23, 45), "g", invariantInfo, "13:10:56:23.045" }; yield return new object[] { new TimeSpan(0, 23, 59, 59, 999), "g", invariantInfo, "23:59:59.999" }; if (PlatformDetection.IsNotInvariantGlobalization) { // general short format, NumberDecimalSeparator used yield return new object[] { input, "g", commaSeparatorInfo, "142:21:21:18,9101112" }; yield return new object[] { TimeSpan.Zero, "g", commaSeparatorInfo, "0:00:00" }; yield return new object[] { new TimeSpan(1), "g", commaSeparatorInfo, "0:00:00,0000001" }; yield return new object[] { new TimeSpan(-1), "g", commaSeparatorInfo, "-0:00:00,0000001" }; yield return new object[] { TimeSpan.MaxValue, "g", commaSeparatorInfo, "10675199:2:48:05,4775807" }; yield return new object[] { TimeSpan.MinValue, "g", commaSeparatorInfo, "-10675199:2:48:05,4775808" }; yield return new object[] { new TimeSpan(1, 2, 3), "g", commaSeparatorInfo, "1:02:03" }; yield return new object[] { -new TimeSpan(1, 2, 3), "g", commaSeparatorInfo, "-1:02:03" }; yield return new object[] { new TimeSpan(12, 34, 56), "g", commaSeparatorInfo, "12:34:56" }; yield return new object[] { new TimeSpan(12, 34, 56, 23), "g", commaSeparatorInfo, "13:10:56:23" }; yield return new object[] { new TimeSpan(12, 34, 56, 23, 45), "g", commaSeparatorInfo, "13:10:56:23,045" }; yield return new object[] { new TimeSpan(0, 23, 59, 59, 999), "g", commaSeparatorInfo, "23:59:59,999" }; } // general long format, invariant culture yield return new object[] { input, "G", invariantInfo, "142:21:21:18.9101112" }; yield return new object[] { TimeSpan.Zero, "G", invariantInfo, "0:00:00:00.0000000" }; yield return new object[] { new TimeSpan(1), "G", invariantInfo, "0:00:00:00.0000001" }; yield return new object[] { new TimeSpan(-1), "G", invariantInfo, "-0:00:00:00.0000001" }; yield return new object[] { TimeSpan.MaxValue, "G", invariantInfo, "10675199:02:48:05.4775807" }; yield return new object[] { TimeSpan.MinValue, "G", invariantInfo, "-10675199:02:48:05.4775808" }; yield return new object[] { new TimeSpan(1, 2, 3), "G", invariantInfo, "0:01:02:03.0000000" }; yield return new object[] { -new TimeSpan(1, 2, 3), "G", invariantInfo, "-0:01:02:03.0000000" }; yield return new object[] { new TimeSpan(12, 34, 56), "G", invariantInfo, "0:12:34:56.0000000" }; yield return new object[] { new TimeSpan(12, 34, 56, 23), "G", invariantInfo, "13:10:56:23.0000000" }; yield return new object[] { new TimeSpan(12, 34, 56, 23, 45), "G", invariantInfo, "13:10:56:23.0450000" }; yield return new object[] { new TimeSpan(0, 23, 59, 59, 999), "G", invariantInfo, "0:23:59:59.9990000" }; if (PlatformDetection.IsNotInvariantGlobalization) { // general long format, NumberDecimalSeparator used yield return new object[] { input, "G", commaSeparatorInfo, "142:21:21:18,9101112" }; yield return new object[] { TimeSpan.Zero, "G", commaSeparatorInfo, "0:00:00:00,0000000" }; yield return new object[] { new TimeSpan(1), "G", commaSeparatorInfo, "0:00:00:00,0000001" }; yield return new object[] { new TimeSpan(-1), "G", commaSeparatorInfo, "-0:00:00:00,0000001" }; yield return new object[] { TimeSpan.MaxValue, "G", commaSeparatorInfo, "10675199:02:48:05,4775807" }; yield return new object[] { TimeSpan.MinValue, "G", commaSeparatorInfo, "-10675199:02:48:05,4775808" }; yield return new object[] { new TimeSpan(1, 2, 3), "G", commaSeparatorInfo, "0:01:02:03,0000000" }; yield return new object[] { -new TimeSpan(1, 2, 3), "G", commaSeparatorInfo, "-0:01:02:03,0000000" }; yield return new object[] { new TimeSpan(12, 34, 56), "G", commaSeparatorInfo, "0:12:34:56,0000000" }; yield return new object[] { new TimeSpan(12, 34, 56, 23), "G", commaSeparatorInfo, "13:10:56:23,0000000" }; yield return new object[] { new TimeSpan(12, 34, 56, 23, 45), "G", commaSeparatorInfo, "13:10:56:23,0450000" }; yield return new object[] { new TimeSpan(0, 23, 59, 59, 999), "G", commaSeparatorInfo, "0:23:59:59,9990000" }; } } [Theory] [MemberData(nameof(ToString_TestData))] public static void ToString_Valid(TimeSpan input, string format, CultureInfo info, string expected) { Assert.Equal(expected, input.ToString(format, info)); if (info == null) { Assert.Equal(expected, input.ToString(format)); if (format == null) { Assert.Equal(expected, input.ToString()); } } } public static IEnumerable<object[]> ToString_InvalidFormat_TestData() { yield return new object[] { "y" }; yield return new object[] { "cc" }; yield return new object[] { "F" }; yield return new object[] { "C" }; } [Theory] [MemberData(nameof(ToString_InvalidFormat_TestData))] public void ToString_InvalidFormat_ThrowsFormatException(string invalidFormat) { Assert.Throws<FormatException>(() => new TimeSpan().ToString(invalidFormat)); } private static void VerifyTimeSpan(TimeSpan timeSpan, int days, int hours, int minutes, int seconds, int milliseconds) { Assert.Equal(days, timeSpan.Days); Assert.Equal(hours, timeSpan.Hours); Assert.Equal(minutes, timeSpan.Minutes); Assert.Equal(seconds, timeSpan.Seconds); Assert.Equal(milliseconds, timeSpan.Milliseconds); Assert.Equal(timeSpan, +timeSpan); } private static void VerifyTimeSpan(TimeSpan timeSpan, int days, int hours, int minutes, int seconds, int milliseconds, int microseconds) { VerifyTimeSpan(timeSpan, days, hours, minutes, seconds, milliseconds); Assert.Equal(microseconds, timeSpan.Microseconds); } private static void VerifyTimeSpan(TimeSpan timeSpan, int days, int hours, int minutes, int seconds, int milliseconds, int microseconds, int nanoseconds) { VerifyTimeSpan(timeSpan, days, hours, minutes, seconds, milliseconds, microseconds); Assert.Equal(nanoseconds, timeSpan.Nanoseconds); } [Theory] [MemberData(nameof(CompareTo_TestData))] public static void CompareTo_Object(TimeSpan timeSpan1, object obj, int expected) { Assert.Equal(expected, Math.Sign(timeSpan1.CompareTo(obj))); } public static IEnumerable<object[]> MultiplicationTestData() { yield return new object[] {new TimeSpan(2, 30, 0), 2.0, new TimeSpan(5, 0, 0)}; yield return new object[] {new TimeSpan(14, 2, 30, 0), 192.0, TimeSpan.FromDays(2708)}; yield return new object[] {TimeSpan.FromDays(366), Math.PI, new TimeSpan(993446995288779)}; yield return new object[] {TimeSpan.FromDays(366), -Math.E, new TimeSpan(-859585952922633)}; yield return new object[] {TimeSpan.FromDays(29.530587981), 13.0, TimeSpan.FromDays(29.530587981 * 13.0) }; yield return new object[] {TimeSpan.FromDays(-29.530587981), -12.0, TimeSpan.FromDays(-29.530587981 * -12.0) }; yield return new object[] {TimeSpan.FromDays(-29.530587981), 0.0, TimeSpan.Zero}; yield return new object[] {TimeSpan.MaxValue, 0.5, TimeSpan.FromTicks((long)(long.MaxValue * 0.5))}; } // ParseDifferentLengthFractionWithLeadingZerosData mainly testing the behavior we have fixed in net core // which is the way we normalize the parsed fraction and possibly rounding it. public static IEnumerable<object[]> ParseDifferentLengthFractionWithLeadingZerosData() { yield return new object[] {"00:00:00.00000001", new TimeSpan(0)}; yield return new object[] {"00:00:00.00000005", new TimeSpan(1)}; yield return new object[] {"00:00:00.09999999", new TimeSpan(1_000_000)}; yield return new object[] {"00:00:00.0268435455", new TimeSpan(268435)}; yield return new object[] {"00:00:00.01", new TimeSpan(1_00_000)}; yield return new object[] {"0:00:00.01000000", new TimeSpan(100_000)}; yield return new object[] {"0:00:00.010000000", new TimeSpan(100_000)}; yield return new object[] {"0:00:00.0123456", new TimeSpan(123456)}; yield return new object[] {"0:00:00.00123456", new TimeSpan(12346)}; yield return new object[] {"0:00:00.00000098", new TimeSpan(10)}; yield return new object[] {"0:00:00.00000099", new TimeSpan(10)}; } [Theory, MemberData(nameof(ParseDifferentLengthFractionWithLeadingZerosData))] public static void ParseDifferentLengthFractionWithLeadingZeros(string input, TimeSpan expected) { Assert.Equal(expected, TimeSpan.Parse(input, CultureInfo.InvariantCulture)); Assert.Equal(expected, TimeSpan.ParseExact(input, "g", CultureInfo.InvariantCulture)); } [Theory, MemberData(nameof(MultiplicationTestData))] public static void Multiplication(TimeSpan timeSpan, double factor, TimeSpan expected) { Assert.Equal(expected, timeSpan * factor); Assert.Equal(expected, factor * timeSpan); } [Fact] public static void OverflowingMultiplication() { Assert.Throws<OverflowException>(() => TimeSpan.MaxValue * 1.000000001); Assert.Throws<OverflowException>(() => -1.000000001 * TimeSpan.MaxValue); } [Fact] public static void NaNMultiplication() { AssertExtensions.Throws<ArgumentException>("factor", () => TimeSpan.FromDays(1) * double.NaN); AssertExtensions.Throws<ArgumentException>("factor", () => double.NaN * TimeSpan.FromDays(1)); } [Theory, MemberData(nameof(MultiplicationTestData))] public static void Division(TimeSpan timeSpan, double factor, TimeSpan expected) { Assert.Equal(factor, expected / timeSpan, 14); double divisor = 1.0 / factor; Assert.Equal(expected, timeSpan / divisor); } [Fact] public static void DivideByZero() { Assert.Throws<OverflowException>(() => TimeSpan.FromDays(1) / 0); Assert.Throws<OverflowException>(() => TimeSpan.FromDays(-1) / 0); Assert.Throws<OverflowException>(() => TimeSpan.Zero / 0); Assert.Equal(double.PositiveInfinity, TimeSpan.FromDays(1) / TimeSpan.Zero); Assert.Equal(double.NegativeInfinity, TimeSpan.FromDays(-1) / TimeSpan.Zero); Assert.True(double.IsNaN(TimeSpan.Zero / TimeSpan.Zero)); } [Fact] public static void NaNDivision() { AssertExtensions.Throws<ArgumentException>("divisor", () => TimeSpan.FromDays(1) / double.NaN); } [Theory, MemberData(nameof(MultiplicationTestData))] public static void NamedMultiplication(TimeSpan timeSpan, double factor, TimeSpan expected) { Assert.Equal(expected, timeSpan.Multiply(factor)); } [Fact] public static void NamedOverflowingMultiplication() { Assert.Throws<OverflowException>(() => TimeSpan.MaxValue.Multiply(1.000000001)); } [Fact] public static void NamedNaNMultiplication() { AssertExtensions.Throws<ArgumentException>("factor", () => TimeSpan.FromDays(1).Multiply(double.NaN)); } [Theory, MemberData(nameof(MultiplicationTestData))] public static void NamedDivision(TimeSpan timeSpan, double factor, TimeSpan expected) { Assert.Equal(factor, expected.Divide(timeSpan), 14); double divisor = 1.0 / factor; Assert.Equal(expected, timeSpan.Divide(divisor)); } [Fact] public static void NamedDivideByZero() { Assert.Throws<OverflowException>(() => TimeSpan.FromDays(1).Divide(0)); Assert.Throws<OverflowException>(() => TimeSpan.FromDays(-1).Divide(0)); Assert.Throws<OverflowException>(() => TimeSpan.Zero.Divide(0)); Assert.Equal(double.PositiveInfinity, TimeSpan.FromDays(1).Divide(TimeSpan.Zero)); Assert.Equal(double.NegativeInfinity, TimeSpan.FromDays(-1).Divide(TimeSpan.Zero)); Assert.True(double.IsNaN(TimeSpan.Zero.Divide(TimeSpan.Zero))); } [Fact] public static void NamedNaNDivision() { AssertExtensions.Throws<ArgumentException>("divisor", () => TimeSpan.FromDays(1).Divide(double.NaN)); } [Theory] [MemberData(nameof(ToString_TestData))] public static void TryFormat_Valid(TimeSpan input, string format, CultureInfo info, string expected) { int charsWritten; Span<char> dst; dst = new char[expected.Length - 1]; Assert.False(input.TryFormat(dst, out charsWritten, format, info)); Assert.Equal(0, charsWritten); dst = new char[expected.Length]; Assert.True(input.TryFormat(dst, out charsWritten, format, info)); Assert.Equal(expected.Length, charsWritten); Assert.Equal(expected, new string(dst)); dst = new char[expected.Length + 1]; Assert.True(input.TryFormat(dst, out charsWritten, format, info)); Assert.Equal(expected.Length, charsWritten); Assert.Equal(expected, new string(dst.Slice(0, dst.Length - 1))); Assert.Equal(0, dst[dst.Length - 1]); } [Theory] [MemberData(nameof(ToString_InvalidFormat_TestData))] public void TryFormat_InvalidFormat_ThrowsFormatException(string invalidFormat) { char[] dst = new char[1]; Assert.Throws<FormatException>(() => new TimeSpan().TryFormat(dst.AsSpan(), out int charsWritten, invalidFormat, null)); } [Fact] public static void ConvertToTimeSpanPrecisionTest() { Assert.Equal(12345, TimeSpan.FromMilliseconds(1.23456).Ticks); Assert.Equal(12345, TimeSpan.FromMilliseconds(1.234567).Ticks); Assert.Equal(12345600, TimeSpan.FromSeconds(1.23456).Ticks); Assert.Equal(1.23456 * 60 * 10_000_000, TimeSpan.FromMinutes(1.23456).Ticks); } [Theory] [InlineData(0, 0)] [InlineData(100, 10)] [InlineData(1_000, 100)] public static void TestTotalMicroseconds(long ticks, double totalMicroseconds) { var timeSpan = new TimeSpan(ticks); Assert.Equal(totalMicroseconds, timeSpan.TotalMicroseconds); } [Theory] [InlineData(0, 0)] [InlineData(100, 10_000)] [InlineData(1_000, 100_000)] public static void TestTotalNanoseconds(long ticks, double totalNanoseconds) { var timeSpan = new TimeSpan(ticks); Assert.Equal(totalNanoseconds, timeSpan.TotalNanoseconds); } } }
57.952156
211
0.596144
[ "MIT" ]
AlexanderSemenyak/runtime
src/libraries/System.Runtime/tests/System/TimeSpanTests.cs
86,001
C#
using System; using System.Collections.Generic; using System.Linq; namespace _10._SoftUni_Exam_Results { internal class Program { static void Main(string[] args) { Dictionary<string, int> languageAndSubmitions = new Dictionary<string, int>(); Dictionary<string, int> usersAndPoints = new Dictionary<string, int>(); string inputLine = Console.ReadLine(); while (inputLine != "exam finished") { string[] inputArr = inputLine.Split('-', StringSplitOptions.RemoveEmptyEntries).ToArray(); string user = inputArr[0]; if (inputArr[1] != "banned") { string language = inputArr[1]; int poits = int.Parse(inputArr[2]); if (!usersAndPoints.ContainsKey(user)) { usersAndPoints.Add(user, 0); } if (poits > usersAndPoints[user]) { usersAndPoints[user] = poits; } if (!languageAndSubmitions.ContainsKey(language)) { languageAndSubmitions.Add(language, 0); } languageAndSubmitions[language]++; } else { if (usersAndPoints.ContainsKey(user)) { usersAndPoints.Remove(user); } } inputLine = Console.ReadLine(); } Console.WriteLine("Results:"); foreach (var user in usersAndPoints.OrderByDescending(user => user.Value).ThenBy(user => user.Key)) { Console.WriteLine($"{user.Key} | {user.Value}"); } Console.WriteLine($"Submissions:"); foreach (var langiage in languageAndSubmitions.OrderByDescending(langiage => langiage.Value).ThenBy(langiage => langiage.Key)) { Console.WriteLine($"{langiage.Key} - {langiage.Value}"); } } } }
37.689655
138
0.480787
[ "MIT" ]
dimitarLaleksandrov/first-steps-in-coding-C-
Homework/Fundamentals whit C#/25. Associative Arrays Exercise/10. SoftUni Exam Results/Program.cs
2,188
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HBaseManagementStudio { public class HexOperator { public static byte[] FromHexString(string hex) { return Enumerable.Range(0, hex.Length) .Where(x => x % 2 == 0) .Select(x => Convert.ToByte(hex.Substring(x, 2), 16)) .ToArray(); } public static string ToHexString(byte[] bytes) { return BitConverter.ToString(bytes).Replace("-", ""); } } }
24.64
74
0.558442
[ "Apache-2.0" ]
zhengyangyong/HBaseManagementStudio
HBaseManagementStudio/Operator/HexOperator.cs
618
C#
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using UniLife.Shared.DataModels; using UniLife.Storage; namespace UniLife.Server.Controllers { public class DersDilsController : ControllerBase { private readonly IApplicationDbContext _applicationDbContext; public DersDilsController(IApplicationDbContext applicationDbContext) { _applicationDbContext = applicationDbContext; } [Microsoft.AspNet.OData.EnableQuery()] [HttpGet] [Authorize] public IEnumerable<DersDil> Get() { return _applicationDbContext.DersDils; } } }
24.964286
77
0.69814
[ "MIT" ]
ahmetsekmen/UniLife
src/UniLife.Server/Controllers/OData/DersDilsController.cs
701
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Css.Parser.Parser { public interface ICssParserFactory { ICssParser CreateParser(); } public class DefaultParserFactory : ICssParserFactory { public ICssParser CreateParser() { return new CssParser(); } } }
22.789474
95
0.662818
[ "MIT" ]
dotnet/cssparser
src/Microsoft.Css.Parser/Parser/CssParserFactory.cs
433
C#
using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace ExchangeSharp { public sealed partial class ExchangeFTXAPI : ExchangeAPI { public override string BaseUrl { get; set; } = "https://ftx.com/api"; public override string BaseUrlWebSocket { get; set; } = "wss://ftx.com/ws/"; #region [ Constructor(s) ] public ExchangeFTXAPI() { NonceStyle = NonceStyle.UnixMillisecondsString; MarketSymbolSeparator = "/"; RequestContentType = "application/json"; } #endregion #region [ Implementation ] /// <inheritdoc /> protected async override Task OnCancelOrderAsync(string orderId, string marketSymbol = null) { await MakeJsonRequestAsync<JToken>($"/orders/{orderId}", null, await GetNoncePayloadAsync(), "DELETE"); } /// <inheritdoc /> protected async override Task<Dictionary<string, decimal>> OnGetAmountsAsync() { var balances = new Dictionary<string, decimal>(); JToken result = await MakeJsonRequestAsync<JToken>("/wallet/balances", null, await GetNoncePayloadAsync()); foreach (JObject obj in result) { decimal amount = obj["total"].ConvertInvariant<decimal>(); balances[obj["coin"].ToStringInvariant()] = amount; } return balances; } /// <inheritdoc /> protected async override Task<Dictionary<string, decimal>> OnGetAmountsAvailableToTradeAsync() { // https://docs.ftx.com/#get-balances // NOTE there is also is "Get balances of all accounts"? // "coin": "USDTBEAR", // "free": 2320.2, // "spotBorrow": 0.0, // "total": 2340.2, // "usdValue": 2340.2, // "availableWithoutBorrow": 2320.2 var balances = new Dictionary<string, decimal>(); JToken result = await MakeJsonRequestAsync<JToken>($"/wallet/balances", null, await GetNoncePayloadAsync()); foreach (JToken token in result.Children()) { balances.Add(token["coin"].ToStringInvariant(), token["availableWithoutBorrow"].ConvertInvariant<decimal>()); } return balances; } /// <inheritdoc /> protected async override Task<IEnumerable<MarketCandle>> OnGetCandlesAsync(string marketSymbol, int periodSeconds, DateTime? startDate = null, DateTime? endDate = null, int? limit = null) { //period options: 15, 60, 300, 900, 3600, 14400, 86400, or any multiple of 86400 up to 30*86400 var queryUrl = $"/markets/{marketSymbol}/candles?resolution={periodSeconds}"; if (startDate.HasValue) { queryUrl += $"&start_time={startDate?.UnixTimestampFromDateTimeSeconds()}"; } if (endDate.HasValue) { queryUrl += $"&end_time={endDate?.UnixTimestampFromDateTimeSeconds()}"; } var candles = new List<MarketCandle>(); var response = await MakeJsonRequestAsync<JToken>(queryUrl, null, await GetNoncePayloadAsync()); foreach (JToken candle in response.Children()) { var parsedCandle = this.ParseCandle(candle, marketSymbol, periodSeconds, "open", "high", "low", "close", "startTime", TimestampType.Iso8601, "volume"); candles.Add(parsedCandle); } return candles; } /// <inheritdoc /> protected async override Task<IEnumerable<ExchangeOrderResult>> OnGetCompletedOrderDetailsAsync(string marketSymbol = null, DateTime? afterDate = null) { string query = "/orders/history"; string parameters = ""; if (!string.IsNullOrEmpty(marketSymbol)) { parameters += $"&market={marketSymbol}"; } if (afterDate != null) { parameters += $"&start_time={afterDate?.UnixTimestampFromDateTimeSeconds()}"; } if (!string.IsNullOrEmpty(parameters)) { query += $"?{parameters}"; } JToken response = await MakeJsonRequestAsync<JToken>(query, null, await GetNoncePayloadAsync()); var orders = new List<ExchangeOrderResult>(); foreach (JToken token in response.Children()) { var symbol = token["market"].ToStringInvariant(); if (!Regex.Match(symbol, @"[\w\d]*\/[[\w\d]]*").Success) { continue; } orders.Add(ParseOrder(token)); } return orders; } /// <inheritdoc /> protected async override Task OnGetHistoricalTradesAsync(Func<IEnumerable<ExchangeTrade>, bool> callback, string marketSymbol, DateTime? startDate = null, DateTime? endDate = null, int? limit = null) { string baseUrl = $"/markets/{marketSymbol}/trades?"; if (startDate != null) { baseUrl += $"&start_time={startDate?.UnixTimestampFromDateTimeMilliseconds()}"; } if (endDate != null) { baseUrl += $"&end_time={endDate?.UnixTimestampFromDateTimeMilliseconds()}"; } List<ExchangeTrade> trades = new List<ExchangeTrade>(); while (true) { JToken result = await MakeJsonRequestAsync<JToken>(baseUrl); foreach (JToken trade in result.Children()) { trades.Add(trade.ParseTrade("size", "price", "side", "time", TimestampType.Iso8601, "id", "buy")); } if (!callback(trades)) { break; } Task.Delay(1000).Wait(); } } /// <inheritdoc /> protected async override Task<IEnumerable<string>> OnGetMarketSymbolsAsync(bool isWebSocket = false) { JToken result = await MakeJsonRequestAsync<JToken>("/markets"); //FTX contains futures which we are not interested in so we filter them out. var names = result.Children().Select(x => x["name"].ToStringInvariant()).Where(x => Regex.Match(x, @"[\w\d]*\/[[\w\d]]*").Success).ToList(); names.Sort(); return names; } /// <inheritdoc /> protected async internal override Task<IEnumerable<ExchangeMarket>> OnGetMarketSymbolsMetadataAsync() { //{ // "name": "BTC-0628", // "baseCurrency": null, // "quoteCurrency": null, // "quoteVolume24h": 28914.76, // "change1h": 0.012, // "change24h": 0.0299, // "changeBod": 0.0156, // "highLeverageFeeExempt": false, // "minProvideSize": 0.001, // "type": "future", // "underlying": "BTC", // "enabled": true, // "ask": 3949.25, // "bid": 3949, // "last": 10579.52, // "postOnly": false, // "price": 10579.52, // "priceIncrement": 0.25, // "sizeIncrement": 0.0001, // "restricted": false, // "volumeUsd24h": 28914.76 //} var markets = new List<ExchangeMarket>(); JToken result = await MakeJsonRequestAsync<JToken>("/markets"); foreach (JToken token in result.Children()) { var symbol = token["name"].ToStringInvariant(); if (!Regex.Match(symbol, @"[\w\d]*\/[[\w\d]]*").Success) { continue; } var market = new ExchangeMarket() { MarketSymbol = symbol, BaseCurrency = token["baseCurrency"].ToStringInvariant(), QuoteCurrency = token["quoteCurrency"].ToStringInvariant(), PriceStepSize = token["priceIncrement"].ConvertInvariant<decimal>(), QuantityStepSize = token["sizeIncrement"].ConvertInvariant<decimal>(), MinTradeSize = token["minProvideSize"].ConvertInvariant<decimal>(), IsActive = token["enabled"].ConvertInvariant<bool>(), }; markets.Add(market); } return markets; } /// <inheritdoc /> protected async override Task<IEnumerable<ExchangeOrderResult>> OnGetOpenOrderDetailsAsync(string marketSymbol = null) { // https://docs.ftx.com/#get-open-orders var markets = new List<ExchangeOrderResult>(); JToken result = await MakeJsonRequestAsync<JToken>($"/orders?market={marketSymbol}", null, await GetNoncePayloadAsync()); foreach (JToken token in result.Children()) { var symbol = token["market"].ToStringInvariant(); if (!Regex.Match(symbol, @"[\w\d]*\/[[\w\d]]*").Success) { continue; } markets.Add(ParseOrder(token)); } return markets; } /// <inheritdoc /> protected async override Task<ExchangeOrderBook> OnGetOrderBookAsync(string marketSymbol, int maxCount = 100) { JToken response = await MakeJsonRequestAsync<JToken>($"/markets/{marketSymbol}/orderbook?depth={maxCount}"); return response.ParseOrderBookFromJTokenArrays(); } /// <inheritdoc /> protected async override Task<ExchangeOrderResult> OnGetOrderDetailsAsync(string orderId, string marketSymbol = null, bool isClientOrderId = false) { // https://docs.ftx.com/#get-order-status and https://docs.ftx.com/#get-order-status-by-client-id if (!string.IsNullOrEmpty(marketSymbol)) throw new NotImplementedException("Searching by marketSymbol is either not implemented by or supported by this exchange. Please submit a PR if you are interested in this feature"); var url = "/orders/"; if (isClientOrderId) { url += "by_client_id/"; } JToken result = await MakeJsonRequestAsync<JToken>($"{url}{orderId}", null, await GetNoncePayloadAsync()); return ParseOrder(result); } /// <inheritdoc /> protected async override Task<IEnumerable<KeyValuePair<string, ExchangeTicker>>> OnGetTickersAsync() { JToken result = await MakeJsonRequestAsync<JToken>("/markets"); var tickers = new Dictionary<string, ExchangeTicker>(); foreach (JToken token in result.Children()) { var symbol = token["name"].ToStringInvariant(); if (!Regex.Match(symbol, @"[\w\d]*\/[[\w\d]]*").Success) { continue; } var ticker = await this.ParseTickerAsync(token, symbol, "ask", "bid", "last", null, null, "time", TimestampType.UnixSecondsDouble); tickers.Add(symbol, ticker); } return tickers; } protected override async Task<ExchangeTicker> OnGetTickerAsync(string marketSymbol) { var result = await MakeJsonRequestAsync<JToken>($"/markets/{marketSymbol}"); return await this.ParseTickerAsync(result, marketSymbol, "ask", "bid", "last", null, null, "time", TimestampType.UnixSecondsDouble); } protected override async Task<ExchangeWithdrawalResponse> OnWithdrawAsync(ExchangeWithdrawalRequest request) { var parameters = new Dictionary<string, object> { { "coin", request.Currency }, { "size", request.Amount }, { "address", request.Address }, { "nonce", await GenerateNonceAsync() }, { "password", request.Password }, { "code", request.Code } }; var result = await MakeJsonRequestAsync<JToken>("/wallet/withdrawals", null, parameters, "POST"); return new ExchangeWithdrawalResponse { Id = result["id"].ToString(), Fee = result.Value<decimal?>("fee") }; } /// <inheritdoc /> protected override async Task<IWebSocket> OnGetTickersWebSocketAsync(Action<IReadOnlyCollection<KeyValuePair<string, ExchangeTicker>>> tickers, params string[] marketSymbols) { if (marketSymbols == null || marketSymbols.Length == 0) { marketSymbols = (await GetMarketSymbolsAsync(true)).ToArray(); } return await ConnectPublicWebSocketAsync(null, messageCallback: async (_socket, msg) => { JToken parsedMsg = JToken.Parse(msg.ToStringFromUTF8()); if (parsedMsg["channel"].ToStringInvariant().Equals("ticker") && !parsedMsg["type"].ToStringInvariant().Equals("subscribed")) { JToken data = parsedMsg["data"]; var exchangeTicker = await this.ParseTickerAsync(data, parsedMsg["market"].ToStringInvariant(), "ask", "bid", "last", null, null, "time", TimestampType.UnixSecondsDouble); var kv = new KeyValuePair<string, ExchangeTicker>(exchangeTicker.MarketSymbol, exchangeTicker); tickers(new List<KeyValuePair<string, ExchangeTicker>> { kv }); } }, connectCallback: async (_socket) => { List<string> marketSymbolList = marketSymbols.ToList(); //{'op': 'subscribe', 'channel': 'trades', 'market': 'BTC-PERP'} for (int i = 0; i < marketSymbolList.Count; i++) { await _socket.SendMessageAsync(new { op = "subscribe", market = marketSymbolList[i], channel = "ticker" }); } }); } /// <inheritdoc /> protected async override Task<ExchangeOrderResult> OnPlaceOrderAsync(ExchangeOrderRequest order) { //{ // "market": "XRP-PERP", // "side": "sell", // "price": 0.306525, // "type": "limit", // "size": 31431.0, // "reduceOnly": false, // "ioc": false, // "postOnly": false, // "clientId": null //} IEnumerable<ExchangeMarket> markets = await OnGetMarketSymbolsMetadataAsync(); ExchangeMarket market = markets.Where(m => m.MarketSymbol == order.MarketSymbol).First(); var payload = await GetNoncePayloadAsync(); var parameters = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase) { {"market", market.MarketSymbol}, {"side", order.IsBuy ? "buy" : "sell" }, {"type", order.OrderType.ToStringLowerInvariant() }, {"size", order.RoundAmount() } }; if (!string.IsNullOrEmpty(order.ClientOrderId)) { parameters.Add("clientId", order.ClientOrderId); } if (order.IsPostOnly != null) { parameters.Add("postOnly", order.IsPostOnly); } if (order.OrderType != OrderType.Market) { int precision = BitConverter.GetBytes(decimal.GetBits((decimal)market.PriceStepSize)[3])[2]; if (order.Price == null) throw new ArgumentNullException(nameof(order.Price)); parameters.Add("price", Math.Round(order.Price.Value, precision)); } else { parameters.Add("price", null); } parameters.CopyTo(payload); order.ExtraParameters.CopyTo(payload); var response = await MakeJsonRequestAsync<JToken>("/orders", null, payload, "POST"); ExchangeOrderResult result = new ExchangeOrderResult { OrderId = response["id"].ToStringInvariant(), ClientOrderId = response["clientId"].ToStringInvariant(), OrderDate = CryptoUtility.ToDateTimeInvariant(response["createdAt"]), Price = CryptoUtility.ConvertInvariant<decimal>(response["price"]), AmountFilled = CryptoUtility.ConvertInvariant<decimal>(response["filledSize"]), AveragePrice = CryptoUtility.ConvertInvariant<decimal>(response["avgFillPrice"]), Amount = CryptoUtility.ConvertInvariant<decimal>(response["size"]), MarketSymbol = response["market"].ToStringInvariant(), IsBuy = response["side"].ToStringInvariant() == "buy" }; return result; } /// <inheritdoc /> protected override async Task ProcessRequestAsync(IHttpWebRequest request, Dictionary<string, object> payload) { if (CanMakeAuthenticatedRequest(payload)) { string timestamp = payload["nonce"].ToStringInvariant(); payload.Remove("nonce"); string form = CryptoUtility.GetJsonForPayload(payload); //Create the signature payload string toHash = $"{timestamp}{request.Method.ToUpperInvariant()}{request.RequestUri.PathAndQuery}"; if (request.Method == "POST") { toHash += form; await CryptoUtility.WriteToRequestAsync(request, form); } byte[] secret = CryptoUtility.ToUnsecureBytesUTF8(PrivateApiKey); string signatureHexString = CryptoUtility.SHA256Sign(toHash, secret); request.AddHeader("FTX-KEY", PublicApiKey.ToUnsecureString()); request.AddHeader("FTX-SIGN", signatureHexString); request.AddHeader("FTX-TS", timestamp); } } #endregion #region Private Methods /// <summary> /// Parses the json of an order. /// </summary> /// <param name="token">Json token to parse the order from.</param> /// <returns>Parsed exchange order result.</returns> private ExchangeOrderResult ParseOrder(JToken token) { return new ExchangeOrderResult() { MarketSymbol = token["market"].ToStringInvariant(), Price = token["price"].ConvertInvariant<decimal>(), AveragePrice = token["avgFillPrice"].ConvertInvariant<decimal>(), OrderDate = token["createdAt"].ConvertInvariant<DateTime>(), IsBuy = token["side"].ToStringInvariant().Equals("buy"), OrderId = token["id"].ToStringInvariant(), Amount = token["size"].ConvertInvariant<decimal>(), AmountFilled = token["filledSize"].ConvertInvariant<decimal>(), ClientOrderId = token["clientId"].ToStringInvariant(), Result = token["status"].ToStringInvariant().ToExchangeAPIOrderResult(token["size"].ConvertInvariant<decimal>() - token["filledSize"].ConvertInvariant<decimal>()), ResultCode = token["status"].ToStringInvariant() }; } #endregion } }
30.35283
224
0.67856
[ "MIT" ]
BZ-CO/ExchangeSharp
src/ExchangeSharp/API/Exchanges/FTX/ExchangeFTXAPI.cs
16,087
C#
using AnnualLeaveRequest.Shared; using AnnualLeaveRequestMinimalAPI.Models; using System; using System.Collections.Generic; namespace AnnualLeaveRequestMinimalAPI.Interfaces { public interface IAnnualLeaveRequestLogic { List<int> GetYears(); List<AnnualLeaveRequestOverviewModel> GetRequestsForYear(int year); AnnualLeaveRequestOverviewModel GetRequest(int annualLeaveRequestID); decimal GetDaysBetweenStartDateAndReturnDate(DateTime startDate, DateTime returnDate); AnnualLeaveRequestCRUDModel Create(AnnualLeaveRequestCRUDModel model); AnnualLeaveRequestCRUDModel Update(AnnualLeaveRequestCRUDModel model); void Delete(int annualLeaveRequestId); } }
38
94
0.795014
[ "MIT" ]
johnt84/AnnualLeaveRequestTool
AnnualLeaveRequestMinimalAPI/Interfaces/IAnnualLeaveRequestLogic.cs
724
C#
using System; using System.Collections.Generic; using System.Numerics; using System.Text; using System.Text.RegularExpressions; namespace MilitantChickensTranferProtocol.Library { public class ResponseReader { public byte[] rawHeader { get; set; } public ResponseHeader header { get; set; } public static BigInteger key { get; set; } public ResponseReader() { //Empty Constructor } public ResponseReader(byte[] _rawHeader, BigInteger _key) { key = _key; rawHeader = dencrypt(_rawHeader); byte respCode = rawHeader[0]; byte[] desc = new byte[rawHeader.Length - 1]; for (int i = 0; i < desc.Length; i++) { desc[i] = rawHeader[i + 1]; } header = new ResponseHeader(respCode,desc); } static byte[] dencrypt(byte[] msg) { string k = key.ToString(); byte[] messageBytes = msg; byte[] keyBytes = Encoding.UTF8.GetBytes(k); for (int i = 0; i < messageBytes.Length; i++) { messageBytes[i] ^= keyBytes[i % keyBytes.Length]; } return messageBytes; } } }
27.826087
65
0.535938
[ "Apache-2.0" ]
HSU-F20-CS346/MilitantChickens-TP
MilitantChickensTranferProtocol.Library/ResponseReader.cs
1,282
C#
using Oqtane.Shared; using System; using Oqtane.Models; using System.Text.Json; using Oqtane.Repository; using Microsoft.Extensions.Configuration; using Microsoft.AspNetCore.Http; using System.Collections.Generic; using Oqtane.Security; namespace Oqtane.Infrastructure { public class LogManager : ILogManager { private readonly ILogRepository Logs; private readonly ITenantResolver TenantResolver; private readonly IConfigurationRoot Config; private readonly IUserPermissions UserPermissions; private readonly IHttpContextAccessor Accessor; public LogManager(ILogRepository Logs, ITenantResolver TenantResolver, IConfigurationRoot Config, IUserPermissions UserPermissions, IHttpContextAccessor Accessor) { this.Logs = Logs; this.TenantResolver = TenantResolver; this.Config = Config; this.UserPermissions = UserPermissions; this.Accessor = Accessor; } public void Log(LogLevel Level, object Class, LogFunction Function, string Message, params object[] Args) { Log(-1, Level, Class.GetType().AssemblyQualifiedName, Function, null, Message, Args); } public void Log(LogLevel Level, object Class, LogFunction Function, Exception Exception, string Message, params object[] Args) { Log(-1, Level, Class.GetType().AssemblyQualifiedName, Function, Exception, Message, Args); } public void Log(int SiteId, LogLevel Level, object Class, LogFunction Function, string Message, params object[] Args) { Log(SiteId, Level, Class.GetType().AssemblyQualifiedName, Function, null, Message, Args); } public void Log(int SiteId, LogLevel Level, object Class, LogFunction Function, Exception Exception, string Message, params object[] Args) { Log log = new Log(); if (SiteId == -1) { log.SiteId = null; Alias alias = TenantResolver.GetAlias(); if (alias != null) { log.SiteId = alias.SiteId; } } else { log.SiteId = SiteId; } log.PageId = null; log.ModuleId = null; log.UserId = null; User user = UserPermissions.GetUser(); if (user != null) { log.UserId = user.UserId; } HttpRequest request = Accessor.HttpContext.Request; if (request != null) { log.Url = request.Scheme.ToString() + "://" + request.Host.ToString() + request.Path.ToString() + request.QueryString.ToString(); } Type type = Type.GetType(Class.ToString()); if (type != null) { log.Category = type.AssemblyQualifiedName; log.Feature = Utilities.GetTypeNameLastSegment(log.Category, 0); } else { log.Category = Class.ToString(); log.Feature = log.Category; } log.Function = Enum.GetName(typeof(LogFunction), Function); log.Level = Enum.GetName(typeof(LogLevel), Level); if (Exception != null) { log.Exception = Exception.ToString(); } log.Message = Message; log.MessageTemplate = ""; try { log.Properties = JsonSerializer.Serialize(Args); } catch // serialization error occurred { log.Properties = ""; } Log(log); } public void Log(Log Log) { LogLevel minlevel = LogLevel.Information; var section = Config.GetSection("Logging:LogLevel:Default"); if (section.Exists()) { minlevel = Enum.Parse<LogLevel>(Config.GetSection("Logging:LogLevel:Default").ToString()); } if (Enum.Parse<LogLevel>(Log.Level) >= minlevel) { Log.LogDate = DateTime.UtcNow; Log.Server = Environment.MachineName; Log.MessageTemplate = Log.Message; Log = ProcessStructuredLog(Log); try { Logs.AddLog(Log); } catch { // an error occurred writing to the database } } } private Log ProcessStructuredLog(Log Log) { try { string message = Log.Message; string properties = ""; if (!string.IsNullOrEmpty(message) && message.Contains("{") && message.Contains("}") && !string.IsNullOrEmpty(Log.Properties)) { // get the named holes in the message and replace values object[] values = JsonSerializer.Deserialize<object[]>(Log.Properties); List<string> names = new List<string>(); int index = message.IndexOf("{"); while (index != -1) { if (message.IndexOf("}", index) != -1) { names.Add(message.Substring(index + 1, message.IndexOf("}", index) - index - 1)); if (values.Length > (names.Count - 1)) { if (values[names.Count - 1] == null) { message = message.Replace("{" + names[names.Count - 1] + "}", "null"); } else { message = message.Replace("{" + names[names.Count - 1] + "}", values[names.Count - 1].ToString()); } } } index = message.IndexOf("{", index + 1); } // rebuild properties into dictionary Dictionary<string, object> propertydictionary = new Dictionary<string, object>(); for (int i = 0; i < values.Length; i++) { if (i < names.Count) { propertydictionary.Add(names[i], values[i]); } else { propertydictionary.Add("Property" + i.ToString(), values[i]); } } properties = JsonSerializer.Serialize(propertydictionary); } Log.Message = message; Log.Properties = properties; } catch { Log.Properties = ""; } return Log; } } }
38.229947
170
0.479787
[ "MIT" ]
mitchelsellers/oqtane.framework
Oqtane.Server/Infrastructure/LogManager.cs
7,151
C#
namespace Merchello.Core.Gateways.Taxation { using Merchello.Core.Models; using Umbraco.Core; /// <summary> /// Defines an invoice taxation strategy base class /// </summary> public abstract class TaxCalculationStrategyBase : ITaxCalculationStrategy { /// <summary> /// The invoice. /// </summary> private readonly IInvoice _invoice; /// <summary> /// The tax address. /// </summary> private readonly IAddress _taxAddress; /// <summary> /// Initializes a new instance of the <see cref="TaxCalculationStrategyBase"/> class. /// </summary> /// <param name="invoice"> /// The invoice. /// </param> /// <param name="taxAddress"> /// The tax address. /// </param> protected TaxCalculationStrategyBase(IInvoice invoice, IAddress taxAddress) { Ensure.ParameterNotNull(invoice, "invoice"); Ensure.ParameterNotNull(taxAddress, "taxAddress"); _invoice = invoice; _taxAddress = taxAddress; } /// <summary> /// Gets the <see cref="IInvoice"/> /// </summary> protected IInvoice Invoice { get { return _invoice; } } /// <summary> /// Gets the tax address /// </summary> protected IAddress TaxAddress { get { return _taxAddress; } } /// <summary> /// Computes the invoice tax result /// </summary> /// <returns> /// The <see cref="ITaxCalculationResult"/> /// </returns> public abstract Attempt<ITaxCalculationResult> CalculateTaxesForInvoice(); } }
27.484375
93
0.542354
[ "MIT" ]
benjaminhowarth1/Merchello
src/Merchello.Core/Gateways/Taxation/TaxCalculationStrategyBase.cs
1,761
C#
using MediatR; using RedisKeyTool.Shared; namespace RedisKeyTool.Application.Command { /// <summary> /// Get the redis dbs command /// </summary> /// <seealso cref="MediatR.IRequest{RedisKeyTool.Shared.DatabaseResponse}" /> public class GetRedisDbs : IRequest<DatabaseResponse> { public GetRedisDbs() { } /// <summary> /// Gets or sets the redis setting. /// </summary> /// <value> /// The redis setting. /// </value> public RedisSetting RedisSetting { get; set; } } }
24.125
81
0.573402
[ "MIT" ]
BlazorHub/radishv2
code/RedisKeyTool.Server.Application/Command/GetRedisDbs.cs
581
C#
using System; using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Sync")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Sync")] [assembly: AssemblyCopyright("Copyright © Microsoft")] [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("fc29ef65-ccc2-4d41-b1c7-6e0437e479da")] // 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("3.2.0")] [assembly: AssemblyFileVersion("3.2.0")] [assembly: CLSCompliant(false)]
37.736842
85
0.724547
[ "MIT" ]
athipp/azure-powershell
src/ServiceManagement/Compute/Sync/Properties/AssemblyInfo.cs
1,400
C#
using System.Collections.Generic; using System.Linq; using AppStudio.DataProviders.Rss; namespace AppStudio.DataProviders.Bing { public class BingParser : IParser<BingSchema> { public IEnumerable<BingSchema> Parse(string data) { RssParser rssParser = new RssParser(); IEnumerable<RssSchema> syndicationItems = rssParser.Parse(data); return (from r in syndicationItems select new BingSchema() { _id = r._id, Title = r.Title, Summary = r.Summary, Link = r.FeedUrl, Published = r.PublishDate }); } } }
30.12
76
0.513944
[ "MIT" ]
LanceMcCarthy/Lancelot.VSauceSupreme
src/VSauce Supreme/AppStudio.DataProviders/Bing/BingParser.cs
755
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EntityLayer { public class BaseEntity : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected void onPropertyChanged(string PropertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName)); } } }
24.894737
86
0.735729
[ "MIT" ]
libinmath3w/PlayGround
PlayGround/EntityLayer/BaseEntity.cs
475
C#