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; namespace UAlbion.Core.Textures { public readonly struct LayerKey : IEquatable<LayerKey> { readonly int _id; readonly int _frame; public LayerKey(int id, int frame) { _id = id; _frame = frame; } public bool Equals(LayerKey other) => _id == other._id && _frame == other._frame; public override bool Equals(object obj) => obj is LayerKey other && Equals(other); public static bool operator ==(LayerKey left, LayerKey right) => left.Equals(right); public static bool operator !=(LayerKey left, LayerKey right) => !(left == right); public override int GetHashCode() { unchecked { return (_id * 397) ^ _frame; } } public override string ToString() => $"LK{_id}.{_frame}"; } }
45.294118
92
0.641558
[ "MIT" ]
Metibor/ualbion
src/Core/Textures/LayerKey.cs
772
C#
using System; using MeteoSharp.Core; namespace MeteoSharp.Measurements { public interface IMeasurement<TUnit> where TUnit : struct, Enum { SmallDecimal Value { get; } TUnit Unit { get; } SmallDecimal ValueIn(TUnit unit); } public interface IMeasurement<TMeasurement, TUnit> : IMeasurement<TUnit>, IEquatable<TMeasurement>, IComparable<TMeasurement>, IComparable where TMeasurement : struct, IMeasurement<TUnit> where TUnit : struct, Enum { TMeasurement In(TUnit unit); } }
23.583333
95
0.659011
[ "MIT" ]
fedarovich/meteo-sharp
Source/MeteoSharp/MeteoSharp/Measurements/IMeasurement.cs
568
C#
using System; using System.Net; using System.Net.Http; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using W4k.AspNetCore.Correlator.Context; using W4k.AspNetCore.Correlator.Context.Types; using W4k.AspNetCore.Correlator.Extensions; using W4k.AspNetCore.Correlator.Extensions.DependencyInjection; using W4k.AspNetCore.Correlator.Options; using Xunit; namespace W4k.AspNetCore.Correlator { public class CorrelationPropagationTests : IDisposable { private readonly IHost _hostAlpha; private readonly IHost _hostBeta; public CorrelationPropagationTests() { _hostAlpha = Host.CreateDefaultBuilder() .ConfigureWebHostDefaults(webBuilder => { webBuilder.ConfigureKestrel(serverOptions => { serverOptions.ListenLocalhost(8081); }); webBuilder.UseStartup<StartupAlpha>(); }) .Build(); _hostBeta = Host.CreateDefaultBuilder() .ConfigureWebHostDefaults(webBuilder => { webBuilder.ConfigureKestrel(serverOptions => { serverOptions.ListenLocalhost(8082); }); webBuilder.UseStartup<StartupBeta>(); }) .Build(); _hostAlpha.Start(); _hostBeta.Start(); } [Fact] public async Task ForwardCorrelation_WhenChangingHeader_ExpectCorrelationSent() { // arrange var correlation = "test-123"; var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:8081/") { Headers = { { "X-Correlation-Id", correlation } } }; // act // // <test> (X-Correlation-Id: test-123) // --> host A (X-Request-Id: test-123) // --> host B // // 1. send request to Host A, X-Correlation-Id: test-123 // 2. send request from Host A to Host B, X-Request-Id: test-123 // 3. cascade result from Host B using var httpClient = new HttpClient(); var response = await httpClient.SendAsync(request); var receivedValue = await response.Content.ReadAsStringAsync(); // assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal($"X-Request-Id:{correlation}", receivedValue); } public void Dispose() { _hostAlpha?.Dispose(); _hostBeta?.Dispose(); } private class StartupAlpha { private const string BetaClientName = "TestBetaClient"; public void ConfigureServices(IServiceCollection services) { services.AddDefaultCorrelator(o => { o.Forward = PropagationSettings.PropagateAs("X-Request-Id"); }); services .AddHttpClient( BetaClientName, httpClient => httpClient.BaseAddress = new Uri("http://localhost:8082")) .WithCorrelation(); } public void Configure(IApplicationBuilder app, IHttpClientFactory httpClientFactory) { app.UseCorrelator(); app.Use(async (context, next) => { var response = await httpClientFactory.CreateClient(BetaClientName).GetAsync("/"); var receivedValue = await response.Content.ReadAsStringAsync(); context.Response.Headers.Add("Content-Type", "text/plain"); await context.Response.WriteAsync(receivedValue); }); } } private class StartupBeta { public void ConfigureServices(IServiceCollection services) { services.AddDefaultCorrelator(); } public void Configure(IApplicationBuilder app, ICorrelationContextAccessor correlationContextAccessor) { app.UseCorrelator(); app.Use(async (context, next) => { context.Response.Headers.Add("Content-Type", "text/plain"); var correlationContext = (RequestCorrelationContext)correlationContextAccessor.CorrelationContext; await context.Response.WriteAsync($"{correlationContext.Header}:{correlationContext.CorrelationId}"); }); } } } }
34.657343
121
0.547821
[ "MIT" ]
wdolek/w4k-aspnetcore-correlator
test/W4k.AspNetCore.Correlator.IntegrationTests/CorrelationPropagationTests.cs
4,958
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Horizon.Utilities { public static class StringHelper { /// <summary> /// Gets whether the string is null, empty, or comprised entirely of whitespace. /// </summary> /// <param name="s"> /// </param> /// <returns> /// True if the string is null, empty, or comprised entirely of whitespace, otherwise false. /// </returns> public static bool IsNullOrWhitespace(this string s) => string.IsNullOrWhiteSpace(s); } }
29.619048
100
0.635048
[ "MIT" ]
TheHeadmaster/Horizon
Horizon/Horizon/Utilities/StringHelper.cs
624
C#
namespace AbpQa274 { public abstract class AbpQa274DomainTestBase : AbpQa274TestBase<AbpQa274DomainTestModule> { } }
16.5
94
0.742424
[ "MIT" ]
liangshiw/AbpQa274
AbpQa274/aspnet-core/test/AbpQa274.Domain.Tests/AbpQa274DomainTestBase.cs
134
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; namespace Birdie.Core.Data.Migrations { [DbContext(typeof(BirdieContext))] [Migration("20210419232303_AddTweetAndMoreTables")] partial class AddTweetAndMoreTables { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .UseIdentityByDefaultColumns() .HasAnnotation("Relational:MaxIdentifierLength", 63) .HasAnnotation("ProductVersion", "5.0.2"); modelBuilder.Entity("Birdie.API.Data.Entities.Country", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("integer") .HasColumnName("id") .UseIdentityByDefaultColumn(); b.Property<string>("Name") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)") .HasColumnName("name"); b.HasKey("Id") .HasName("pk_country"); b.ToTable("country"); }); modelBuilder.Entity("Birdie.API.Data.Entities.Favorite", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasColumnName("id") .UseIdentityByDefaultColumn(); b.Property<DateTime>("FavoritedAt") .HasColumnType("timestamp without time zone") .HasColumnName("favorited_at"); b.Property<long>("TweetId") .HasColumnType("bigint") .HasColumnName("tweet_id"); b.Property<long>("UserId") .HasColumnType("bigint") .HasColumnName("user_id"); b.HasKey("Id") .HasName("pk_favorites"); b.ToTable("favorites"); }); modelBuilder.Entity("Birdie.API.Data.Entities.Hashtag", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasColumnName("id") .UseIdentityByDefaultColumn(); b.Property<int[]>("Indices") .HasColumnType("integer[]") .HasColumnName("indices"); b.Property<string>("Title") .IsRequired() .HasMaxLength(40) .HasColumnType("character varying(40)") .HasColumnName("title"); b.HasKey("Id") .HasName("pk_hashtag"); b.ToTable("hashtag"); }); modelBuilder.Entity("Birdie.API.Data.Entities.Media", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasColumnName("id") .UseIdentityByDefaultColumn(); b.Property<string>("DisplayUrl") .HasColumnType("text") .HasColumnName("display_url"); b.Property<int[]>("Indices") .HasColumnType("integer[]") .HasColumnName("indices"); b.Property<long>("TweetId") .HasColumnType("bigint") .HasColumnName("tweet_id"); b.Property<int>("Type") .HasColumnType("integer") .HasColumnName("type"); b.Property<string>("Url") .HasColumnType("text") .HasColumnName("url"); b.HasKey("Id") .HasName("pk_media"); b.HasIndex("TweetId") .HasDatabaseName("ix_media_tweet_id"); b.ToTable("media"); }); modelBuilder.Entity("Birdie.API.Data.Entities.Mention", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasColumnName("id") .UseIdentityByDefaultColumn(); b.Property<int[]>("Indices") .HasColumnType("integer[]") .HasColumnName("indices"); b.Property<string>("Name") .HasColumnType("text") .HasColumnName("name"); b.Property<string>("ScreenName") .HasColumnType("text") .HasColumnName("screen_name"); b.Property<long?>("TweetId") .HasColumnType("bigint") .HasColumnName("tweet_id"); b.Property<long>("UserId") .HasColumnType("bigint") .HasColumnName("user_id"); b.HasKey("Id") .HasName("pk_mention"); b.HasIndex("TweetId") .HasDatabaseName("ix_mention_tweet_id"); b.ToTable("mention"); }); modelBuilder.Entity("Birdie.API.Data.Entities.Retweet", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasColumnName("id") .UseIdentityByDefaultColumn(); b.Property<DateTime>("RetweetedAt") .HasColumnType("timestamp without time zone") .HasColumnName("retweeted_at"); b.Property<long>("TweetId") .HasColumnType("bigint") .HasColumnName("tweet_id"); b.Property<long>("UserId") .HasColumnType("bigint") .HasColumnName("user_id"); b.HasKey("Id") .HasName("pk_retweets"); b.ToTable("retweets"); }); modelBuilder.Entity("Birdie.API.Data.Entities.Tweet", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasColumnName("id") .UseIdentityByDefaultColumn(); b.Property<string>("Body") .IsRequired() .HasMaxLength(300) .HasColumnType("character varying(300)") .HasColumnName("body"); b.Property<DateTime>("CreatedAt") .ValueGeneratedOnAdd() .HasColumnType("timestamp without time zone") .HasColumnName("created_at") .HasDefaultValueSql("now()"); b.Property<bool>("Favorited") .ValueGeneratedOnAdd() .HasColumnType("boolean") .HasDefaultValue(false) .HasColumnName("favorited"); b.Property<bool>("Retweeted") .ValueGeneratedOnAdd() .HasColumnType("boolean") .HasDefaultValue(false) .HasColumnName("retweeted"); b.Property<long>("UserId") .HasColumnType("bigint") .HasColumnName("user_id"); b.HasKey("Id") .HasName("pk_tweets"); b.HasIndex("UserId") .HasDatabaseName("ix_tweets_user_id"); b.ToTable("tweets"); }); modelBuilder.Entity("Birdie.API.Data.Entities.TweetStats", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasColumnName("id") .UseIdentityByDefaultColumn(); b.Property<int>("FavoriteCount") .HasColumnType("integer") .HasColumnName("favorite_count"); b.Property<int>("QuoteCount") .HasColumnType("integer") .HasColumnName("quote_count"); b.Property<int>("ReplyCount") .HasColumnType("integer") .HasColumnName("reply_count"); b.Property<int>("RetweetCount") .HasColumnType("integer") .HasColumnName("retweet_count"); b.Property<long>("TweetId") .HasColumnType("bigint") .HasColumnName("tweet_id"); b.HasKey("Id") .HasName("pk_tweet_stats"); b.HasIndex("TweetId") .IsUnique() .HasDatabaseName("ix_tweet_stats_tweet_id"); b.ToTable("tweet_stats"); }); modelBuilder.Entity("Birdie.API.Data.Entities.Url", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasColumnName("id") .UseIdentityByDefaultColumn(); b.Property<string>("DisplayUrl") .HasColumnType("text") .HasColumnName("display_url"); b.Property<string>("ExpandedUrl") .HasColumnType("text") .HasColumnName("expanded_url"); b.Property<string>("GeneratedUrl") .HasColumnType("text") .HasColumnName("generated_url"); b.Property<int[]>("Indices") .HasColumnType("integer[]") .HasColumnName("indices"); b.Property<long>("TweetId") .HasColumnType("bigint") .HasColumnName("tweet_id"); b.HasKey("Id") .HasName("pk_url"); b.HasIndex("TweetId") .HasDatabaseName("ix_url_tweet_id"); b.ToTable("url"); }); modelBuilder.Entity("Birdie.API.Data.Entities.User", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasColumnName("id") .UseIdentityByDefaultColumn(); b.Property<bool>("CanDm") .ValueGeneratedOnAdd() .HasColumnType("boolean") .HasDefaultValue(false) .HasColumnName("can_dm"); b.Property<bool>("CanMediaTag") .ValueGeneratedOnAdd() .HasColumnType("boolean") .HasDefaultValue(true) .HasColumnName("can_media_tag"); b.Property<int?>("CountryId") .HasColumnType("integer") .HasColumnName("country_id"); b.Property<DateTime>("CreatedAt") .ValueGeneratedOnAdd() .HasColumnType("timestamp without time zone") .HasColumnName("created_at") .HasDefaultValueSql("now()"); b.Property<string>("Description") .HasMaxLength(140) .HasColumnType("character varying(140)") .HasColumnName("description"); b.Property<string>("Email") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)") .HasColumnName("email"); b.Property<bool>("Following") .ValueGeneratedOnAdd() .HasColumnType("boolean") .HasDefaultValue(false) .HasColumnName("following"); b.Property<bool>("IsProtected") .ValueGeneratedOnAdd() .HasColumnType("boolean") .HasDefaultValue(false) .HasColumnName("is_protected"); b.Property<bool>("IsVerified") .ValueGeneratedOnAdd() .HasColumnType("boolean") .HasDefaultValue(false) .HasColumnName("is_verified"); b.Property<string>("Location") .HasMaxLength(100) .HasColumnType("character varying(100)") .HasColumnName("location"); b.Property<string>("Name") .IsRequired() .HasMaxLength(20) .HasColumnType("character varying(20)") .HasColumnName("name"); b.Property<long>("PinnedStatusId") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasDefaultValue(0L) .HasColumnName("pinned_status_id"); b.Property<string>("ProfileBannerUrl") .IsRequired() .ValueGeneratedOnAdd() .HasMaxLength(250) .HasColumnType("character varying(250)") .HasDefaultValue("default_banner_pic.jpg") .HasColumnName("profile_banner_url"); b.Property<string>("ProfileImageUrl") .IsRequired() .ValueGeneratedOnAdd() .HasMaxLength(250) .HasColumnType("character varying(250)") .HasDefaultValue("default_profile_pic.jpg") .HasColumnName("profile_image_url"); b.Property<string>("Url") .HasMaxLength(250) .HasColumnType("character varying(250)") .HasColumnName("url"); b.Property<string>("Username") .IsRequired() .HasMaxLength(20) .HasColumnType("character varying(20)") .HasColumnName("username"); b.Property<bool>("WantRetweet") .ValueGeneratedOnAdd() .HasColumnType("boolean") .HasDefaultValue(true) .HasColumnName("want_retweet"); b.HasKey("Id") .HasName("pk_users"); b.HasIndex("CountryId") .HasDatabaseName("ix_users_country_id"); b.ToTable("users"); }); modelBuilder.Entity("Birdie.API.Data.Entities.UserStatistics", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasColumnName("id") .UseIdentityByDefaultColumn(); b.Property<int>("FavouritesCount") .HasColumnType("integer") .HasColumnName("favourites_count"); b.Property<int>("FollowersCount") .HasColumnType("integer") .HasColumnName("followers_count"); b.Property<int>("FriendsCount") .HasColumnType("integer") .HasColumnName("friends_count"); b.Property<int>("ListedCount") .HasColumnType("integer") .HasColumnName("listed_count"); b.Property<int>("MediaCount") .HasColumnType("integer") .HasColumnName("media_count"); b.Property<int>("StatusCount") .HasColumnType("integer") .HasColumnName("status_count"); b.Property<long>("UserId") .HasColumnType("bigint") .HasColumnName("user_id"); b.HasKey("Id") .HasName("pk_user_statistics"); b.HasIndex("UserId") .IsUnique() .HasDatabaseName("ix_user_statistics_user_id"); b.ToTable("user_statistics"); }); modelBuilder.Entity("HashtagTweet", b => { b.Property<long>("HashtagsId") .HasColumnType("bigint") .HasColumnName("hashtags_id"); b.Property<long>("TweetsId") .HasColumnType("bigint") .HasColumnName("tweets_id"); b.HasKey("HashtagsId", "TweetsId") .HasName("pk_hashtag_tweet"); b.HasIndex("TweetsId") .HasDatabaseName("ix_hashtag_tweet_tweets_id"); b.ToTable("hashtag_tweet"); }); modelBuilder.Entity("Birdie.API.Data.Entities.Media", b => { b.HasOne("Birdie.API.Data.Entities.Tweet", "Tweet") .WithMany("Mediae") .HasForeignKey("TweetId") .HasConstraintName("fk_media_tweets_tweet_id") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Tweet"); }); modelBuilder.Entity("Birdie.API.Data.Entities.Mention", b => { b.HasOne("Birdie.API.Data.Entities.Tweet", "Tweet") .WithMany("Mentions") .HasForeignKey("TweetId") .HasConstraintName("fk_mention_tweets_tweet_id"); b.Navigation("Tweet"); }); modelBuilder.Entity("Birdie.API.Data.Entities.Tweet", b => { b.HasOne("Birdie.API.Data.Entities.User", "User") .WithMany("Tweets") .HasForeignKey("UserId") .HasConstraintName("fk_tweets_users_user_id") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("User"); }); modelBuilder.Entity("Birdie.API.Data.Entities.TweetStats", b => { b.HasOne("Birdie.API.Data.Entities.Tweet", "Tweet") .WithOne("Stats") .HasForeignKey("Birdie.API.Data.Entities.TweetStats", "TweetId") .HasConstraintName("fk_tweet_stats_tweets_tweet_id") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Tweet"); }); modelBuilder.Entity("Birdie.API.Data.Entities.Url", b => { b.HasOne("Birdie.API.Data.Entities.Tweet", "Tweet") .WithMany("Urls") .HasForeignKey("TweetId") .HasConstraintName("fk_url_tweets_tweet_id") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Tweet"); }); modelBuilder.Entity("Birdie.API.Data.Entities.User", b => { b.HasOne("Birdie.API.Data.Entities.Country", "Country") .WithMany() .HasForeignKey("CountryId") .HasConstraintName("fk_users_country_country_id"); b.Navigation("Country"); }); modelBuilder.Entity("Birdie.API.Data.Entities.UserStatistics", b => { b.HasOne("Birdie.API.Data.Entities.User", "User") .WithOne("Statistics") .HasForeignKey("Birdie.API.Data.Entities.UserStatistics", "UserId") .HasConstraintName("fk_user_statistics_users_user_id") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("User"); }); modelBuilder.Entity("HashtagTweet", b => { b.HasOne("Birdie.API.Data.Entities.Hashtag", null) .WithMany() .HasForeignKey("HashtagsId") .HasConstraintName("fk_hashtag_tweet_hashtag_hashtags_id") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Birdie.API.Data.Entities.Tweet", null) .WithMany() .HasForeignKey("TweetsId") .HasConstraintName("fk_hashtag_tweet_tweets_tweets_id") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Birdie.API.Data.Entities.Tweet", b => { b.Navigation("Mediae"); b.Navigation("Mentions"); b.Navigation("Stats"); b.Navigation("Urls"); }); modelBuilder.Entity("Birdie.API.Data.Entities.User", b => { b.Navigation("Statistics"); b.Navigation("Tweets"); }); #pragma warning restore 612, 618 } } }
38.070147
91
0.425076
[ "MIT" ]
jnnrz/Birdie.Core
src/Data/Migrations/20210419232303_AddTweetAndMoreTables.Designer.cs
23,339
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using Azure.Core.TestFramework; namespace Azure.Identity.Tests { public abstract class IdentityRecordedTestBase : RecordedTestBase<IdentityTestEnvironment> { protected IdentityRecordedTestBase(bool isAsync) : this(isAsync, RecordedTestMode.Playback) { } protected IdentityRecordedTestBase(bool isAsync, RecordedTestMode mode) : base(isAsync, mode) { // the following headers are added by MSAL and need to be excluded from matching for recordings Matcher.ExcludeHeaders.Add("Content-Length"); Matcher.ExcludeHeaders.Add("client-request-id"); Matcher.ExcludeHeaders.Add("x-client-OS"); Matcher.ExcludeHeaders.Add("x-client-SKU"); Matcher.ExcludeHeaders.Add("x-client-CPU"); Matcher.ExcludeHeaders.Add("x-client-Ver"); Sanitizer = new IdentityRecordedTestSanitizer(); } } }
36.714286
107
0.677043
[ "MIT" ]
MiriBerezin/azure-sdk-for-net
sdk/identity/Azure.Identity/tests/IdentityRecordedTestBase.cs
1,030
C#
using System.ComponentModel.DataAnnotations; namespace Aura.Core.Models { public class UserUpdateDto { [Required(ErrorMessage = "You should provide a name value.")] [MaxLength(50)] public string Name { get; set; } [Required(ErrorMessage = "You should provide a email value.")] public string Email { get; set; } } }
24.666667
70
0.637838
[ "MIT" ]
srdjanRakic/Aura
src/Aura.Core/Models/UserUpdateDto.cs
372
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 medialive-2017-10-14.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.MediaLive.Model { /// <summary> /// DVB Service Description Table (SDT) /// </summary> public partial class DvbSdtSettings { private DvbSdtOutputSdt _outputSdt; private int? _repInterval; private string _serviceName; private string _serviceProviderName; /// <summary> /// Gets and sets the property OutputSdt. Selects method of inserting SDT information /// into output stream. The sdtFollow setting copies SDT information from input stream /// to output stream. The sdtFollowIfPresent setting copies SDT information from input /// stream to output stream if SDT information is present in the input, otherwise it will /// fall back on the user-defined values. The sdtManual setting means user will enter /// the SDT information. The sdtNone setting means output stream will not contain SDT /// information. /// </summary> public DvbSdtOutputSdt OutputSdt { get { return this._outputSdt; } set { this._outputSdt = value; } } // Check to see if OutputSdt property is set internal bool IsSetOutputSdt() { return this._outputSdt != null; } /// <summary> /// Gets and sets the property RepInterval. The number of milliseconds between instances /// of this table in the output transport stream. /// </summary> public int RepInterval { get { return this._repInterval.GetValueOrDefault(); } set { this._repInterval = value; } } // Check to see if RepInterval property is set internal bool IsSetRepInterval() { return this._repInterval.HasValue; } /// <summary> /// Gets and sets the property ServiceName. The service name placed in the serviceDescriptor /// in the Service Description Table. Maximum length is 256 characters. /// </summary> public string ServiceName { get { return this._serviceName; } set { this._serviceName = value; } } // Check to see if ServiceName property is set internal bool IsSetServiceName() { return this._serviceName != null; } /// <summary> /// Gets and sets the property ServiceProviderName. The service provider name placed in /// the serviceDescriptor in the Service Description Table. Maximum length is 256 characters. /// </summary> public string ServiceProviderName { get { return this._serviceProviderName; } set { this._serviceProviderName = value; } } // Check to see if ServiceProviderName property is set internal bool IsSetServiceProviderName() { return this._serviceProviderName != null; } } }
34.754545
107
0.640335
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/MediaLive/Generated/Model/DvbSdtSettings.cs
3,823
C#
// // Copyright (c) Microsoft and contributors. 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. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.AzureStack.Management; using Microsoft.AzureStack.Management.Models; namespace Microsoft.AzureStack.Management { public static partial class ManagedOfferOperationsExtensions { /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedOfferOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='parameters'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static ManagedOfferCreateOrUpdateResult CreateOrUpdate(this IManagedOfferOperations operations, string resourceGroupName, ManagedOfferCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IManagedOfferOperations)s).CreateOrUpdateAsync(resourceGroupName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedOfferOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='parameters'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static Task<ManagedOfferCreateOrUpdateResult> CreateOrUpdateAsync(this IManagedOfferOperations operations, string resourceGroupName, ManagedOfferCreateOrUpdateParameters parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, parameters, CancellationToken.None); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedOfferOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='offerId'> /// Required. Your documentation here. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Delete(this IManagedOfferOperations operations, string resourceGroupName, string offerId) { return Task.Factory.StartNew((object s) => { return ((IManagedOfferOperations)s).DeleteAsync(resourceGroupName, offerId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedOfferOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='offerId'> /// Required. Your documentation here. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteAsync(this IManagedOfferOperations operations, string resourceGroupName, string offerId) { return operations.DeleteAsync(resourceGroupName, offerId, CancellationToken.None); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedOfferOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='offerId'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static ManagedOfferGetResult Get(this IManagedOfferOperations operations, string resourceGroupName, string offerId) { return Task.Factory.StartNew((object s) => { return ((IManagedOfferOperations)s).GetAsync(resourceGroupName, offerId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedOfferOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='offerId'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static Task<ManagedOfferGetResult> GetAsync(this IManagedOfferOperations operations, string resourceGroupName, string offerId) { return operations.GetAsync(resourceGroupName, offerId, CancellationToken.None); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedOfferOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='offerId'> /// Required. Your documentation here. /// </param> /// <param name='metricDefinitionId'> /// Required. Your documentation here. /// </param> /// <param name='filter'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static ManagedOfferGetMetricDefinitionsResult GetMetricDefinitions(this IManagedOfferOperations operations, string resourceGroupName, string offerId, string metricDefinitionId, string filter) { return Task.Factory.StartNew((object s) => { return ((IManagedOfferOperations)s).GetMetricDefinitionsAsync(resourceGroupName, offerId, metricDefinitionId, filter); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedOfferOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='offerId'> /// Required. Your documentation here. /// </param> /// <param name='metricDefinitionId'> /// Required. Your documentation here. /// </param> /// <param name='filter'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static Task<ManagedOfferGetMetricDefinitionsResult> GetMetricDefinitionsAsync(this IManagedOfferOperations operations, string resourceGroupName, string offerId, string metricDefinitionId, string filter) { return operations.GetMetricDefinitionsAsync(resourceGroupName, offerId, metricDefinitionId, filter, CancellationToken.None); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedOfferOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='offerId'> /// Required. Your documentation here. /// </param> /// <param name='metricId'> /// Required. Your documentation here. /// </param> /// <param name='filter'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static ManagedOfferGetMetricsResult GetMetrics(this IManagedOfferOperations operations, string resourceGroupName, string offerId, string metricId, string filter) { return Task.Factory.StartNew((object s) => { return ((IManagedOfferOperations)s).GetMetricsAsync(resourceGroupName, offerId, metricId, filter); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedOfferOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='offerId'> /// Required. Your documentation here. /// </param> /// <param name='metricId'> /// Required. Your documentation here. /// </param> /// <param name='filter'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static Task<ManagedOfferGetMetricsResult> GetMetricsAsync(this IManagedOfferOperations operations, string resourceGroupName, string offerId, string metricId, string filter) { return operations.GetMetricsAsync(resourceGroupName, offerId, metricId, filter, CancellationToken.None); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedOfferOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='offerName'> /// Required. Your documentation here. /// </param> /// <param name='parameters'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static ManagedOfferLinkResult Link(this IManagedOfferOperations operations, string resourceGroupName, string offerName, ManagedOfferLinkParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IManagedOfferOperations)s).LinkAsync(resourceGroupName, offerName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedOfferOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='offerName'> /// Required. Your documentation here. /// </param> /// <param name='parameters'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static Task<ManagedOfferLinkResult> LinkAsync(this IManagedOfferOperations operations, string resourceGroupName, string offerName, ManagedOfferLinkParameters parameters) { return operations.LinkAsync(resourceGroupName, offerName, parameters, CancellationToken.None); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedOfferOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='includeDetails'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static ManagedOfferListResult List(this IManagedOfferOperations operations, string resourceGroupName, bool includeDetails) { return Task.Factory.StartNew((object s) => { return ((IManagedOfferOperations)s).ListAsync(resourceGroupName, includeDetails); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedOfferOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='includeDetails'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static Task<ManagedOfferListResult> ListAsync(this IManagedOfferOperations operations, string resourceGroupName, bool includeDetails) { return operations.ListAsync(resourceGroupName, includeDetails, CancellationToken.None); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedOfferOperations. /// </param> /// <param name='nextLink'> /// Required. Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </param> /// <returns> /// Your documentation here. /// </returns> public static ManagedOfferListResult ListNext(this IManagedOfferOperations operations, string nextLink) { return Task.Factory.StartNew((object s) => { return ((IManagedOfferOperations)s).ListNextAsync(nextLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedOfferOperations. /// </param> /// <param name='nextLink'> /// Required. Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </param> /// <returns> /// Your documentation here. /// </returns> public static Task<ManagedOfferListResult> ListNextAsync(this IManagedOfferOperations operations, string nextLink) { return operations.ListNextAsync(nextLink, CancellationToken.None); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedOfferOperations. /// </param> /// <param name='includeDetails'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static ManagedOfferListResult ListWithoutResourceGroup(this IManagedOfferOperations operations, bool includeDetails) { return Task.Factory.StartNew((object s) => { return ((IManagedOfferOperations)s).ListWithoutResourceGroupAsync(includeDetails); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedOfferOperations. /// </param> /// <param name='includeDetails'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static Task<ManagedOfferListResult> ListWithoutResourceGroupAsync(this IManagedOfferOperations operations, bool includeDetails) { return operations.ListWithoutResourceGroupAsync(includeDetails, CancellationToken.None); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedOfferOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='offerName'> /// Required. Your documentation here. /// </param> /// <param name='parameters'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static ManagedOfferUnlinkResult Unlink(this IManagedOfferOperations operations, string resourceGroupName, string offerName, ManagedOfferUnlinkParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IManagedOfferOperations)s).UnlinkAsync(resourceGroupName, offerName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedOfferOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='offerName'> /// Required. Your documentation here. /// </param> /// <param name='parameters'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static Task<ManagedOfferUnlinkResult> UnlinkAsync(this IManagedOfferOperations operations, string resourceGroupName, string offerName, ManagedOfferUnlinkParameters parameters) { return operations.UnlinkAsync(resourceGroupName, offerName, parameters, CancellationToken.None); } } }
41.507965
217
0.596026
[ "Apache-2.0" ]
CerebralMischief/azure-sdk-for-net
src/ResourceManagement/AzureStackAdmin/AzureStackManagement/Generated/ManagedOfferOperationsExtensions.cs
23,452
C#
using System; using System.Xml; using System.Collections.Generic; using System.Linq; using VisuMap.Plugin; using VisuMap.Script; namespace VisuMap.GeneticAnalysis { public class LevenshteinMetric : IMetric { string[] motifs; public LevenshteinMetric() { } public void Initialize(IDataset dataset, XmlElement filterNode) { motifs = new string[dataset.Rows]; for (int row = 0; row < dataset.Rows; row++) { motifs[row] = dataset.GetDataAt(row, 0); } maxLength = motifs.Max(s => s.Length); mem1 = null; // This is only for the single threaded execution. } static void Swap<T>(ref T arg1,ref T arg2) { T temp = arg1; arg1 = arg2; arg2 = temp; } int maxLength; // the maximal string length allowd [ThreadStatic] static int[] mem1, mem2, mem3; void InitThreadMemory(int maxi) { if (mem1 == null) { mem1 = new int[maxLength+1]; mem2 = new int[maxLength+1]; mem3 = new int[maxLength+1]; } else { Array.Clear(mem1, 0, maxi + 1); Array.Clear(mem2, 0, maxi + 1); Array.Clear(mem3, 0, maxi + 1); } } // // The following implementation is obtained from: // http://stackoverflow.com/questions/9453731/how-to-calculate-distance-similarity-measure-of-given-2-strings // public double Distance(int idxI, int idxJ) { string source = motifs[idxI]; string target = motifs[idxJ]; int length1 = source.Length; int length2 = target.Length; // Ensure arrays [i] / length1 use shorter length if (length1 > length2) { Swap(ref target, ref source); Swap(ref length1, ref length2); } int maxi = length1; int maxj = length2; InitThreadMemory(maxi); int[] dCurrent = mem1; int[] dMinus1 = mem2; int[] dMinus2 = mem3; int[] dSwap; for (int i = 0; i <= maxi; i++) { dCurrent[i] = i; } int jm1 = 0, im1 = 0, im2 = -1; for (int j = 1; j <= maxj; j++) { // Rotate dSwap = dMinus2; dMinus2 = dMinus1; dMinus1 = dCurrent; dCurrent = dSwap; // Initialize int minDistance = int.MaxValue; dCurrent[0] = j; im1 = 0; im2 = -1; for (int i = 1; i <= maxi; i++) { int cost = source[im1] == target[jm1] ? 0 : 1; int del = dCurrent[im1] + 1; int ins = dMinus1[i] + 1; int sub = dMinus1[im1] + cost; //Fastest execution for min value of 3 integers int min = (del > ins) ? (ins > sub ? sub : ins) : (del > sub ? sub : del); if (i > 1 && j > 1 && source[im2] == target[jm1] && source[im1] == target[j - 2]) min = Math.Min(min, dMinus2[im2] + cost); dCurrent[i] = min; if (min < minDistance) { minDistance = min; } im1++; im2++; } jm1++; } return dCurrent[maxi]; } public string Name { get { return "Seq.Levenshtein"; } set { ; } } public bool IsApplicable(IDataset dataset) { if ((dataset.Columns > 0) && (dataset.ColumnSpecList[0].DataType == 'e')) return true; else return false; } public bool IsApplicable(IDataset dataset, XmlElement filterNode) { return false; } public IFilterEditor FilterEditor { get { return null; } } } }
30
117
0.463235
[ "MIT" ]
VisuMap/OpenVisuMap
GeneticAnalysis/LevenshteinMetric.cs
4,082
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DriftingAI : MonoBehaviour { public float maxRadiusFromCenter; public float driftInterval; public float stayAtTargetDuration; private EnemyMovement movement; private Vector2 currentTarget = Vector2.zero; private float nextDriftTime = 0; private float stopMovingTime = 0; // 0 means we're at our starting position. 1 means we're at our target. private float progressToTarget; private Vector2 vectorFromStartToTarget; // Start is called before the first frame update void Start() { this.movement = GetComponentInParent<EnemyMovement>(); } // Update is called once per frame void FixedUpdate() { if (this.nextDriftTime <= Time.time) { this.PickNewTarget(); } else if (this.stopMovingTime > Time.time) { // Compute how far we should move towards the target in this frame. float movementDuration = this.driftInterval - this.stayAtTargetDuration; float t = (movementDuration - (this.stopMovingTime - Time.time)) / movementDuration; float previousProgress = this.progressToTarget; this.progressToTarget = Mathf.SmoothStep(0f, 1f, t); Vector2 displacement = vectorFromStartToTarget * (this.progressToTarget - previousProgress); this.movement.Move(displacement); } } private void PickNewTarget() { float magnitude = Random.value * this.maxRadiusFromCenter; float angle = Random.value * Mathf.PI * 2f; Vector2 nextTarget = V2.FromMagnitudeAngle(magnitude, angle); this.vectorFromStartToTarget = nextTarget - this.currentTarget; this.currentTarget = nextTarget; this.progressToTarget = 0; this.stopMovingTime = Time.time + this.driftInterval - this.stayAtTargetDuration; this.nextDriftTime = Time.time + this.driftInterval; } }
34.40678
104
0.669951
[ "MIT" ]
kukushie/kukushie-dev-stream-shmup
Kukushie's Dev Stream Shmup/Assets/Scripts/AI/Movement/DriftingAI.cs
2,032
C#
namespace PrivateWiki.Core.DebugMode { public class GetDebugMode : IQuery<DebugMode> { } }
22.75
50
0.78022
[ "MIT" ]
lampenlampen/PrivateWiki
PrivateWiki/Core/DebugMode/GetDebugMode.cs
91
C#
/* * Ory APIs * * Documentation for all public and administrative Ory APIs. Administrative APIs can only be accessed with a valid Personal Access Token. Public APIs are mostly used in browsers. * * The version of the OpenAPI document: v0.0.1-alpha.3 * Contact: support@ory.sh * Generated by: https://github.com/openapitools/openapi-generator.git */ using Xunit; using System; using System.Linq; using System.IO; using System.Collections.Generic; using Ory.Client.Api; using Ory.Client.Model; using Ory.Client.Client; using System.Reflection; using Newtonsoft.Json; namespace Ory.Client.Test.Model { /// <summary> /// Class for testing ClientVolumeUsageData /// </summary> /// <remarks> /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the model. /// </remarks> public class ClientVolumeUsageDataTests : IDisposable { // TODO uncomment below to declare an instance variable for ClientVolumeUsageData //private ClientVolumeUsageData instance; public ClientVolumeUsageDataTests() { // TODO uncomment below to create an instance of ClientVolumeUsageData //instance = new ClientVolumeUsageData(); } public void Dispose() { // Cleanup when everything is done. } /// <summary> /// Test an instance of ClientVolumeUsageData /// </summary> [Fact] public void ClientVolumeUsageDataInstanceTest() { // TODO uncomment below to test "IsType" ClientVolumeUsageData //Assert.IsType<ClientVolumeUsageData>(instance); } /// <summary> /// Test the property 'RefCount' /// </summary> [Fact] public void RefCountTest() { // TODO unit test for the property 'RefCount' } /// <summary> /// Test the property 'Size' /// </summary> [Fact] public void SizeTest() { // TODO unit test for the property 'Size' } } }
26.9625
179
0.62216
[ "Apache-2.0" ]
Stackwalkerllc/sdk
clients/client/dotnet/src/Ory.Client.Test/Model/ClientVolumeUsageDataTests.cs
2,157
C#
/* * MoesifAPI.PCL * */ using System; using System.IO; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Moesif.Api; namespace Moesif.Api.Models { public class UserModel: INotifyPropertyChanged { // These fields hold the values for the public properties. private DateTime? modifiedTime; private string sessionToken; private string ipAddress; private string userId; private string companyId; private string userAgentString; private object metadata; private CampaignModel campaign; /// <summary> /// Time when request was made /// </summary> [JsonProperty("modified_time")] public DateTime ModifiedTime { get { return this.modifiedTime??DateTime.UtcNow; } set { this.modifiedTime = value; onPropertyChanged("ModifiedTime"); } } /// <summary> /// End user's auth/session token /// </summary> [JsonProperty("session_token")] public string SessionToken { get { return this.sessionToken; } set { this.sessionToken = value; onPropertyChanged("SessionToken"); } } /// <summary> /// End user's ip address /// </summary> [JsonProperty("ip_address")] public string IpAddress { get { return this.ipAddress; } set { this.ipAddress = value; onPropertyChanged("IpAddress"); } } /// <summary> /// End user's user_id string from your app /// </summary> [JsonProperty("user_id")] public string UserId { get { return this.userId; } set { this.userId = value; onPropertyChanged("UserId"); } } /// <summary> /// End user's company_id string from your app /// </summary> [JsonProperty("company_id")] public string CompanyId { get { return this.companyId; } set { this.companyId = value; onPropertyChanged("CompanyId"); } } /// <summary> /// End user's user_agent_string string from your app /// </summary> [JsonProperty("user_agent_string")] public string UserAgentString { get { return this.userAgentString; } set { this.userAgentString = value; onPropertyChanged("UserAgentString"); } } /// <summary> /// Metadata from your app, see documentation /// </summary> [JsonProperty("metadata")] public object Metadata { get { return this.metadata; } set { this.metadata = value; onPropertyChanged("Metadata"); } } /// <summary> /// Campaign object /// </summary> [JsonProperty("campaign")] public CampaignModel Campaign { get { return this.campaign; } set { this.campaign = value; onPropertyChanged("Campaign"); } } /// <summary> /// Property changed event for observer pattern /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises event when a property is changed /// </summary> /// <param name="propertyName">Name of the changed property</param> protected void onPropertyChanged(String propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }
24.464865
82
0.46973
[ "Apache-2.0" ]
Moesif/moesifapi-csharp
Moesif.Api/Models/UserModel.cs
4,528
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 sagemaker-2017-07-24.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.SageMaker.Model { /// <summary> /// This is the response object from the DescribeInferenceRecommendationsJob operation. /// </summary> public partial class DescribeInferenceRecommendationsJobResponse : AmazonWebServiceResponse { private DateTime? _completionTime; private DateTime? _creationTime; private string _failureReason; private List<InferenceRecommendation> _inferenceRecommendations = new List<InferenceRecommendation>(); private RecommendationJobInputConfig _inputConfig; private string _jobArn; private string _jobDescription; private string _jobName; private RecommendationJobType _jobType; private DateTime? _lastModifiedTime; private string _roleArn; private RecommendationJobStatus _status; private RecommendationJobStoppingConditions _stoppingConditions; /// <summary> /// Gets and sets the property CompletionTime. /// <para> /// A timestamp that shows when the job completed. /// </para> /// </summary> public DateTime CompletionTime { get { return this._completionTime.GetValueOrDefault(); } set { this._completionTime = value; } } // Check to see if CompletionTime property is set internal bool IsSetCompletionTime() { return this._completionTime.HasValue; } /// <summary> /// Gets and sets the property CreationTime. /// <para> /// A timestamp that shows when the job was created. /// </para> /// </summary> [AWSProperty(Required=true)] public DateTime CreationTime { get { return this._creationTime.GetValueOrDefault(); } set { this._creationTime = value; } } // Check to see if CreationTime property is set internal bool IsSetCreationTime() { return this._creationTime.HasValue; } /// <summary> /// Gets and sets the property FailureReason. /// <para> /// If the job fails, provides information why the job failed. /// </para> /// </summary> [AWSProperty(Max=1024)] public string FailureReason { get { return this._failureReason; } set { this._failureReason = value; } } // Check to see if FailureReason property is set internal bool IsSetFailureReason() { return this._failureReason != null; } /// <summary> /// Gets and sets the property InferenceRecommendations. /// <para> /// The recommendations made by Inference Recommender. /// </para> /// </summary> [AWSProperty(Min=1, Max=10)] public List<InferenceRecommendation> InferenceRecommendations { get { return this._inferenceRecommendations; } set { this._inferenceRecommendations = value; } } // Check to see if InferenceRecommendations property is set internal bool IsSetInferenceRecommendations() { return this._inferenceRecommendations != null && this._inferenceRecommendations.Count > 0; } /// <summary> /// Gets and sets the property InputConfig. /// <para> /// Returns information about the versioned model package Amazon Resource Name (ARN), /// the traffic pattern, and endpoint configurations you provided when you initiated the /// job. /// </para> /// </summary> [AWSProperty(Required=true)] public RecommendationJobInputConfig InputConfig { get { return this._inputConfig; } set { this._inputConfig = value; } } // Check to see if InputConfig property is set internal bool IsSetInputConfig() { return this._inputConfig != null; } /// <summary> /// Gets and sets the property JobArn. /// <para> /// The Amazon Resource Name (ARN) of the job. /// </para> /// </summary> [AWSProperty(Required=true, Max=256)] public string JobArn { get { return this._jobArn; } set { this._jobArn = value; } } // Check to see if JobArn property is set internal bool IsSetJobArn() { return this._jobArn != null; } /// <summary> /// Gets and sets the property JobDescription. /// <para> /// The job description that you provided when you initiated the job. /// </para> /// </summary> [AWSProperty(Max=128)] public string JobDescription { get { return this._jobDescription; } set { this._jobDescription = value; } } // Check to see if JobDescription property is set internal bool IsSetJobDescription() { return this._jobDescription != null; } /// <summary> /// Gets and sets the property JobName. /// <para> /// The name of the job. The name must be unique within an Amazon Web Services Region /// in the Amazon Web Services account. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=64)] public string JobName { get { return this._jobName; } set { this._jobName = value; } } // Check to see if JobName property is set internal bool IsSetJobName() { return this._jobName != null; } /// <summary> /// Gets and sets the property JobType. /// <para> /// The job type that you provided when you initiated the job. /// </para> /// </summary> [AWSProperty(Required=true)] public RecommendationJobType JobType { get { return this._jobType; } set { this._jobType = value; } } // Check to see if JobType property is set internal bool IsSetJobType() { return this._jobType != null; } /// <summary> /// Gets and sets the property LastModifiedTime. /// <para> /// A timestamp that shows when the job was last modified. /// </para> /// </summary> [AWSProperty(Required=true)] public DateTime LastModifiedTime { get { return this._lastModifiedTime.GetValueOrDefault(); } set { this._lastModifiedTime = value; } } // Check to see if LastModifiedTime property is set internal bool IsSetLastModifiedTime() { return this._lastModifiedTime.HasValue; } /// <summary> /// Gets and sets the property RoleArn. /// <para> /// The Amazon Resource Name (ARN) of the Amazon Web Services Identity and Access Management /// (IAM) role you provided when you initiated the job. /// </para> /// </summary> [AWSProperty(Required=true, Min=20, Max=2048)] public string RoleArn { get { return this._roleArn; } set { this._roleArn = value; } } // Check to see if RoleArn property is set internal bool IsSetRoleArn() { return this._roleArn != null; } /// <summary> /// Gets and sets the property Status. /// <para> /// The status of the job. /// </para> /// </summary> [AWSProperty(Required=true)] public RecommendationJobStatus Status { get { return this._status; } set { this._status = value; } } // Check to see if Status property is set internal bool IsSetStatus() { return this._status != null; } /// <summary> /// Gets and sets the property StoppingConditions. /// <para> /// The stopping conditions that you provided when you initiated the job. /// </para> /// </summary> public RecommendationJobStoppingConditions StoppingConditions { get { return this._stoppingConditions; } set { this._stoppingConditions = value; } } // Check to see if StoppingConditions property is set internal bool IsSetStoppingConditions() { return this._stoppingConditions != null; } } }
31.763333
110
0.575716
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/src/Services/SageMaker/Generated/Model/DescribeInferenceRecommendationsJobResponse.cs
9,529
C#
// _ _ _ ____ _ _____ // / \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___ // / _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \ // / ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | | // /_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_| // | // Copyright 2015-2020 Łukasz "JustArchi" Domeradzki // Contact: JustArchi@JustArchi.net // | // 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; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Specialized; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using ArchiSteamFarm.Collections; using ArchiSteamFarm.Localization; using ArchiSteamFarm.NLog; using ArchiSteamFarm.Plugins; using JetBrains.Annotations; using Newtonsoft.Json; using SteamKit2; using SteamKit2.Unified.Internal; namespace ArchiSteamFarm { public sealed class Bot : IDisposable { internal const ushort CallbackSleep = 500; // In milliseconds internal const ushort MaxMessagePrefixLength = MaxMessageLength - ReservedMessageLength - 2; // 2 for a minimum of 2 characters (escape one and real one) internal const byte MinPlayingBlockedTTL = 60; // Delay in seconds added when account was occupied during our disconnect, to not disconnect other Steam client session too soon private const char DefaultBackgroundKeysRedeemerSeparator = '\t'; private const byte LoginCooldownInMinutes = 25; // Captcha disappears after around 20 minutes, so we make it 25 private const uint LoginID = 1242; // This must be the same for all ASF bots and all ASF processes private const ushort MaxMessageLength = 5000; // This is a limitation enforced by Steam private const byte MaxTwoFactorCodeFailures = WebBrowser.MaxTries; // Max TwoFactorCodeMismatch failures in a row before we determine that our 2FA credentials are invalid (because Steam wrongly returns those, of course) private const byte RedeemCooldownInHours = 1; // 1 hour since first redeem attempt, this is a limitation enforced by Steam private const byte ReservedMessageLength = 2; // 2 for 2x optional … [PublicAPI] public static IReadOnlyDictionary<string, Bot> BotsReadOnly => Bots; internal static ConcurrentDictionary<string, Bot> Bots { get; private set; } internal static StringComparer BotsComparer { get; private set; } internal static EOSType OSType { get; private set; } = EOSType.Unknown; private static readonly SemaphoreSlim BotsSemaphore = new SemaphoreSlim(1, 1); private static readonly SemaphoreSlim LoginRateLimitingSemaphore = new SemaphoreSlim(1, 1); private static readonly SemaphoreSlim LoginSemaphore = new SemaphoreSlim(1, 1); [JsonIgnore] [PublicAPI] public readonly Actions Actions; [JsonIgnore] [PublicAPI] public readonly ArchiLogger ArchiLogger; [JsonIgnore] [PublicAPI] public readonly ArchiWebHandler ArchiWebHandler; [JsonProperty] [PublicAPI] public readonly string BotName; [JsonProperty] [PublicAPI] public readonly CardsFarmer CardsFarmer; [JsonIgnore] [PublicAPI] public readonly Commands Commands; [JsonIgnore] [PublicAPI] public readonly SteamConfiguration SteamConfiguration; [JsonProperty] [PublicAPI] public uint GamesToRedeemInBackgroundCount => BotDatabase?.GamesToRedeemInBackgroundCount ?? 0; [JsonProperty] [PublicAPI] public bool IsConnectedAndLoggedOn => SteamClient?.SteamID != null; [JsonProperty] [PublicAPI] public bool IsPlayingPossible => !PlayingBlocked && !LibraryLocked; internal readonly ArchiHandler ArchiHandler; internal readonly BotDatabase BotDatabase; internal readonly ConcurrentDictionary<uint, (EPaymentMethod PaymentMethod, DateTime TimeCreated)> OwnedPackageIDs = new ConcurrentDictionary<uint, (EPaymentMethod PaymentMethod, DateTime TimeCreated)>(); internal readonly SteamApps SteamApps; internal readonly SteamFriends SteamFriends; internal bool CanReceiveSteamCards => !IsAccountLimited && !IsAccountLocked; internal bool HasMobileAuthenticator => BotDatabase?.MobileAuthenticator != null; internal bool IsAccountLimited => AccountFlags.HasFlag(EAccountFlags.LimitedUser) || AccountFlags.HasFlag(EAccountFlags.LimitedUserForce); internal bool IsAccountLocked => AccountFlags.HasFlag(EAccountFlags.Lockdown); private readonly CallbackManager CallbackManager; private readonly SemaphoreSlim CallbackSemaphore = new SemaphoreSlim(1, 1); private readonly SemaphoreSlim GamesRedeemerInBackgroundSemaphore = new SemaphoreSlim(1, 1); private readonly Timer HeartBeatTimer; private readonly SemaphoreSlim InitializationSemaphore = new SemaphoreSlim(1, 1); private readonly SemaphoreSlim MessagingSemaphore = new SemaphoreSlim(1, 1); private readonly ConcurrentDictionary<ArchiHandler.UserNotificationsCallback.EUserNotification, uint> PastNotifications = new ConcurrentDictionary<ArchiHandler.UserNotificationsCallback.EUserNotification, uint>(); private readonly SemaphoreSlim PICSSemaphore = new SemaphoreSlim(1, 1); private readonly Statistics Statistics; private readonly SteamClient SteamClient; private readonly ConcurrentHashSet<ulong> SteamFamilySharingIDs = new ConcurrentHashSet<ulong>(); private readonly SteamUser SteamUser; private readonly Trading Trading; private IEnumerable<(string FilePath, EFileType FileType)> RelatedFiles { get { foreach (EFileType fileType in Enum.GetValues(typeof(EFileType))) { string filePath = GetFilePath(fileType); if (string.IsNullOrEmpty(filePath)) { ArchiLogger.LogNullError(nameof(filePath)); yield break; } yield return (filePath, fileType); } } } #pragma warning disable IDE0051 [JsonProperty(PropertyName = SharedInfo.UlongCompatibilityStringPrefix + nameof(SteamID))] [JetBrains.Annotations.NotNull] private string SSteamID => SteamID.ToString(); #pragma warning restore IDE0051 [JsonProperty] public EAccountFlags AccountFlags { get; private set; } [JsonProperty] public BotConfig BotConfig { get; private set; } [JsonProperty] public bool KeepRunning { get; private set; } [JsonProperty] public string Nickname { get; private set; } [PublicAPI] public ulong SteamID { get; private set; } [PublicAPI] public long WalletBalance { get; private set; } [PublicAPI] public ECurrencyCode WalletCurrency { get; private set; } internal bool PlayingBlocked { get; private set; } internal bool PlayingWasBlocked { get; private set; } private string AuthCode; #pragma warning disable IDE0052 [JsonProperty] private string AvatarHash; #pragma warning restore IDE0052 private Timer ConnectionFailureTimer; private string DeviceID; private bool FirstTradeSent; private Timer GamesRedeemerInBackgroundTimer; private byte HeartBeatFailures; private EResult LastLogOnResult; private DateTime LastLogonSessionReplaced; private bool LibraryLocked; private ulong MasterChatGroupID; private Timer PlayingWasBlockedTimer; private bool ReconnectOnUserInitiated; private Timer SendItemsTimer; private bool SteamParentalActive = true; private SteamSaleEvent SteamSaleEvent; private string TwoFactorCode; private byte TwoFactorCodeFailures; private Bot([JetBrains.Annotations.NotNull] string botName, [JetBrains.Annotations.NotNull] BotConfig botConfig, [JetBrains.Annotations.NotNull] BotDatabase botDatabase) { if (string.IsNullOrEmpty(botName) || (botConfig == null) || (botDatabase == null)) { throw new ArgumentNullException(nameof(botName) + " || " + nameof(botConfig) + " || " + nameof(botDatabase)); } BotName = botName; BotConfig = botConfig; BotDatabase = botDatabase; ArchiLogger = new ArchiLogger(botName); if (HasMobileAuthenticator) { BotDatabase.MobileAuthenticator.Init(this); } ArchiWebHandler = new ArchiWebHandler(this); SteamConfiguration = SteamConfiguration.Create(builder => builder.WithProtocolTypes(ASF.GlobalConfig.SteamProtocols).WithCellID(ASF.GlobalDatabase.CellID).WithServerListProvider(ASF.GlobalDatabase.ServerListProvider).WithHttpClientFactory(ArchiWebHandler.GenerateDisposableHttpClient)); // Initialize SteamClient = new SteamClient(SteamConfiguration); if (Debugging.IsUserDebugging && Directory.Exists(SharedInfo.DebugDirectory)) { string debugListenerPath = Path.Combine(SharedInfo.DebugDirectory, botName); try { Directory.CreateDirectory(debugListenerPath); SteamClient.DebugNetworkListener = new NetHookNetworkListener(debugListenerPath); } catch (Exception e) { ArchiLogger.LogGenericException(e); } } SteamUnifiedMessages steamUnifiedMessages = SteamClient.GetHandler<SteamUnifiedMessages>(); ArchiHandler = new ArchiHandler(ArchiLogger, steamUnifiedMessages); SteamClient.AddHandler(ArchiHandler); CallbackManager = new CallbackManager(SteamClient); CallbackManager.Subscribe<SteamClient.ConnectedCallback>(OnConnected); CallbackManager.Subscribe<SteamClient.DisconnectedCallback>(OnDisconnected); SteamApps = SteamClient.GetHandler<SteamApps>(); CallbackManager.Subscribe<SteamApps.GuestPassListCallback>(OnGuestPassList); CallbackManager.Subscribe<SteamApps.LicenseListCallback>(OnLicenseList); SteamFriends = SteamClient.GetHandler<SteamFriends>(); CallbackManager.Subscribe<SteamFriends.FriendsListCallback>(OnFriendsList); CallbackManager.Subscribe<SteamFriends.PersonaStateCallback>(OnPersonaState); CallbackManager.Subscribe<SteamUnifiedMessages.ServiceMethodNotification>(OnServiceMethod); SteamUser = SteamClient.GetHandler<SteamUser>(); CallbackManager.Subscribe<SteamUser.LoggedOffCallback>(OnLoggedOff); CallbackManager.Subscribe<SteamUser.LoggedOnCallback>(OnLoggedOn); CallbackManager.Subscribe<SteamUser.LoginKeyCallback>(OnLoginKey); CallbackManager.Subscribe<SteamUser.UpdateMachineAuthCallback>(OnMachineAuth); CallbackManager.Subscribe<SteamUser.WalletInfoCallback>(OnWalletUpdate); CallbackManager.Subscribe<ArchiHandler.PlayingSessionStateCallback>(OnPlayingSessionState); CallbackManager.Subscribe<ArchiHandler.SharedLibraryLockStatusCallback>(OnSharedLibraryLockStatus); CallbackManager.Subscribe<ArchiHandler.UserNotificationsCallback>(OnUserNotifications); CallbackManager.Subscribe<ArchiHandler.VanityURLChangedCallback>(OnVanityURLChangedCallback); Actions = new Actions(this); CardsFarmer = new CardsFarmer(this); Commands = new Commands(this); Trading = new Trading(this); if (!Debugging.IsDebugBuild && ASF.GlobalConfig.Statistics) { Statistics = new Statistics(this); } HeartBeatTimer = new Timer( async e => await HeartBeat().ConfigureAwait(false), null, TimeSpan.FromMinutes(1) + TimeSpan.FromSeconds(ASF.LoadBalancingDelay * Bots.Count), // Delay TimeSpan.FromMinutes(1) // Period ); } public void Dispose() { // Those are objects that are always being created if constructor doesn't throw exception Actions.Dispose(); CallbackSemaphore.Dispose(); GamesRedeemerInBackgroundSemaphore.Dispose(); InitializationSemaphore.Dispose(); MessagingSemaphore.Dispose(); PICSSemaphore.Dispose(); // Those are objects that might be null and the check should be in-place ArchiWebHandler?.Dispose(); BotDatabase?.Dispose(); CardsFarmer?.Dispose(); ConnectionFailureTimer?.Dispose(); GamesRedeemerInBackgroundTimer?.Dispose(); HeartBeatTimer?.Dispose(); PlayingWasBlockedTimer?.Dispose(); SendItemsTimer?.Dispose(); Statistics?.Dispose(); SteamSaleEvent?.Dispose(); Trading?.Dispose(); } [PublicAPI] public static Bot GetBot(string botName) { if (string.IsNullOrEmpty(botName)) { ASF.ArchiLogger.LogNullError(nameof(botName)); return null; } if (Bots.TryGetValue(botName, out Bot targetBot)) { return targetBot; } if (!ulong.TryParse(botName, out ulong steamID) || (steamID == 0) || !new SteamID(steamID).IsIndividualAccount) { return null; } return Bots.Values.FirstOrDefault(bot => bot.SteamID == steamID); } [PublicAPI] public static HashSet<Bot> GetBots(string args) { if (string.IsNullOrEmpty(args)) { ASF.ArchiLogger.LogNullError(nameof(args)); return null; } string[] botNames = args.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); HashSet<Bot> result = new HashSet<Bot>(); foreach (string botName in botNames) { if (botName.Equals(SharedInfo.ASF, StringComparison.OrdinalIgnoreCase)) { IEnumerable<Bot> allBots = Bots.OrderBy(bot => bot.Key, BotsComparer).Select(bot => bot.Value); result.UnionWith(allBots); return result; } if (botName.Contains("..")) { string[] botRange = botName.Split(new[] { ".." }, StringSplitOptions.RemoveEmptyEntries); if (botRange.Length == 2) { Bot firstBot = GetBot(botRange[0]); if (firstBot != null) { Bot lastBot = GetBot(botRange[1]); if (lastBot != null) { foreach (Bot bot in Bots.OrderBy(bot => bot.Key, BotsComparer).Select(bot => bot.Value).SkipWhile(bot => bot != firstBot)) { result.Add(bot); if (bot == lastBot) { break; } } continue; } } } } if (botName.StartsWith("r!", StringComparison.OrdinalIgnoreCase)) { string botsPattern = botName.Substring(2); RegexOptions botsRegex = RegexOptions.None; if ((BotsComparer == StringComparer.InvariantCulture) || (BotsComparer == StringComparer.Ordinal)) { botsRegex |= RegexOptions.CultureInvariant; } else if ((BotsComparer == StringComparer.InvariantCultureIgnoreCase) || (BotsComparer == StringComparer.OrdinalIgnoreCase)) { botsRegex |= RegexOptions.CultureInvariant | RegexOptions.IgnoreCase; } Regex regex; try { regex = new Regex(botsPattern, botsRegex); } catch (ArgumentException e) { ASF.ArchiLogger.LogGenericWarningException(e); return null; } IEnumerable<Bot> regexMatches = Bots.Where(kvp => regex.IsMatch(kvp.Key)).Select(kvp => kvp.Value); result.UnionWith(regexMatches); continue; } Bot singleBot = GetBot(botName); if (singleBot == null) { continue; } result.Add(singleBot); } return result; } [PublicAPI] public async Task<byte?> GetTradeHoldDuration(ulong steamID, ulong tradeID) { if ((steamID == 0) || !new SteamID(steamID).IsIndividualAccount || (tradeID == 0)) { ArchiLogger.LogNullError(nameof(steamID) + " || " + nameof(tradeID)); return null; } if (SteamFriends.GetFriendRelationship(steamID) == EFriendRelationship.Friend) { byte? tradeHoldDurationForUser = await ArchiWebHandler.GetTradeHoldDurationForUser(steamID).ConfigureAwait(false); if (tradeHoldDurationForUser.HasValue) { return tradeHoldDurationForUser; } } Bot targetBot = Bots.Values.FirstOrDefault(bot => bot.SteamID == steamID); if (targetBot?.IsConnectedAndLoggedOn == true) { string targetTradeToken = await targetBot.ArchiHandler.GetTradeToken().ConfigureAwait(false); if (!string.IsNullOrEmpty(targetTradeToken)) { byte? tradeHoldDurationForUser = await ArchiWebHandler.GetTradeHoldDurationForUser(steamID, targetTradeToken).ConfigureAwait(false); if (tradeHoldDurationForUser.HasValue) { return tradeHoldDurationForUser; } } } return await ArchiWebHandler.GetTradeHoldDurationForTrade(tradeID).ConfigureAwait(false); } [PublicAPI] public bool HasPermission(ulong steamID, BotConfig.EPermission permission) { if ((steamID == 0) || !new SteamID(steamID).IsIndividualAccount || (permission == BotConfig.EPermission.None)) { ArchiLogger.LogNullError(nameof(steamID) + " || " + nameof(permission)); return false; } if (ASF.IsOwner(steamID)) { return true; } return permission switch { BotConfig.EPermission.FamilySharing when SteamFamilySharingIDs.Contains(steamID) => true, _ => BotConfig.SteamUserPermissions.TryGetValue(steamID, out BotConfig.EPermission realPermission) && (realPermission >= permission) }; } [PublicAPI] public void SetUserInput(ASF.EUserInputType inputType, string inputValue) { if ((inputType == ASF.EUserInputType.Unknown) || !Enum.IsDefined(typeof(ASF.EUserInputType), inputType) || string.IsNullOrEmpty(inputValue)) { ArchiLogger.LogNullError(nameof(inputType) + " || " + nameof(inputValue)); return; } // This switch should cover ONLY bot properties switch (inputType) { case ASF.EUserInputType.DeviceID: DeviceID = inputValue; break; case ASF.EUserInputType.Login: if (BotConfig != null) { BotConfig.SteamLogin = inputValue; } break; case ASF.EUserInputType.Password: if (BotConfig != null) { BotConfig.DecryptedSteamPassword = inputValue; } break; case ASF.EUserInputType.SteamGuard: AuthCode = inputValue; break; case ASF.EUserInputType.SteamParentalCode: if (BotConfig != null) { BotConfig.SteamParentalCode = inputValue; } break; case ASF.EUserInputType.TwoFactorAuthentication: TwoFactorCode = inputValue; break; default: ASF.ArchiLogger.LogGenericError(string.Format(Strings.WarningUnknownValuePleaseReport, nameof(inputType), inputType)); break; } } internal void AddGamesToRedeemInBackground(IOrderedDictionary gamesToRedeemInBackground) { if ((gamesToRedeemInBackground == null) || (gamesToRedeemInBackground.Count == 0)) { ArchiLogger.LogNullError(nameof(gamesToRedeemInBackground)); return; } BotDatabase.AddGamesToRedeemInBackground(gamesToRedeemInBackground); if ((GamesRedeemerInBackgroundTimer == null) && BotDatabase.HasGamesToRedeemInBackground && IsConnectedAndLoggedOn) { Utilities.InBackground(RedeemGamesInBackground); } } internal async Task<bool> DeleteAllRelatedFiles() { await BotDatabase.MakeReadOnly().ConfigureAwait(false); foreach (string filePath in RelatedFiles.Select(file => file.FilePath).Where(File.Exists)) { try { File.Delete(filePath); } catch (Exception e) { ArchiLogger.LogGenericException(e); return false; } } return true; } internal bool DeleteRedeemedKeysFiles() { string unusedKeysFilePath = GetFilePath(EFileType.KeysToRedeemUnused); if (string.IsNullOrEmpty(unusedKeysFilePath)) { ASF.ArchiLogger.LogNullError(nameof(unusedKeysFilePath)); return false; } if (File.Exists(unusedKeysFilePath)) { try { File.Delete(unusedKeysFilePath); } catch (Exception e) { ArchiLogger.LogGenericException(e); return false; } } string usedKeysFilePath = GetFilePath(EFileType.KeysToRedeemUsed); if (string.IsNullOrEmpty(usedKeysFilePath)) { ASF.ArchiLogger.LogNullError(nameof(usedKeysFilePath)); return false; } if (File.Exists(usedKeysFilePath)) { try { File.Delete(usedKeysFilePath); } catch (Exception e) { ArchiLogger.LogGenericException(e); return false; } } return true; } internal static string FormatBotResponse(string response, string botName) { if (string.IsNullOrEmpty(response) || string.IsNullOrEmpty(botName)) { ASF.ArchiLogger.LogNullError(nameof(response) + " || " + nameof(botName)); return null; } return Environment.NewLine + "<" + botName + "> " + response; } internal async Task<(uint PlayableAppID, DateTime IgnoredUntil, bool IgnoredGlobally)> GetAppDataForIdling(uint appID, float hoursPlayed, bool allowRecursiveDiscovery = true, bool optimisticDiscovery = true) { if ((appID == 0) || (hoursPlayed < 0)) { ArchiLogger.LogNullError(nameof(appID) + " || " + nameof(hoursPlayed)); return (0, DateTime.MaxValue, true); } HashSet<uint> packageIDs = ASF.GlobalDatabase.GetPackageIDs(appID, OwnedPackageIDs.Keys); if ((packageIDs == null) || (packageIDs.Count == 0)) { return (0, DateTime.MaxValue, true); } if ((hoursPlayed < CardsFarmer.HoursForRefund) && !BotConfig.IdleRefundableGames) { DateTime mostRecent = DateTime.MinValue; foreach (uint packageID in packageIDs) { if (!OwnedPackageIDs.TryGetValue(packageID, out (EPaymentMethod PaymentMethod, DateTime TimeCreated) packageData)) { continue; } if (IsRefundable(packageData.PaymentMethod) && (packageData.TimeCreated > mostRecent)) { mostRecent = packageData.TimeCreated; } } if (mostRecent > DateTime.MinValue) { DateTime playableIn = mostRecent.AddDays(CardsFarmer.DaysForRefund); if (playableIn > DateTime.UtcNow) { return (0, playableIn, false); } } } AsyncJobMultiple<SteamApps.PICSProductInfoCallback>.ResultSet productInfoResultSet = null; for (byte i = 0; (i < WebBrowser.MaxTries) && (productInfoResultSet == null) && IsConnectedAndLoggedOn; i++) { await PICSSemaphore.WaitAsync().ConfigureAwait(false); try { productInfoResultSet = await SteamApps.PICSGetProductInfo(appID, null, false); } catch (Exception e) { ArchiLogger.LogGenericWarningException(e); } finally { PICSSemaphore.Release(); } } if (productInfoResultSet == null) { return (optimisticDiscovery ? appID : 0, DateTime.MinValue, true); } foreach (Dictionary<uint, SteamApps.PICSProductInfoCallback.PICSProductInfo> productInfoApps in productInfoResultSet.Results.Select(result => result.Apps)) { if (!productInfoApps.TryGetValue(appID, out SteamApps.PICSProductInfoCallback.PICSProductInfo productInfoApp)) { continue; } KeyValue productInfo = productInfoApp.KeyValues; if (productInfo == KeyValue.Invalid) { ArchiLogger.LogNullError(nameof(productInfo)); break; } KeyValue commonProductInfo = productInfo["common"]; if (commonProductInfo == KeyValue.Invalid) { continue; } string releaseState = commonProductInfo["ReleaseState"].Value; if (!string.IsNullOrEmpty(releaseState)) { // We must convert this to uppercase, since Valve doesn't stick to any convention and we can have a case mismatch switch (releaseState.ToUpperInvariant()) { case "RELEASED": break; case "PRELOADONLY": case "PRERELEASE": return (0, DateTime.MaxValue, true); default: ArchiLogger.LogGenericError(string.Format(Strings.WarningUnknownValuePleaseReport, nameof(releaseState), releaseState)); break; } } string type = commonProductInfo["type"].Value; if (string.IsNullOrEmpty(type)) { return (appID, DateTime.MinValue, true); } // We must convert this to uppercase, since Valve doesn't stick to any convention and we can have a case mismatch switch (type.ToUpperInvariant()) { case "APPLICATION": case "EPISODE": case "GAME": case "MOD": case "MOVIE": case "SERIES": case "TOOL": case "VIDEO": // Types that can be idled return (appID, DateTime.MinValue, true); case "ADVERTISING": case "DEMO": case "DLC": case "GUIDE": case "HARDWARE": case "MUSIC": // Types that can't be idled break; default: ArchiLogger.LogGenericError(string.Format(Strings.WarningUnknownValuePleaseReport, nameof(type), type)); break; } if (!allowRecursiveDiscovery) { return (0, DateTime.MinValue, true); } string listOfDlc = productInfo["extended"]["listofdlc"].Value; if (string.IsNullOrEmpty(listOfDlc)) { return (appID, DateTime.MinValue, true); } string[] dlcAppIDsTexts = listOfDlc.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (string dlcAppIDsText in dlcAppIDsTexts) { if (!uint.TryParse(dlcAppIDsText, out uint dlcAppID) || (dlcAppID == 0)) { ArchiLogger.LogNullError(nameof(dlcAppID)); break; } (uint playableAppID, _, _) = await GetAppDataForIdling(dlcAppID, hoursPlayed, false, false).ConfigureAwait(false); if (playableAppID != 0) { return (playableAppID, DateTime.MinValue, true); } } return (appID, DateTime.MinValue, true); } return ((productInfoResultSet.Complete && !productInfoResultSet.Failed) || optimisticDiscovery ? appID : 0, DateTime.MinValue, true); } internal static string GetFilePath(string botName, EFileType fileType) { if (string.IsNullOrEmpty(botName) || !Enum.IsDefined(typeof(EFileType), fileType)) { ASF.ArchiLogger.LogNullError(nameof(botName) + " || " + nameof(fileType)); return null; } string botPath = Path.Combine(SharedInfo.ConfigDirectory, botName); switch (fileType) { case EFileType.Config: return botPath + SharedInfo.JsonConfigExtension; case EFileType.Database: return botPath + SharedInfo.DatabaseExtension; case EFileType.KeysToRedeem: return botPath + SharedInfo.KeysExtension; case EFileType.KeysToRedeemUnused: return botPath + SharedInfo.KeysExtension + SharedInfo.KeysUnusedExtension; case EFileType.KeysToRedeemUsed: return botPath + SharedInfo.KeysExtension + SharedInfo.KeysUsedExtension; case EFileType.MobileAuthenticator: return botPath + SharedInfo.MobileAuthenticatorExtension; case EFileType.SentryFile: return botPath + SharedInfo.SentryHashExtension; default: ASF.ArchiLogger.LogGenericError(string.Format(Strings.WarningUnknownValuePleaseReport, nameof(fileType), fileType)); return null; } } [ItemCanBeNull] internal async Task<HashSet<uint>> GetMarketableAppIDs() => await ArchiWebHandler.GetAppList().ConfigureAwait(false); [ItemCanBeNull] internal async Task<Dictionary<uint, (uint ChangeNumber, HashSet<uint> AppIDs)>> GetPackagesData(IReadOnlyCollection<uint> packageIDs) { if ((packageIDs == null) || (packageIDs.Count == 0)) { ArchiLogger.LogNullError(nameof(packageIDs)); return null; } AsyncJobMultiple<SteamApps.PICSProductInfoCallback>.ResultSet productInfoResultSet = null; for (byte i = 0; (i < WebBrowser.MaxTries) && (productInfoResultSet == null) && IsConnectedAndLoggedOn; i++) { await PICSSemaphore.WaitAsync().ConfigureAwait(false); try { productInfoResultSet = await SteamApps.PICSGetProductInfo(Enumerable.Empty<uint>(), packageIDs); } catch (Exception e) { ArchiLogger.LogGenericWarningException(e); } finally { PICSSemaphore.Release(); } } if (productInfoResultSet == null) { return null; } Dictionary<uint, (uint ChangeNumber, HashSet<uint> AppIDs)> result = new Dictionary<uint, (uint ChangeNumber, HashSet<uint> AppIDs)>(); foreach (SteamApps.PICSProductInfoCallback.PICSProductInfo productInfo in productInfoResultSet.Results.SelectMany(productInfoResult => productInfoResult.Packages).Where(productInfoPackages => productInfoPackages.Key != 0).Select(productInfoPackages => productInfoPackages.Value)) { if (productInfo.KeyValues == KeyValue.Invalid) { ArchiLogger.LogNullError(nameof(productInfo)); return null; } (uint ChangeNumber, HashSet<uint> AppIDs) value = (productInfo.ChangeNumber, null); try { KeyValue appIDs = productInfo.KeyValues["appids"]; if (appIDs == KeyValue.Invalid) { continue; } value.AppIDs = new HashSet<uint>(appIDs.Children.Count); foreach (string appIDText in appIDs.Children.Select(app => app.Value)) { if (!uint.TryParse(appIDText, out uint appID) || (appID == 0)) { ArchiLogger.LogNullError(nameof(appID)); return null; } value.AppIDs.Add(appID); } } finally { result[productInfo.ID] = value; } } return result; } internal async Task<(Dictionary<string, string> UnusedKeys, Dictionary<string, string> UsedKeys)> GetUsedAndUnusedKeys() { string unusedKeysFilePath = GetFilePath(EFileType.KeysToRedeemUnused); if (string.IsNullOrEmpty(unusedKeysFilePath)) { ASF.ArchiLogger.LogNullError(nameof(unusedKeysFilePath)); return (null, null); } string usedKeysFilePath = GetFilePath(EFileType.KeysToRedeemUsed); if (string.IsNullOrEmpty(usedKeysFilePath)) { ASF.ArchiLogger.LogNullError(nameof(usedKeysFilePath)); return (null, null); } string[] files = { unusedKeysFilePath, usedKeysFilePath }; IList<Dictionary<string, string>> results = await Utilities.InParallel(files.Select(GetKeysFromFile)).ConfigureAwait(false); return (results[0], results[1]); } internal async Task IdleGame(CardsFarmer.Game game) { if (game == null) { ArchiLogger.LogNullError(nameof(game)); return; } await ArchiHandler.PlayGames(game.PlayableAppID.ToEnumerable(), BotConfig.CustomGamePlayedWhileFarming).ConfigureAwait(false); } internal async Task IdleGames(IReadOnlyCollection<CardsFarmer.Game> games) { if ((games == null) || (games.Count == 0)) { ArchiLogger.LogNullError(nameof(games)); return; } await ArchiHandler.PlayGames(games.Select(game => game.PlayableAppID), BotConfig.CustomGamePlayedWhileFarming).ConfigureAwait(false); } internal async Task ImportKeysToRedeem(string filePath) { if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath)) { ArchiLogger.LogNullError(nameof(filePath)); return; } try { OrderedDictionary gamesToRedeemInBackground = new OrderedDictionary(); using (StreamReader reader = new StreamReader(filePath)) { string line; while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null) { if (line.Length == 0) { continue; } // Valid formats: // Key (name will be the same as key and replaced from redemption result, if possible) // Name + Key (user provides both, if name is equal to key, above logic is used, otherwise name is kept) // Name + <Ignored> + Key (BGR output format, we include extra properties in the middle, those are ignored during import) string[] parsedArgs = line.Split(DefaultBackgroundKeysRedeemerSeparator, StringSplitOptions.RemoveEmptyEntries); if (parsedArgs.Length < 1) { ArchiLogger.LogGenericWarning(string.Format(Strings.ErrorIsInvalid, line)); continue; } string name = parsedArgs[0]; string key = parsedArgs[parsedArgs.Length - 1]; gamesToRedeemInBackground[key] = name; } } if (gamesToRedeemInBackground.Count > 0) { IOrderedDictionary validGamesToRedeemInBackground = ValidateGamesToRedeemInBackground(gamesToRedeemInBackground); if ((validGamesToRedeemInBackground != null) && (validGamesToRedeemInBackground.Count > 0)) { AddGamesToRedeemInBackground(validGamesToRedeemInBackground); } } File.Delete(filePath); } catch (Exception e) { ArchiLogger.LogGenericException(e); } } internal static void Init(StringComparer botsComparer) { if (botsComparer == null) { ASF.ArchiLogger.LogNullError(nameof(botsComparer)); return; } if (Bots != null) { ASF.ArchiLogger.LogGenericError(Strings.WarningFailed); return; } BotsComparer = botsComparer; Bots = new ConcurrentDictionary<string, Bot>(botsComparer); } internal bool IsBlacklistedFromIdling(uint appID) { if (appID == 0) { ArchiLogger.LogNullError(nameof(appID)); return false; } return BotDatabase.IsBlacklistedFromIdling(appID); } internal bool IsBlacklistedFromTrades(ulong steamID) { if ((steamID == 0) || !new SteamID(steamID).IsIndividualAccount) { ArchiLogger.LogNullError(nameof(steamID)); return false; } return BotDatabase.IsBlacklistedFromTrades(steamID); } internal bool IsPriorityIdling(uint appID) { if (appID == 0) { ArchiLogger.LogNullError(nameof(appID)); return false; } return BotDatabase.IsPriorityIdling(appID); } internal async Task OnConfigChanged(bool deleted) { if (deleted) { await Destroy().ConfigureAwait(false); return; } string configFile = GetFilePath(EFileType.Config); if (string.IsNullOrEmpty(configFile)) { ArchiLogger.LogNullError(nameof(configFile)); return; } BotConfig botConfig = await BotConfig.Load(configFile).ConfigureAwait(false); if (botConfig == null) { await Destroy().ConfigureAwait(false); return; } if (botConfig == BotConfig) { return; } await InitializationSemaphore.WaitAsync().ConfigureAwait(false); try { if (botConfig == BotConfig) { return; } Stop(botConfig.Enabled); BotConfig = botConfig; await InitModules().ConfigureAwait(false); InitStart(); } finally { InitializationSemaphore.Release(); } } internal async Task OnFarmingFinished(bool farmedSomething) { await OnFarmingStopped().ConfigureAwait(false); if (BotConfig.SendOnFarmingFinished && (BotConfig.LootableTypes.Count > 0) && (farmedSomething || !FirstTradeSent)) { FirstTradeSent = true; await Actions.SendInventory(filterFunction: item => BotConfig.LootableTypes.Contains(item.Type)).ConfigureAwait(false); } if (BotConfig.ShutdownOnFarmingFinished) { Stop(); } await PluginsCore.OnBotFarmingFinished(this, farmedSomething).ConfigureAwait(false); } internal async Task OnFarmingStopped() { await ResetGamesPlayed().ConfigureAwait(false); await PluginsCore.OnBotFarmingStopped(this).ConfigureAwait(false); } internal async Task<bool> RefreshSession() { if (!IsConnectedAndLoggedOn) { return false; } SteamUser.WebAPIUserNonceCallback callback; try { callback = await SteamUser.RequestWebAPIUserNonce(); } catch (Exception e) { ArchiLogger.LogGenericWarningException(e); await Connect(true).ConfigureAwait(false); return false; } if (string.IsNullOrEmpty(callback?.Nonce)) { await Connect(true).ConfigureAwait(false); return false; } if (await ArchiWebHandler.Init(SteamID, SteamClient.Universe, callback.Nonce, SteamParentalActive ? BotConfig.SteamParentalCode : null).ConfigureAwait(false)) { return true; } await Connect(true).ConfigureAwait(false); return false; } internal static async Task RegisterBot(string botName) { if (string.IsNullOrEmpty(botName)) { ASF.ArchiLogger.LogNullError(nameof(botName)); return; } if (Bots.ContainsKey(botName)) { return; } string configFilePath = GetFilePath(botName, EFileType.Config); if (string.IsNullOrEmpty(configFilePath)) { ASF.ArchiLogger.LogNullError(nameof(configFilePath)); return; } BotConfig botConfig = await BotConfig.Load(configFilePath).ConfigureAwait(false); if (botConfig == null) { ASF.ArchiLogger.LogGenericError(string.Format(Strings.ErrorBotConfigInvalid, configFilePath)); return; } if (Debugging.IsDebugConfigured) { ASF.ArchiLogger.LogGenericDebug(configFilePath + ": " + JsonConvert.SerializeObject(botConfig, Formatting.Indented)); } string databaseFilePath = GetFilePath(botName, EFileType.Database); if (string.IsNullOrEmpty(databaseFilePath)) { ASF.ArchiLogger.LogNullError(nameof(databaseFilePath)); return; } BotDatabase botDatabase = await BotDatabase.CreateOrLoad(databaseFilePath).ConfigureAwait(false); if (botDatabase == null) { ASF.ArchiLogger.LogGenericError(string.Format(Strings.ErrorDatabaseInvalid, databaseFilePath)); return; } if (Debugging.IsDebugConfigured) { ASF.ArchiLogger.LogGenericDebug(databaseFilePath + ": " + JsonConvert.SerializeObject(botDatabase, Formatting.Indented)); } Bot bot; await BotsSemaphore.WaitAsync().ConfigureAwait(false); try { if (Bots.ContainsKey(botName)) { return; } bot = new Bot(botName, botConfig, botDatabase); if (!Bots.TryAdd(botName, bot)) { ASF.ArchiLogger.LogNullError(nameof(bot)); bot.Dispose(); return; } } finally { BotsSemaphore.Release(); } await PluginsCore.OnBotInit(bot).ConfigureAwait(false); HashSet<ClientMsgHandler> customHandlers = await PluginsCore.OnBotSteamHandlersInit(bot).ConfigureAwait(false); if ((customHandlers != null) && (customHandlers.Count > 0)) { foreach (ClientMsgHandler customHandler in customHandlers) { bot.SteamClient.AddHandler(customHandler); } } await PluginsCore.OnBotSteamCallbacksInit(bot, bot.CallbackManager).ConfigureAwait(false); await bot.InitModules().ConfigureAwait(false); bot.InitStart(); } internal async Task<bool> Rename(string newBotName) { if (string.IsNullOrEmpty(newBotName)) { ArchiLogger.LogNullError(nameof(newBotName)); return false; } if (newBotName.Equals(SharedInfo.ASF) || Bots.ContainsKey(newBotName)) { return false; } if (KeepRunning) { Stop(true); } await BotDatabase.MakeReadOnly().ConfigureAwait(false); // We handle the config file last as it'll trigger new bot creation foreach ((string filePath, EFileType fileType) in RelatedFiles.Where(file => File.Exists(file.FilePath)).OrderByDescending(file => file.FileType != EFileType.Config)) { string newFilePath = GetFilePath(newBotName, fileType); if (string.IsNullOrEmpty(newFilePath)) { ArchiLogger.LogNullError(nameof(newFilePath)); return false; } try { File.Move(filePath, newFilePath); } catch (Exception e) { ArchiLogger.LogGenericException(e); return false; } } return true; } internal void RequestPersonaStateUpdate() { if (!IsConnectedAndLoggedOn) { return; } SteamFriends.RequestFriendInfo(SteamID, EClientPersonaStateFlag.PlayerName | EClientPersonaStateFlag.Presence); } internal async Task<bool> SendMessage(ulong steamID, string message) { if ((steamID == 0) || !new SteamID(steamID).IsIndividualAccount || string.IsNullOrEmpty(message)) { ArchiLogger.LogNullError(nameof(steamID) + " || " + nameof(message)); return false; } if (!IsConnectedAndLoggedOn) { return false; } ArchiLogger.LogChatMessage(true, message, steamID: steamID); ushort maxMessageLength = (ushort) (MaxMessageLength - ReservedMessageLength - (ASF.GlobalConfig.SteamMessagePrefix?.Length ?? 0)); // We must escape our message prior to sending it message = Escape(message); int i = 0; while (i < message.Length) { int partLength; bool copyNewline = false; // ReSharper disable ArrangeMissingParentheses - conflict with Roslyn if (message.Length - i > maxMessageLength) { int lastNewLine = message.LastIndexOf(Environment.NewLine, i + maxMessageLength - Environment.NewLine.Length, maxMessageLength - Environment.NewLine.Length, StringComparison.Ordinal); if (lastNewLine > i) { partLength = lastNewLine - i + Environment.NewLine.Length; copyNewline = true; } else { partLength = maxMessageLength; } } else { partLength = message.Length - i; } // If our message is of max length and ends with a single '\' then we can't split it here, it escapes the next character if ((partLength >= maxMessageLength) && (message[i + partLength - 1] == '\\') && (message[i + partLength - 2] != '\\')) { // Instead, we'll cut this message one char short and include the rest in next iteration partLength--; } // ReSharper restore ArrangeMissingParentheses string messagePart = message.Substring(i, partLength); messagePart = ASF.GlobalConfig.SteamMessagePrefix + (i > 0 ? "…" : "") + messagePart + (maxMessageLength < message.Length - i ? "…" : ""); await MessagingSemaphore.WaitAsync().ConfigureAwait(false); try { bool sent = false; for (byte j = 0; (j < WebBrowser.MaxTries) && !sent && IsConnectedAndLoggedOn; j++) { // TODO: Determine if this dirty workaround fixes "ghost notification" bug // Theory: Perhaps Steam is confused when dealing with more than 1 message per second from the same user, check if this helps await Task.Delay(1000).ConfigureAwait(false); EResult result = await ArchiHandler.SendMessage(steamID, messagePart).ConfigureAwait(false); switch (result) { case EResult.Fail: case EResult.RateLimitExceeded: case EResult.Timeout: await Task.Delay(5000).ConfigureAwait(false); continue; case EResult.OK: sent = true; break; default: ArchiLogger.LogGenericError(string.Format(Strings.WarningUnknownValuePleaseReport, nameof(result), result)); return false; } } if (!sent) { ArchiLogger.LogGenericWarning(Strings.WarningFailed); return false; } } finally { MessagingSemaphore.Release(); } i += partLength - (copyNewline ? Environment.NewLine.Length : 0); } return true; } internal async Task<bool> SendMessage(ulong chatGroupID, ulong chatID, string message) { if ((chatGroupID == 0) || (chatID == 0) || string.IsNullOrEmpty(message)) { ArchiLogger.LogNullError(nameof(chatGroupID) + " || " + nameof(chatID) + " || " + nameof(message)); return false; } if (!IsConnectedAndLoggedOn) { return false; } ArchiLogger.LogChatMessage(true, message, chatGroupID, chatID); ushort maxMessageLength = (ushort) (MaxMessageLength - ReservedMessageLength - (ASF.GlobalConfig.SteamMessagePrefix?.Length ?? 0)); // We must escape our message prior to sending it message = Escape(message); int i = 0; // ReSharper disable ArrangeMissingParentheses - conflict with Roslyn while (i < message.Length) { int partLength; bool copyNewline = false; if (message.Length - i > maxMessageLength) { int lastNewLine = message.LastIndexOf(Environment.NewLine, i + maxMessageLength - Environment.NewLine.Length, maxMessageLength - Environment.NewLine.Length, StringComparison.Ordinal); if (lastNewLine > i) { partLength = lastNewLine - i + Environment.NewLine.Length; copyNewline = true; } else { partLength = maxMessageLength; } } else { partLength = message.Length - i; } // If our message is of max length and ends with a single '\' then we can't split it here, it escapes the next character if ((partLength >= maxMessageLength) && (message[i + partLength - 1] == '\\') && (message[i + partLength - 2] != '\\')) { // Instead, we'll cut this message one char short and include the rest in next iteration partLength--; } // ReSharper restore ArrangeMissingParentheses string messagePart = message.Substring(i, partLength); messagePart = ASF.GlobalConfig.SteamMessagePrefix + (i > 0 ? "…" : "") + messagePart + (maxMessageLength < message.Length - i ? "…" : ""); await MessagingSemaphore.WaitAsync().ConfigureAwait(false); try { bool sent = false; for (byte j = 0; (j < WebBrowser.MaxTries) && !sent && IsConnectedAndLoggedOn; j++) { EResult result = await ArchiHandler.SendMessage(chatGroupID, chatID, messagePart).ConfigureAwait(false); switch (result) { case EResult.Fail: case EResult.RateLimitExceeded: case EResult.Timeout: await Task.Delay(5000).ConfigureAwait(false); continue; case EResult.OK: sent = true; break; default: ArchiLogger.LogGenericError(string.Format(Strings.WarningUnknownValuePleaseReport, nameof(result), result)); return false; } } if (!sent) { ArchiLogger.LogGenericWarning(Strings.WarningFailed); return false; } } finally { MessagingSemaphore.Release(); } i += partLength - (copyNewline ? Environment.NewLine.Length : 0); } return true; } internal async Task<bool> SendTypingMessage(ulong steamID) { if ((steamID == 0) || !new SteamID(steamID).IsIndividualAccount) { ArchiLogger.LogNullError(nameof(steamID)); return false; } if (!IsConnectedAndLoggedOn) { return false; } return await ArchiHandler.SendTypingStatus(steamID).ConfigureAwait(false) == EResult.OK; } internal async Task Start() { if (KeepRunning) { return; } KeepRunning = true; Utilities.InBackground(HandleCallbacks, true); ArchiLogger.LogGenericInfo(Strings.Starting); // Support and convert 2FA files if (!HasMobileAuthenticator) { string mobileAuthenticatorFilePath = GetFilePath(EFileType.MobileAuthenticator); if (string.IsNullOrEmpty(mobileAuthenticatorFilePath)) { ArchiLogger.LogNullError(nameof(mobileAuthenticatorFilePath)); return; } if (File.Exists(mobileAuthenticatorFilePath)) { await ImportAuthenticator(mobileAuthenticatorFilePath).ConfigureAwait(false); } } string keysToRedeemFilePath = GetFilePath(EFileType.KeysToRedeem); if (string.IsNullOrEmpty(keysToRedeemFilePath)) { ArchiLogger.LogNullError(nameof(keysToRedeemFilePath)); return; } if (File.Exists(keysToRedeemFilePath)) { await ImportKeysToRedeem(keysToRedeemFilePath).ConfigureAwait(false); } await Connect().ConfigureAwait(false); } internal void Stop(bool skipShutdownEvent = false) { if (!KeepRunning) { return; } KeepRunning = false; ArchiLogger.LogGenericInfo(Strings.BotStopping); if (SteamClient.IsConnected) { Disconnect(); } if (!skipShutdownEvent) { Utilities.InBackground(Events.OnBotShutdown); } } internal static IOrderedDictionary ValidateGamesToRedeemInBackground(IOrderedDictionary gamesToRedeemInBackground) { if ((gamesToRedeemInBackground == null) || (gamesToRedeemInBackground.Count == 0)) { ASF.ArchiLogger.LogNullError(nameof(gamesToRedeemInBackground)); return null; } HashSet<object> invalidKeys = new HashSet<object>(); foreach (DictionaryEntry game in gamesToRedeemInBackground) { bool invalid = false; string key = game.Key as string; if (string.IsNullOrEmpty(key)) { invalid = true; ASF.ArchiLogger.LogGenericWarning(string.Format(Strings.ErrorIsInvalid, nameof(key))); } else if (!Utilities.IsValidCdKey(key)) { invalid = true; ASF.ArchiLogger.LogGenericWarning(string.Format(Strings.ErrorIsInvalid, key)); } string name = game.Value as string; if (string.IsNullOrEmpty(name)) { invalid = true; ASF.ArchiLogger.LogGenericWarning(string.Format(Strings.ErrorIsInvalid, nameof(name))); } if (invalid) { invalidKeys.Add(game.Key); } } if (invalidKeys.Count > 0) { foreach (string invalidKey in invalidKeys) { gamesToRedeemInBackground.Remove(invalidKey); } } return gamesToRedeemInBackground; } private async Task CheckOccupationStatus() { StopPlayingWasBlockedTimer(); if (!IsPlayingPossible) { PlayingWasBlocked = true; ArchiLogger.LogGenericInfo(Strings.BotAccountOccupied); return; } if (PlayingWasBlocked && (PlayingWasBlockedTimer == null)) { InitPlayingWasBlockedTimer(); } ArchiLogger.LogGenericInfo(Strings.BotAccountFree); if (!await CardsFarmer.Resume(false).ConfigureAwait(false)) { await ResetGamesPlayed().ConfigureAwait(false); } } private async Task Connect(bool force = false) { if (!force && (!KeepRunning || SteamClient.IsConnected)) { return; } await LimitLoginRequestsAsync().ConfigureAwait(false); if (!force && (!KeepRunning || SteamClient.IsConnected)) { return; } ArchiLogger.LogGenericInfo(Strings.BotConnecting); InitConnectionFailureTimer(); SteamClient.Connect(); } private async Task Destroy(bool force = false) { if (KeepRunning) { if (!force) { Stop(); } else { // Stop() will most likely block due to connection freeze, don't wait for it Utilities.InBackground(() => Stop()); } } Bots.TryRemove(BotName, out _); await PluginsCore.OnBotDestroy(this).ConfigureAwait(false); } private void Disconnect() { StopConnectionFailureTimer(); SteamClient.Disconnect(); } private static string Escape(string message) { if (string.IsNullOrEmpty(message)) { ASF.ArchiLogger.LogNullError(nameof(message)); return null; } return message.Replace("\\", "\\\\").Replace("[", "\\["); } private string GetFilePath(EFileType fileType) { if (!Enum.IsDefined(typeof(EFileType), fileType)) { ASF.ArchiLogger.LogNullError(nameof(fileType)); return null; } return GetFilePath(BotName, fileType); } [ItemCanBeNull] private async Task<Dictionary<string, string>> GetKeysFromFile(string filePath) { if (string.IsNullOrEmpty(filePath)) { ArchiLogger.LogNullError(nameof(filePath)); return null; } if (!File.Exists(filePath)) { return new Dictionary<string, string>(0, StringComparer.Ordinal); } Dictionary<string, string> keys = new Dictionary<string, string>(StringComparer.Ordinal); try { using StreamReader reader = new StreamReader(filePath); string line; while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null) { if (line.Length == 0) { continue; } string[] parsedArgs = line.Split(DefaultBackgroundKeysRedeemerSeparator, StringSplitOptions.RemoveEmptyEntries); if (parsedArgs.Length < 3) { ArchiLogger.LogGenericWarning(string.Format(Strings.ErrorIsInvalid, line)); continue; } string key = parsedArgs[parsedArgs.Length - 1]; if (!Utilities.IsValidCdKey(key)) { ArchiLogger.LogGenericWarning(string.Format(Strings.ErrorIsInvalid, key)); continue; } string name = parsedArgs[0]; keys[key] = name; } } catch (Exception e) { ArchiLogger.LogGenericException(e); return null; } return keys; } private void HandleCallbacks() { TimeSpan timeSpan = TimeSpan.FromMilliseconds(CallbackSleep); while (KeepRunning || SteamClient.IsConnected) { if (!CallbackSemaphore.Wait(0)) { if (Debugging.IsUserDebugging) { ArchiLogger.LogGenericDebug(string.Format(Strings.WarningFailedWithError, nameof(CallbackSemaphore))); } return; } try { CallbackManager.RunWaitAllCallbacks(timeSpan); } catch (Exception e) { ArchiLogger.LogGenericException(e); } finally { CallbackSemaphore.Release(); } } } private async Task HeartBeat() { if (!KeepRunning || !IsConnectedAndLoggedOn || (HeartBeatFailures == byte.MaxValue)) { return; } try { if (DateTime.UtcNow.Subtract(ArchiHandler.LastPacketReceived).TotalSeconds > ASF.GlobalConfig.ConnectionTimeout) { await SteamFriends.RequestProfileInfo(SteamID); } HeartBeatFailures = 0; if (Statistics != null) { Utilities.InBackground(Statistics.OnHeartBeat); } } catch (Exception e) { ArchiLogger.LogGenericDebuggingException(e); if (!KeepRunning || !IsConnectedAndLoggedOn || (HeartBeatFailures == byte.MaxValue)) { return; } if (++HeartBeatFailures >= (byte) Math.Ceiling(ASF.GlobalConfig.ConnectionTimeout / 10.0)) { HeartBeatFailures = byte.MaxValue; ArchiLogger.LogGenericWarning(Strings.BotConnectionLost); Utilities.InBackground(() => Connect(true)); } } } private async Task ImportAuthenticator(string maFilePath) { if (HasMobileAuthenticator || !File.Exists(maFilePath)) { return; } ArchiLogger.LogGenericInfo(Strings.BotAuthenticatorConverting); try { string json = await RuntimeCompatibility.File.ReadAllTextAsync(maFilePath).ConfigureAwait(false); if (string.IsNullOrEmpty(json)) { ArchiLogger.LogGenericError(string.Format(Strings.ErrorIsEmpty, nameof(json))); return; } MobileAuthenticator authenticator = JsonConvert.DeserializeObject<MobileAuthenticator>(json); if (authenticator == null) { ArchiLogger.LogNullError(nameof(authenticator)); return; } if (!authenticator.HasValidDeviceID) { ArchiLogger.LogGenericWarning(Strings.BotAuthenticatorInvalidDeviceID); if (string.IsNullOrEmpty(DeviceID)) { string deviceID = await Logging.GetUserInput(ASF.EUserInputType.DeviceID, BotName).ConfigureAwait(false); if (string.IsNullOrEmpty(deviceID)) { return; } SetUserInput(ASF.EUserInputType.DeviceID, deviceID); } if (!MobileAuthenticator.IsValidDeviceID(DeviceID)) { ArchiLogger.LogGenericWarning(Strings.BotAuthenticatorInvalidDeviceID); return; } authenticator.CorrectDeviceID(DeviceID); } authenticator.Init(this); BotDatabase.MobileAuthenticator = authenticator; File.Delete(maFilePath); } catch (Exception e) { ArchiLogger.LogGenericException(e); return; } ArchiLogger.LogGenericInfo(Strings.BotAuthenticatorImportFinished); } private void InitConnectionFailureTimer() { if (ConnectionFailureTimer != null) { return; } ConnectionFailureTimer = new Timer( async e => await InitPermanentConnectionFailure().ConfigureAwait(false), null, TimeSpan.FromMinutes(Math.Ceiling(ASF.GlobalConfig.ConnectionTimeout / 30.0)), // Delay Timeout.InfiniteTimeSpan // Period ); } private async Task InitializeFamilySharing() { HashSet<ulong> steamIDs = await ArchiWebHandler.GetFamilySharingSteamIDs().ConfigureAwait(false); if (steamIDs == null) { return; } SteamFamilySharingIDs.ReplaceWith(steamIDs); } private async Task<bool> InitLoginAndPassword(bool requiresPassword) { if (string.IsNullOrEmpty(BotConfig.SteamLogin)) { string steamLogin = await Logging.GetUserInput(ASF.EUserInputType.Login, BotName).ConfigureAwait(false); if (string.IsNullOrEmpty(steamLogin)) { return false; } SetUserInput(ASF.EUserInputType.Login, steamLogin); } if (requiresPassword && string.IsNullOrEmpty(BotConfig.DecryptedSteamPassword)) { string steamPassword = await Logging.GetUserInput(ASF.EUserInputType.Password, BotName).ConfigureAwait(false); if (string.IsNullOrEmpty(steamPassword)) { return false; } SetUserInput(ASF.EUserInputType.Password, steamPassword); } return true; } private async Task InitModules() { AccountFlags = EAccountFlags.NormalUser; AvatarHash = Nickname = null; MasterChatGroupID = 0; WalletBalance = 0; WalletCurrency = ECurrencyCode.Invalid; CardsFarmer.SetInitialState(BotConfig.Paused); if (SendItemsTimer != null) { SendItemsTimer.Dispose(); SendItemsTimer = null; } if ((BotConfig.SendTradePeriod > 0) && (BotConfig.LootableTypes.Count > 0) && BotConfig.SteamUserPermissions.Values.Any(permission => permission >= BotConfig.EPermission.Master)) { SendItemsTimer = new Timer( async e => await Actions.SendInventory(filterFunction: item => BotConfig.LootableTypes.Contains(item.Type)).ConfigureAwait(false), null, TimeSpan.FromHours(BotConfig.SendTradePeriod) + TimeSpan.FromSeconds(ASF.LoadBalancingDelay * Bots.Count), // Delay TimeSpan.FromHours(BotConfig.SendTradePeriod) // Period ); } if (SteamSaleEvent != null) { SteamSaleEvent.Dispose(); SteamSaleEvent = null; } if (BotConfig.AutoSteamSaleEvent) { SteamSaleEvent = new SteamSaleEvent(this); } await PluginsCore.OnBotInitModules(this, BotConfig.AdditionalProperties).ConfigureAwait(false); } private async Task InitPermanentConnectionFailure() { if (!KeepRunning) { return; } ArchiLogger.LogGenericWarning(Strings.BotHeartBeatFailed); await Destroy(true).ConfigureAwait(false); await RegisterBot(BotName).ConfigureAwait(false); } private void InitPlayingWasBlockedTimer() { if (PlayingWasBlockedTimer != null) { return; } PlayingWasBlockedTimer = new Timer( e => ResetPlayingWasBlockedWithTimer(), null, TimeSpan.FromSeconds(MinPlayingBlockedTTL), // Delay Timeout.InfiniteTimeSpan // Period ); } private void InitStart() { if (!BotConfig.Enabled) { ArchiLogger.LogGenericInfo(Strings.BotInstanceNotStartingBecauseDisabled); return; } // Start Utilities.InBackground(Start); } private bool IsMasterClanID(ulong steamID) { if ((steamID == 0) || !new SteamID(steamID).IsClanAccount) { ArchiLogger.LogNullError(nameof(steamID)); return false; } return steamID == BotConfig.SteamMasterClanID; } private static bool IsRefundable(EPaymentMethod paymentMethod) { if (paymentMethod == EPaymentMethod.None) { ASF.ArchiLogger.LogNullError(nameof(paymentMethod)); return false; } // Complimentary is also a flag return paymentMethod switch { EPaymentMethod.ActivationCode => false, EPaymentMethod.Complimentary => false, EPaymentMethod.GuestPass => false, EPaymentMethod.HardwarePromo => false, _ => !paymentMethod.HasFlag(EPaymentMethod.Complimentary) }; } private async Task JoinMasterChatGroupID() { if (BotConfig.SteamMasterClanID == 0) { return; } if (MasterChatGroupID == 0) { ulong chatGroupID = await ArchiHandler.GetClanChatGroupID(BotConfig.SteamMasterClanID).ConfigureAwait(false); if (chatGroupID == 0) { return; } MasterChatGroupID = chatGroupID; } HashSet<ulong> chatGroupIDs = await ArchiHandler.GetMyChatGroupIDs().ConfigureAwait(false); if (chatGroupIDs?.Contains(MasterChatGroupID) != false) { return; } if (!await ArchiHandler.JoinChatRoomGroup(MasterChatGroupID).ConfigureAwait(false)) { ArchiLogger.LogGenericWarning(string.Format(Strings.WarningFailedWithError, nameof(ArchiHandler.JoinChatRoomGroup))); } } private static async Task LimitLoginRequestsAsync() { if (ASF.GlobalConfig.LoginLimiterDelay == 0) { await LoginRateLimitingSemaphore.WaitAsync().ConfigureAwait(false); LoginRateLimitingSemaphore.Release(); return; } await LoginSemaphore.WaitAsync().ConfigureAwait(false); try { await LoginRateLimitingSemaphore.WaitAsync().ConfigureAwait(false); LoginRateLimitingSemaphore.Release(); } finally { Utilities.InBackground( async () => { await Task.Delay(ASF.GlobalConfig.LoginLimiterDelay * 1000).ConfigureAwait(false); LoginSemaphore.Release(); } ); } } private async void OnConnected(SteamClient.ConnectedCallback callback) { if (callback == null) { ArchiLogger.LogNullError(nameof(callback)); return; } HeartBeatFailures = 0; ReconnectOnUserInitiated = false; StopConnectionFailureTimer(); ArchiLogger.LogGenericInfo(Strings.BotConnected); if (!KeepRunning) { ArchiLogger.LogGenericInfo(Strings.BotDisconnecting); Disconnect(); return; } string sentryFilePath = GetFilePath(EFileType.SentryFile); if (string.IsNullOrEmpty(sentryFilePath)) { ArchiLogger.LogNullError(nameof(sentryFilePath)); return; } byte[] sentryFileHash = null; if (File.Exists(sentryFilePath)) { try { byte[] sentryFileContent = await RuntimeCompatibility.File.ReadAllBytesAsync(sentryFilePath).ConfigureAwait(false); sentryFileHash = CryptoHelper.SHAHash(sentryFileContent); } catch (Exception e) { ArchiLogger.LogGenericException(e); try { File.Delete(sentryFilePath); } catch { // Ignored, we can only try to delete faulted file at best } } } string loginKey = null; if (BotConfig.UseLoginKeys) { // Login keys are not guaranteed to be valid, we should use them only if we don't have full details available from the user if (string.IsNullOrEmpty(BotConfig.DecryptedSteamPassword) || (string.IsNullOrEmpty(AuthCode) && string.IsNullOrEmpty(TwoFactorCode) && !HasMobileAuthenticator)) { loginKey = BotDatabase.LoginKey; // Decrypt login key if needed if (!string.IsNullOrEmpty(loginKey) && (loginKey.Length > 19) && (BotConfig.PasswordFormat != ArchiCryptoHelper.ECryptoMethod.PlainText)) { loginKey = ArchiCryptoHelper.Decrypt(BotConfig.PasswordFormat, loginKey); } } } else { // If we're not using login keys, ensure we don't have any saved BotDatabase.LoginKey = null; } if (!await InitLoginAndPassword(string.IsNullOrEmpty(loginKey)).ConfigureAwait(false)) { Stop(); return; } // Steam login and password fields can contain ASCII characters only, including spaces const string nonAsciiPattern = @"[^\u0000-\u007F]+"; string username = Regex.Replace(BotConfig.SteamLogin, nonAsciiPattern, "", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); string password = BotConfig.DecryptedSteamPassword; if (!string.IsNullOrEmpty(password)) { password = Regex.Replace(password, nonAsciiPattern, "", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); } ArchiLogger.LogGenericInfo(Strings.BotLoggingIn); if (string.IsNullOrEmpty(TwoFactorCode) && HasMobileAuthenticator) { // We should always include 2FA token, even if it's not required TwoFactorCode = await BotDatabase.MobileAuthenticator.GenerateToken().ConfigureAwait(false); } InitConnectionFailureTimer(); SteamUser.LogOnDetails logOnDetails = new SteamUser.LogOnDetails { AuthCode = AuthCode, CellID = ASF.GlobalDatabase.CellID, LoginID = LoginID, LoginKey = loginKey, Password = password, SentryFileHash = sentryFileHash, ShouldRememberPassword = BotConfig.UseLoginKeys, TwoFactorCode = TwoFactorCode, Username = username }; if (OSType == EOSType.Unknown) { OSType = logOnDetails.ClientOSType; } SteamUser.LogOn(logOnDetails); } private async void OnDisconnected(SteamClient.DisconnectedCallback callback) { if (callback == null) { ArchiLogger.LogNullError(nameof(callback)); return; } EResult lastLogOnResult = LastLogOnResult; LastLogOnResult = EResult.Invalid; HeartBeatFailures = 0; SteamParentalActive = true; StopConnectionFailureTimer(); StopPlayingWasBlockedTimer(); ArchiLogger.LogGenericInfo(Strings.BotDisconnected); OwnedPackageIDs.Clear(); PastNotifications.Clear(); Actions.OnDisconnected(); ArchiWebHandler.OnDisconnected(); CardsFarmer.OnDisconnected(); Trading.OnDisconnected(); FirstTradeSent = false; await PluginsCore.OnBotDisconnected(this, callback.UserInitiated ? EResult.OK : lastLogOnResult).ConfigureAwait(false); // If we initiated disconnect, do not attempt to reconnect if (callback.UserInitiated && !ReconnectOnUserInitiated) { return; } switch (lastLogOnResult) { case EResult.AccountDisabled: case EResult.InvalidPassword when string.IsNullOrEmpty(BotDatabase.LoginKey): // Do not attempt to reconnect, those failures are permanent return; case EResult.InvalidPassword: BotDatabase.LoginKey = null; ArchiLogger.LogGenericInfo(Strings.BotRemovedExpiredLoginKey); break; case EResult.NoConnection: case EResult.ServiceUnavailable: case EResult.Timeout: case EResult.TryAnotherCM: await Task.Delay(5000).ConfigureAwait(false); break; case EResult.RateLimitExceeded: ArchiLogger.LogGenericInfo(string.Format(Strings.BotRateLimitExceeded, TimeSpan.FromMinutes(LoginCooldownInMinutes).ToHumanReadable())); if (!await LoginRateLimitingSemaphore.WaitAsync(1000 * WebBrowser.MaxTries).ConfigureAwait(false)) { break; } try { await Task.Delay(LoginCooldownInMinutes * 60 * 1000).ConfigureAwait(false); } finally { LoginRateLimitingSemaphore.Release(); } break; } if (!KeepRunning || SteamClient.IsConnected) { return; } ArchiLogger.LogGenericInfo(Strings.BotReconnecting); await Connect().ConfigureAwait(false); } private async void OnFriendsList(SteamFriends.FriendsListCallback callback) { if (callback?.FriendList == null) { ArchiLogger.LogNullError(nameof(callback) + " || " + nameof(callback.FriendList)); return; } foreach (SteamFriends.FriendsListCallback.Friend friend in callback.FriendList.Where(friend => friend.Relationship == EFriendRelationship.RequestRecipient)) { switch (friend.SteamID.AccountType) { case EAccountType.Clan when IsMasterClanID(friend.SteamID): ArchiHandler.AcknowledgeClanInvite(friend.SteamID, true); await JoinMasterChatGroupID().ConfigureAwait(false); break; case EAccountType.Clan: bool acceptGroupRequest = await PluginsCore.OnBotFriendRequest(this, friend.SteamID).ConfigureAwait(false); if (acceptGroupRequest) { ArchiHandler.AcknowledgeClanInvite(friend.SteamID, true); await JoinMasterChatGroupID().ConfigureAwait(false); break; } if (BotConfig.BotBehaviour.HasFlag(BotConfig.EBotBehaviour.RejectInvalidGroupInvites)) { ArchiHandler.AcknowledgeClanInvite(friend.SteamID, false); } break; default: if (HasPermission(friend.SteamID, BotConfig.EPermission.FamilySharing)) { if (!await ArchiHandler.AddFriend(friend.SteamID).ConfigureAwait(false)) { ArchiLogger.LogGenericWarning(string.Format(Strings.WarningFailedWithError, nameof(ArchiHandler.AddFriend))); } break; } bool acceptFriendRequest = await PluginsCore.OnBotFriendRequest(this, friend.SteamID).ConfigureAwait(false); if (acceptFriendRequest) { if (!await ArchiHandler.AddFriend(friend.SteamID).ConfigureAwait(false)) { ArchiLogger.LogGenericWarning(string.Format(Strings.WarningFailedWithError, nameof(ArchiHandler.AddFriend))); } break; } if (BotConfig.BotBehaviour.HasFlag(BotConfig.EBotBehaviour.RejectInvalidFriendInvites)) { if (!await ArchiHandler.RemoveFriend(friend.SteamID).ConfigureAwait(false)) { ArchiLogger.LogGenericWarning(string.Format(Strings.WarningFailedWithError, nameof(ArchiHandler.RemoveFriend))); } } break; } } } private async void OnGuestPassList(SteamApps.GuestPassListCallback callback) { if (callback?.GuestPasses == null) { ArchiLogger.LogNullError(nameof(callback) + " || " + nameof(callback.GuestPasses)); return; } if ((callback.CountGuestPassesToRedeem == 0) || (callback.GuestPasses.Count == 0) || !BotConfig.AcceptGifts) { return; } HashSet<ulong> guestPassIDs = callback.GuestPasses.Select(guestPass => guestPass["gid"].AsUnsignedLong()).Where(gid => gid != 0).ToHashSet(); if (guestPassIDs.Count == 0) { return; } await Actions.AcceptGuestPasses(guestPassIDs).ConfigureAwait(false); } private async Task OnIncomingChatMessage(CChatRoom_IncomingChatMessage_Notification notification) { if (notification == null) { ArchiLogger.LogNullError(nameof(notification)); return; } // Under normal circumstances, timestamp must always be greater than 0, but Steam already proved that it's capable of going against the logic if ((notification.steamid_sender != SteamID) && (notification.timestamp > 0)) { if (ShouldAckChatMessage(notification.steamid_sender)) { Utilities.InBackground(() => ArchiHandler.AckChatMessage(notification.chat_group_id, notification.chat_id, notification.timestamp)); } } string message; // Prefer to use message without bbcode, but only if it's available if (!string.IsNullOrEmpty(notification.message_no_bbcode)) { message = notification.message_no_bbcode; } else if (!string.IsNullOrEmpty(notification.message)) { message = UnEscape(notification.message); } else { return; } ArchiLogger.LogChatMessage(false, message, notification.chat_group_id, notification.chat_id, notification.steamid_sender); // Steam network broadcasts chat events also when we don't explicitly sign into Steam community // We'll explicitly ignore those messages when using offline mode, as it was done in the first version of Steam chat when no messages were broadcasted at all before signing in // Handling messages will still work correctly in invisible mode, which is how it should work in the first place // This goes in addition to usual logic that ignores irrelevant messages from being parsed further if ((notification.chat_group_id != MasterChatGroupID) || (BotConfig.OnlineStatus == EPersonaState.Offline)) { return; } await Commands.HandleMessage(notification.chat_group_id, notification.chat_id, notification.steamid_sender, message).ConfigureAwait(false); } private async Task OnIncomingMessage(CFriendMessages_IncomingMessage_Notification notification) { if (notification == null) { ArchiLogger.LogNullError(nameof(notification)); return; } if ((EChatEntryType) notification.chat_entry_type != EChatEntryType.ChatMsg) { return; } // Under normal circumstances, timestamp must always be greater than 0, but Steam already proved that it's capable of going against the logic if (!notification.local_echo && (notification.rtime32_server_timestamp > 0)) { if (ShouldAckChatMessage(notification.steamid_friend)) { Utilities.InBackground(() => ArchiHandler.AckMessage(notification.steamid_friend, notification.rtime32_server_timestamp)); } } string message; // Prefer to use message without bbcode, but only if it's available if (!string.IsNullOrEmpty(notification.message_no_bbcode)) { message = notification.message_no_bbcode; } else if (!string.IsNullOrEmpty(notification.message)) { message = UnEscape(notification.message); } else { return; } ArchiLogger.LogChatMessage(notification.local_echo, message, steamID: notification.steamid_friend); // Steam network broadcasts chat events also when we don't explicitly sign into Steam community // We'll explicitly ignore those messages when using offline mode, as it was done in the first version of Steam chat when no messages were broadcasted at all before signing in // Handling messages will still work correctly in invisible mode, which is how it should work in the first place // This goes in addition to usual logic that ignores irrelevant messages from being parsed further if (notification.local_echo || (BotConfig.OnlineStatus == EPersonaState.Offline)) { return; } await Commands.HandleMessage(notification.steamid_friend, message).ConfigureAwait(false); } private async void OnLicenseList(SteamApps.LicenseListCallback callback) { if (callback?.LicenseList == null) { ArchiLogger.LogNullError(nameof(callback) + " || " + nameof(callback.LicenseList)); return; } bool initialLogin = OwnedPackageIDs.Count == 0; Commands.OnNewLicenseList(); OwnedPackageIDs.Clear(); Dictionary<uint, uint> packagesToRefresh = new Dictionary<uint, uint>(); foreach (SteamApps.LicenseListCallback.License license in callback.LicenseList.Where(license => license.PackageID != 0)) { OwnedPackageIDs[license.PackageID] = (license.PaymentMethod, license.TimeCreated); if (!ASF.GlobalDatabase.PackagesData.TryGetValue(license.PackageID, out (uint ChangeNumber, HashSet<uint> _) packageData) || (packageData.ChangeNumber < license.LastChangeNumber)) { packagesToRefresh[license.PackageID] = (uint) license.LastChangeNumber; } } if (packagesToRefresh.Count > 0) { ArchiLogger.LogGenericTrace(Strings.BotRefreshingPackagesData); await ASF.GlobalDatabase.RefreshPackages(this, packagesToRefresh).ConfigureAwait(false); ArchiLogger.LogGenericTrace(Strings.Done); } if (initialLogin && CardsFarmer.Paused) { // Emit initial game playing status in this case await ResetGamesPlayed().ConfigureAwait(false); } await CardsFarmer.OnNewGameAdded().ConfigureAwait(false); } private void OnLoggedOff(SteamUser.LoggedOffCallback callback) { if (callback == null) { ArchiLogger.LogNullError(nameof(callback)); return; } LastLogOnResult = callback.Result; ArchiLogger.LogGenericInfo(string.Format(Strings.BotLoggedOff, callback.Result)); switch (callback.Result) { case EResult.LoggedInElsewhere: // This result directly indicates that playing was blocked when we got (forcefully) disconnected PlayingWasBlocked = true; break; case EResult.LogonSessionReplaced: DateTime now = DateTime.UtcNow; if (now.Subtract(LastLogonSessionReplaced).TotalHours < 1) { ArchiLogger.LogGenericError(Strings.BotLogonSessionReplaced); Stop(); return; } LastLogonSessionReplaced = now; break; } ReconnectOnUserInitiated = true; SteamClient.Disconnect(); } private async void OnLoggedOn(SteamUser.LoggedOnCallback callback) { if (callback == null) { ArchiLogger.LogNullError(nameof(callback)); return; } // Always reset one-time-only access tokens when we get OnLoggedOn() response AuthCode = TwoFactorCode = null; // Keep LastLogOnResult for OnDisconnected() LastLogOnResult = callback.Result; HeartBeatFailures = 0; StopConnectionFailureTimer(); switch (callback.Result) { case EResult.AccountDisabled: case EResult.InvalidPassword when string.IsNullOrEmpty(BotDatabase.LoginKey): // Those failures are permanent, we should Stop() the bot if any of those happen ArchiLogger.LogGenericWarning(string.Format(Strings.BotUnableToLogin, callback.Result, callback.ExtendedResult)); Stop(); break; case EResult.AccountLogonDenied: string authCode = await Logging.GetUserInput(ASF.EUserInputType.SteamGuard, BotName).ConfigureAwait(false); if (string.IsNullOrEmpty(authCode)) { Stop(); break; } SetUserInput(ASF.EUserInputType.SteamGuard, authCode); break; case EResult.AccountLoginDeniedNeedTwoFactor: if (!HasMobileAuthenticator) { string twoFactorCode = await Logging.GetUserInput(ASF.EUserInputType.TwoFactorAuthentication, BotName).ConfigureAwait(false); if (string.IsNullOrEmpty(twoFactorCode)) { Stop(); break; } SetUserInput(ASF.EUserInputType.TwoFactorAuthentication, twoFactorCode); } break; case EResult.OK: AccountFlags = callback.AccountFlags; SteamID = callback.ClientSteamID; ArchiLogger.LogGenericInfo(string.Format(Strings.BotLoggedOn, SteamID + (!string.IsNullOrEmpty(callback.VanityURL) ? "/" + callback.VanityURL : ""))); // Old status for these doesn't matter, we'll update them if needed TwoFactorCodeFailures = 0; LibraryLocked = PlayingBlocked = false; if (PlayingWasBlocked && (PlayingWasBlockedTimer == null)) { InitPlayingWasBlockedTimer(); } if (IsAccountLimited) { ArchiLogger.LogGenericWarning(Strings.BotAccountLimited); } if (IsAccountLocked) { ArchiLogger.LogGenericWarning(Strings.BotAccountLocked); } if ((callback.CellID != 0) && (callback.CellID != ASF.GlobalDatabase.CellID)) { ASF.GlobalDatabase.CellID = callback.CellID; } // Handle steamID-based maFile if (!HasMobileAuthenticator) { string maFilePath = Path.Combine(SharedInfo.ConfigDirectory, SteamID + SharedInfo.MobileAuthenticatorExtension); if (File.Exists(maFilePath)) { await ImportAuthenticator(maFilePath).ConfigureAwait(false); } } if (callback.ParentalSettings != null) { (bool isSteamParentalEnabled, string steamParentalCode) = ValidateSteamParental(callback.ParentalSettings, BotConfig.SteamParentalCode); if (isSteamParentalEnabled) { SteamParentalActive = true; if (!string.IsNullOrEmpty(steamParentalCode)) { if (BotConfig.SteamParentalCode != steamParentalCode) { SetUserInput(ASF.EUserInputType.SteamParentalCode, steamParentalCode); } } else if (string.IsNullOrEmpty(BotConfig.SteamParentalCode) || (BotConfig.SteamParentalCode.Length != BotConfig.SteamParentalCodeLength)) { steamParentalCode = await Logging.GetUserInput(ASF.EUserInputType.SteamParentalCode, BotName).ConfigureAwait(false); if (string.IsNullOrEmpty(steamParentalCode) || (steamParentalCode.Length != BotConfig.SteamParentalCodeLength)) { Stop(); break; } SetUserInput(ASF.EUserInputType.SteamParentalCode, steamParentalCode); } } else { SteamParentalActive = false; } } else if (SteamParentalActive && !string.IsNullOrEmpty(BotConfig.SteamParentalCode) && (BotConfig.SteamParentalCode.Length != BotConfig.SteamParentalCodeLength)) { string steamParentalCode = await Logging.GetUserInput(ASF.EUserInputType.SteamParentalCode, BotName).ConfigureAwait(false); if (string.IsNullOrEmpty(steamParentalCode) || (steamParentalCode.Length != BotConfig.SteamParentalCodeLength)) { Stop(); break; } SetUserInput(ASF.EUserInputType.SteamParentalCode, steamParentalCode); } ArchiWebHandler.OnVanityURLChanged(callback.VanityURL); if (!await ArchiWebHandler.Init(SteamID, SteamClient.Universe, callback.WebAPIUserNonce, SteamParentalActive ? BotConfig.SteamParentalCode : null).ConfigureAwait(false)) { if (!await RefreshSession().ConfigureAwait(false)) { break; } } // Pre-fetch API key for future usage if possible Utilities.InBackground(ArchiWebHandler.HasValidApiKey); if ((GamesRedeemerInBackgroundTimer == null) && BotDatabase.HasGamesToRedeemInBackground) { Utilities.InBackground(RedeemGamesInBackground); } ArchiHandler.SetCurrentMode(2); ArchiHandler.RequestItemAnnouncements(); // Sometimes Steam won't send us our own PersonaStateCallback, so request it explicitly RequestPersonaStateUpdate(); Utilities.InBackground(InitializeFamilySharing); if (Statistics != null) { Utilities.InBackground(Statistics.OnLoggedOn); } if (BotConfig.OnlineStatus != EPersonaState.Offline) { SteamFriends.SetPersonaState(BotConfig.OnlineStatus); } if (BotConfig.SteamMasterClanID != 0) { Utilities.InBackground( async () => { if (!await ArchiWebHandler.JoinGroup(BotConfig.SteamMasterClanID).ConfigureAwait(false)) { ArchiLogger.LogGenericWarning(string.Format(Strings.WarningFailedWithError, nameof(ArchiWebHandler.JoinGroup))); } await JoinMasterChatGroupID().ConfigureAwait(false); } ); } await PluginsCore.OnBotLoggedOn(this).ConfigureAwait(false); break; case EResult.InvalidPassword: case EResult.NoConnection: case EResult.PasswordRequiredToKickSession: // Not sure about this one, it seems to be just generic "try again"? #694 case EResult.RateLimitExceeded: case EResult.ServiceUnavailable: case EResult.Timeout: case EResult.TryAnotherCM: case EResult.TwoFactorCodeMismatch: ArchiLogger.LogGenericWarning(string.Format(Strings.BotUnableToLogin, callback.Result, callback.ExtendedResult)); if ((callback.Result == EResult.TwoFactorCodeMismatch) && HasMobileAuthenticator) { if (++TwoFactorCodeFailures >= MaxTwoFactorCodeFailures) { TwoFactorCodeFailures = 0; ArchiLogger.LogGenericError(string.Format(Strings.BotInvalidAuthenticatorDuringLogin, MaxTwoFactorCodeFailures)); Stop(); } } break; default: // Unexpected result, shutdown immediately ArchiLogger.LogGenericError(string.Format(Strings.BotUnableToLogin, callback.Result, callback.ExtendedResult)); Stop(); break; } } private void OnLoginKey(SteamUser.LoginKeyCallback callback) { if (string.IsNullOrEmpty(callback?.LoginKey)) { ArchiLogger.LogNullError(nameof(callback) + " || " + nameof(callback.LoginKey)); return; } if (!BotConfig.UseLoginKeys) { return; } string loginKey = callback.LoginKey; if (BotConfig.PasswordFormat != ArchiCryptoHelper.ECryptoMethod.PlainText) { loginKey = ArchiCryptoHelper.Encrypt(BotConfig.PasswordFormat, loginKey); } BotDatabase.LoginKey = loginKey; SteamUser.AcceptNewLoginKey(callback); } private async void OnMachineAuth(SteamUser.UpdateMachineAuthCallback callback) { if (callback == null) { ArchiLogger.LogNullError(nameof(callback)); return; } string sentryFilePath = GetFilePath(EFileType.SentryFile); if (string.IsNullOrEmpty(sentryFilePath)) { ArchiLogger.LogNullError(nameof(sentryFilePath)); return; } long fileSize; byte[] sentryHash; try { using FileStream fileStream = File.Open(sentryFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite); fileStream.Seek(callback.Offset, SeekOrigin.Begin); await fileStream.WriteAsync(callback.Data, 0, callback.BytesToWrite).ConfigureAwait(false); fileSize = fileStream.Length; fileStream.Seek(0, SeekOrigin.Begin); using SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider(); sentryHash = sha.ComputeHash(fileStream); } catch (Exception e) { ArchiLogger.LogGenericException(e); try { File.Delete(sentryFilePath); } catch { // Ignored, we can only try to delete faulted file at best } return; } // Inform the steam servers that we're accepting this sentry file SteamUser.SendMachineAuthResponse( new SteamUser.MachineAuthDetails { BytesWritten = callback.BytesToWrite, FileName = callback.FileName, FileSize = (int) fileSize, JobID = callback.JobID, LastError = 0, Offset = callback.Offset, OneTimePassword = callback.OneTimePassword, Result = EResult.OK, SentryFileHash = sentryHash } ); } private void OnPersonaState(SteamFriends.PersonaStateCallback callback) { if (callback == null) { ArchiLogger.LogNullError(nameof(callback)); return; } if (callback.FriendID != SteamID) { return; } string avatarHash = null; if ((callback.AvatarHash != null) && (callback.AvatarHash.Length > 0) && callback.AvatarHash.Any(singleByte => singleByte != 0)) { avatarHash = BitConverter.ToString(callback.AvatarHash).Replace("-", "").ToLowerInvariant(); if (string.IsNullOrEmpty(avatarHash) || avatarHash.All(singleChar => singleChar == '0')) { avatarHash = null; } } AvatarHash = avatarHash; Nickname = callback.Name; if (Statistics != null) { Utilities.InBackground(() => Statistics.OnPersonaState(callback.Name, avatarHash)); } } private async void OnPlayingSessionState(ArchiHandler.PlayingSessionStateCallback callback) { if (callback == null) { ArchiLogger.LogNullError(nameof(callback)); return; } if (callback.PlayingBlocked == PlayingBlocked) { return; // No status update, we're not interested } PlayingBlocked = callback.PlayingBlocked; await CheckOccupationStatus().ConfigureAwait(false); } private async void OnServiceMethod(SteamUnifiedMessages.ServiceMethodNotification notification) { if (notification == null) { ArchiLogger.LogNullError(nameof(notification)); return; } switch (notification.MethodName) { case "ChatRoomClient.NotifyIncomingChatMessage#1": await OnIncomingChatMessage((CChatRoom_IncomingChatMessage_Notification) notification.Body).ConfigureAwait(false); break; case "FriendMessagesClient.IncomingMessage#1": await OnIncomingMessage((CFriendMessages_IncomingMessage_Notification) notification.Body).ConfigureAwait(false); break; } } private async void OnSharedLibraryLockStatus(ArchiHandler.SharedLibraryLockStatusCallback callback) { if (callback == null) { ArchiLogger.LogNullError(nameof(callback)); return; } // Ignore no status updates if (LibraryLocked) { if ((callback.LibraryLockedBySteamID != 0) && (callback.LibraryLockedBySteamID != SteamID)) { return; } LibraryLocked = false; } else { if ((callback.LibraryLockedBySteamID == 0) || (callback.LibraryLockedBySteamID == SteamID)) { return; } LibraryLocked = true; } await CheckOccupationStatus().ConfigureAwait(false); } private void OnUserNotifications(ArchiHandler.UserNotificationsCallback callback) { if (callback == null) { ArchiLogger.LogNullError(nameof(callback)); return; } if ((callback.Notifications == null) || (callback.Notifications.Count == 0)) { return; } HashSet<ArchiHandler.UserNotificationsCallback.EUserNotification> newPluginNotifications = new HashSet<ArchiHandler.UserNotificationsCallback.EUserNotification>(); foreach ((ArchiHandler.UserNotificationsCallback.EUserNotification notification, uint count) in callback.Notifications) { bool newNotification; if (count > 0) { newNotification = !PastNotifications.TryGetValue(notification, out uint previousCount) || (count > previousCount); PastNotifications[notification] = count; if (newNotification) { newPluginNotifications.Add(notification); } } else { newNotification = false; PastNotifications.TryRemove(notification, out _); } ArchiLogger.LogGenericTrace(notification + " = " + count); switch (notification) { case ArchiHandler.UserNotificationsCallback.EUserNotification.Gifts when newNotification && BotConfig.AcceptGifts: Utilities.InBackground(Actions.AcceptDigitalGiftCards); break; case ArchiHandler.UserNotificationsCallback.EUserNotification.Items when newNotification: Utilities.InBackground(CardsFarmer.OnNewItemsNotification); if (BotConfig.BotBehaviour.HasFlag(BotConfig.EBotBehaviour.DismissInventoryNotifications)) { Utilities.InBackground(ArchiWebHandler.MarkInventory); } break; case ArchiHandler.UserNotificationsCallback.EUserNotification.Trading when newNotification: Utilities.InBackground(Trading.OnNewTrade); break; } } if (newPluginNotifications.Count > 0) { Utilities.InBackground(() => PluginsCore.OnBotUserNotifications(this, newPluginNotifications)); } } private void OnVanityURLChangedCallback(ArchiHandler.VanityURLChangedCallback callback) { if (callback == null) { ArchiLogger.LogNullError(nameof(callback)); return; } ArchiWebHandler.OnVanityURLChanged(callback.VanityURL); } private void OnWalletUpdate(SteamUser.WalletInfoCallback callback) { if (callback == null) { ArchiLogger.LogNullError(nameof(callback)); return; } WalletBalance = callback.LongBalance; WalletCurrency = callback.Currency; } [SuppressMessage("ReSharper", "FunctionComplexityOverflow")] private async Task RedeemGamesInBackground() { if (!await GamesRedeemerInBackgroundSemaphore.WaitAsync(0).ConfigureAwait(false)) { return; } try { if (GamesRedeemerInBackgroundTimer != null) { GamesRedeemerInBackgroundTimer.Dispose(); GamesRedeemerInBackgroundTimer = null; } ArchiLogger.LogGenericInfo(Strings.Starting); bool assumeWalletKeyOnBadActivationCode = BotConfig.RedeemingPreferences.HasFlag(BotConfig.ERedeemingPreferences.AssumeWalletKeyOnBadActivationCode); while (IsConnectedAndLoggedOn && BotDatabase.HasGamesToRedeemInBackground) { (string key, string name) = BotDatabase.GetGameToRedeemInBackground(); if (string.IsNullOrEmpty(key) || string.IsNullOrEmpty(name)) { ArchiLogger.LogNullError(nameof(key) + " || " + nameof(name)); break; } ArchiHandler.PurchaseResponseCallback result = await Actions.RedeemKey(key).ConfigureAwait(false); if (result == null) { continue; } if (((result.PurchaseResultDetail == EPurchaseResultDetail.CannotRedeemCodeFromClient) || ((result.PurchaseResultDetail == EPurchaseResultDetail.BadActivationCode) && assumeWalletKeyOnBadActivationCode)) && (WalletCurrency != ECurrencyCode.Invalid)) { // If it's a wallet code, we try to redeem it first, then handle the inner result as our primary one (EResult Result, EPurchaseResultDetail? PurchaseResult)? walletResult = await ArchiWebHandler.RedeemWalletKey(key).ConfigureAwait(false); if (walletResult != null) { result.Result = walletResult.Value.Result; result.PurchaseResultDetail = walletResult.Value.PurchaseResult.GetValueOrDefault(walletResult.Value.Result == EResult.OK ? EPurchaseResultDetail.NoDetail : EPurchaseResultDetail.BadActivationCode); // BadActivationCode is our smart guess in this case } else { result.Result = EResult.Timeout; result.PurchaseResultDetail = EPurchaseResultDetail.Timeout; } } ArchiLogger.LogGenericDebug(string.Format(Strings.BotRedeem, key, result.Result + "/" + result.PurchaseResultDetail)); bool rateLimited = false; bool redeemed = false; switch (result.PurchaseResultDetail) { case EPurchaseResultDetail.AccountLocked: case EPurchaseResultDetail.AlreadyPurchased: case EPurchaseResultDetail.CannotRedeemCodeFromClient: case EPurchaseResultDetail.DoesNotOwnRequiredApp: case EPurchaseResultDetail.RestrictedCountry: case EPurchaseResultDetail.Timeout: break; case EPurchaseResultDetail.BadActivationCode: case EPurchaseResultDetail.DuplicateActivationCode: case EPurchaseResultDetail.NoDetail: // OK redeemed = true; break; case EPurchaseResultDetail.RateLimited: rateLimited = true; break; default: ASF.ArchiLogger.LogGenericError(string.Format(Strings.WarningUnknownValuePleaseReport, nameof(result.PurchaseResultDetail), result.PurchaseResultDetail)); break; } if (rateLimited) { break; } BotDatabase.RemoveGameToRedeemInBackground(key); // If user omitted the name or intentionally provided the same name as key, replace it with the Steam result if (name.Equals(key) && (result.Items != null) && (result.Items.Count > 0)) { name = string.Join(", ", result.Items.Values); } string logEntry = name + DefaultBackgroundKeysRedeemerSeparator + "[" + result.PurchaseResultDetail + "]" + ((result.Items != null) && (result.Items.Count > 0) ? DefaultBackgroundKeysRedeemerSeparator + string.Join(", ", result.Items) : "") + DefaultBackgroundKeysRedeemerSeparator + key; string filePath = GetFilePath(redeemed ? EFileType.KeysToRedeemUsed : EFileType.KeysToRedeemUnused); if (string.IsNullOrEmpty(filePath)) { ArchiLogger.LogNullError(nameof(filePath)); return; } try { await RuntimeCompatibility.File.AppendAllTextAsync(filePath, logEntry + Environment.NewLine).ConfigureAwait(false); } catch (Exception e) { ArchiLogger.LogGenericException(e); ArchiLogger.LogGenericError(string.Format(Strings.Content, logEntry)); break; } } if (IsConnectedAndLoggedOn && BotDatabase.HasGamesToRedeemInBackground) { ArchiLogger.LogGenericInfo(string.Format(Strings.BotRateLimitExceeded, TimeSpan.FromHours(RedeemCooldownInHours).ToHumanReadable())); GamesRedeemerInBackgroundTimer = new Timer( async e => await RedeemGamesInBackground().ConfigureAwait(false), null, TimeSpan.FromHours(RedeemCooldownInHours), // Delay Timeout.InfiniteTimeSpan // Period ); } ArchiLogger.LogGenericInfo(Strings.Done); } finally { GamesRedeemerInBackgroundSemaphore.Release(); } } private async Task ResetGamesPlayed() { if (CardsFarmer.NowFarming) { return; } if (BotConfig.GamesPlayedWhileIdle.Count > 0) { if (!IsPlayingPossible) { return; } // This function might be executed before PlayingSessionStateCallback/SharedLibraryLockStatusCallback, ensure proper delay in this case await Task.Delay(2000).ConfigureAwait(false); if (CardsFarmer.NowFarming || !IsPlayingPossible) { return; } } await ArchiHandler.PlayGames(BotConfig.GamesPlayedWhileIdle, BotConfig.CustomGamePlayedWhileIdle).ConfigureAwait(false); } private void ResetPlayingWasBlockedWithTimer() { PlayingWasBlocked = false; StopPlayingWasBlockedTimer(); } private bool ShouldAckChatMessage(ulong steamID) { if ((steamID == 0) || !new SteamID(steamID).IsIndividualAccount) { ArchiLogger.LogNullError(nameof(steamID)); return false; } if (BotConfig.BotBehaviour.HasFlag(BotConfig.EBotBehaviour.MarkReceivedMessagesAsRead)) { return true; } return BotConfig.BotBehaviour.HasFlag(BotConfig.EBotBehaviour.MarkBotMessagesAsRead) && Bots.Values.Any(bot => bot.SteamID == steamID); } private void StopConnectionFailureTimer() { if (ConnectionFailureTimer == null) { return; } ConnectionFailureTimer.Dispose(); ConnectionFailureTimer = null; } private void StopPlayingWasBlockedTimer() { if (PlayingWasBlockedTimer == null) { return; } PlayingWasBlockedTimer.Dispose(); PlayingWasBlockedTimer = null; } private static string UnEscape(string message) { if (string.IsNullOrEmpty(message)) { ASF.ArchiLogger.LogNullError(nameof(message)); return null; } return message.Replace("\\[", "[").Replace("\\\\", "\\"); } private (bool IsSteamParentalEnabled, string SteamParentalCode) ValidateSteamParental(ParentalSettings settings, string steamParentalCode = null) { if (settings == null) { ArchiLogger.LogNullError(nameof(settings)); return (false, null); } if (!settings.is_enabled) { return (false, null); } ArchiCryptoHelper.ESteamParentalAlgorithm steamParentalAlgorithm; switch (settings.passwordhashtype) { case 4: steamParentalAlgorithm = ArchiCryptoHelper.ESteamParentalAlgorithm.Pbkdf2; break; case 6: steamParentalAlgorithm = ArchiCryptoHelper.ESteamParentalAlgorithm.SCrypt; break; default: ArchiLogger.LogGenericError(string.Format(Strings.WarningUnknownValuePleaseReport, nameof(settings.passwordhashtype), settings.passwordhashtype)); return (true, null); } if ((steamParentalCode != null) && (steamParentalCode.Length == BotConfig.SteamParentalCodeLength)) { byte i = 0; byte[] password = new byte[steamParentalCode.Length]; foreach (char character in steamParentalCode.TakeWhile(character => (character >= '0') && (character <= '9'))) { password[i++] = (byte) character; } if (i >= steamParentalCode.Length) { IEnumerable<byte> passwordHash = ArchiCryptoHelper.GenerateSteamParentalHash(password, settings.salt, (byte) settings.passwordhash.Length, steamParentalAlgorithm); if (passwordHash?.SequenceEqual(settings.passwordhash) == true) { return (true, steamParentalCode); } } } ArchiLogger.LogGenericInfo(Strings.BotGeneratingSteamParentalCode); steamParentalCode = ArchiCryptoHelper.RecoverSteamParentalCode(settings.passwordhash, settings.salt, steamParentalAlgorithm); ArchiLogger.LogGenericInfo(Strings.Done); return (true, steamParentalCode); } internal enum EFileType : byte { Config, Database, KeysToRedeem, KeysToRedeemUnused, KeysToRedeemUsed, MobileAuthenticator, SentryFile } } }
31.525624
293
0.71581
[ "Apache-2.0" ]
xianzhe001/ArchiSteamFarm
ArchiSteamFarm/Bot.cs
95,975
C#
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v1/enums/conversion_attribution_event_type.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Ads.GoogleAds.V1.Enums { /// <summary>Holder for reflection information generated from google/ads/googleads/v1/enums/conversion_attribution_event_type.proto</summary> public static partial class ConversionAttributionEventTypeReflection { #region Descriptor /// <summary>File descriptor for google/ads/googleads/v1/enums/conversion_attribution_event_type.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static ConversionAttributionEventTypeReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CkVnb29nbGUvYWRzL2dvb2dsZWFkcy92MS9lbnVtcy9jb252ZXJzaW9uX2F0", "dHJpYnV0aW9uX2V2ZW50X3R5cGUucHJvdG8SHWdvb2dsZS5hZHMuZ29vZ2xl", "YWRzLnYxLmVudW1zGhxnb29nbGUvYXBpL2Fubm90YXRpb25zLnByb3RvIoUB", "CiJDb252ZXJzaW9uQXR0cmlidXRpb25FdmVudFR5cGVFbnVtIl8KHkNvbnZl", "cnNpb25BdHRyaWJ1dGlvbkV2ZW50VHlwZRIPCgtVTlNQRUNJRklFRBAAEgsK", "B1VOS05PV04QARIOCgpJTVBSRVNTSU9OEAISDwoLSU5URVJBQ1RJT04QA0L4", "AQohY29tLmdvb2dsZS5hZHMuZ29vZ2xlYWRzLnYxLmVudW1zQiNDb252ZXJz", "aW9uQXR0cmlidXRpb25FdmVudFR5cGVQcm90b1ABWkJnb29nbGUuZ29sYW5n", "Lm9yZy9nZW5wcm90by9nb29nbGVhcGlzL2Fkcy9nb29nbGVhZHMvdjEvZW51", "bXM7ZW51bXOiAgNHQUGqAh1Hb29nbGUuQWRzLkdvb2dsZUFkcy5WMS5FbnVt", "c8oCHUdvb2dsZVxBZHNcR29vZ2xlQWRzXFYxXEVudW1z6gIhR29vZ2xlOjpB", "ZHM6Okdvb2dsZUFkczo6VjE6OkVudW1zYgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V1.Enums.ConversionAttributionEventTypeEnum), global::Google.Ads.GoogleAds.V1.Enums.ConversionAttributionEventTypeEnum.Parser, null, null, new[]{ typeof(global::Google.Ads.GoogleAds.V1.Enums.ConversionAttributionEventTypeEnum.Types.ConversionAttributionEventType) }, null) })); } #endregion } #region Messages /// <summary> /// Container for enum indicating the event type the conversion is attributed to. /// </summary> public sealed partial class ConversionAttributionEventTypeEnum : pb::IMessage<ConversionAttributionEventTypeEnum> { private static readonly pb::MessageParser<ConversionAttributionEventTypeEnum> _parser = new pb::MessageParser<ConversionAttributionEventTypeEnum>(() => new ConversionAttributionEventTypeEnum()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ConversionAttributionEventTypeEnum> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Ads.GoogleAds.V1.Enums.ConversionAttributionEventTypeReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ConversionAttributionEventTypeEnum() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ConversionAttributionEventTypeEnum(ConversionAttributionEventTypeEnum other) : this() { _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ConversionAttributionEventTypeEnum Clone() { return new ConversionAttributionEventTypeEnum(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ConversionAttributionEventTypeEnum); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ConversionAttributionEventTypeEnum other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (_unknownFields != null) { _unknownFields.WriteTo(output); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ConversionAttributionEventTypeEnum other) { if (other == null) { return; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; } } } #region Nested types /// <summary>Container for nested types declared in the ConversionAttributionEventTypeEnum message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { /// <summary> /// The event type of conversions that are attributed to. /// </summary> public enum ConversionAttributionEventType { /// <summary> /// Not specified. /// </summary> [pbr::OriginalName("UNSPECIFIED")] Unspecified = 0, /// <summary> /// Represents value unknown in this version. /// </summary> [pbr::OriginalName("UNKNOWN")] Unknown = 1, /// <summary> /// The conversion is attributed to an impression. /// </summary> [pbr::OriginalName("IMPRESSION")] Impression = 2, /// <summary> /// The conversion is attributed to an interaction. /// </summary> [pbr::OriginalName("INTERACTION")] Interaction = 3, } } #endregion } #endregion } #endregion Designer generated code
39.882353
350
0.71601
[ "Apache-2.0" ]
chrisdunelm/google-ads-dotnet
src/V1/Stubs/ConversionAttributionEventType.cs
7,458
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. namespace Test.Psi { using System; using System.Collections.Generic; using System.Linq; using System.Reactive; using System.Reactive.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Psi; using Microsoft.Psi.Components; using Microsoft.Psi.Diagnostics; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class PipelineTest { [TestMethod] [Timeout(60000)] public void Pass_Data_From_One_Pipeline_To_Another() { using (var p1 = Pipeline.Create("a")) using (var p2 = Pipeline.Create("b")) { var ready = new AutoResetEvent(false); var src = Generators.Sequence(p1, new[] { 1, 2, 3 }, TimeSpan.FromTicks(1)); var dest = new Processor<int, int>(p2, (i, e, o) => o.Post(i, e.OriginatingTime)); dest.Do(i => ready.Set()); var connector = new Connector<int>(p1, p2); src.PipeTo(connector); connector.PipeTo(dest); p2.RunAsync(); p1.Run(); Assert.IsTrue(ready.WaitOne(100)); } } [TestMethod] [Timeout(60000)] public void Perf_Of_Allocation() { var bytes = new byte[100]; using (var p1 = Pipeline.Create("a")) { var count = 100; var ready = new AutoResetEvent(false); var src = Timers.Timer(p1, TimeSpan.FromMilliseconds(5)); src .Select(t => new byte[100], DeliveryPolicy.Unlimited) .Select(b => b[50], DeliveryPolicy.Unlimited) .Do(_ => { if (count > 0) { count--; } else { ready.Set(); } }); p1.RunAsync(); ready.WaitOne(-1); Assert.AreEqual(0, count); } } [TestMethod] [Timeout(60000)] public void Subpipelines() { using (var p = Pipeline.Create("root")) { using (var s = Subpipeline.Create(p, "sub")) { // add to sub-pipeline var seq = Generators.Sequence(s, new[] { 1, 2, 3 }, TimeSpan.FromTicks(1)).ToObservable().ToListObservable(); p.Run(); // run parent pipeline Assert.IsTrue(Enumerable.SequenceEqual(new int[] { 1, 2, 3 }, seq.AsEnumerable())); } } } public class TestReactiveCompositeComponent : Subpipeline { public TestReactiveCompositeComponent(Pipeline parent) : base(parent, "TestReactiveCompositeComponent") { var input = this.CreateInputConnectorFrom<int>(parent, "Input"); var output = this.CreateOutputConnectorTo<int>(parent, "Output"); this.In = input.In; this.Out = output.Out; input.Select(i => i * 2).PipeTo(output); } public Receiver<int> In { get; private set; } public Emitter<int> Out { get; private set; } } [TestMethod] [Timeout(60000)] public void SubpipelineAsReactiveComponent() { using (var p = Pipeline.Create("root")) { var doubler = new TestReactiveCompositeComponent(p); Assert.AreEqual(p, doubler.Out.Pipeline); // composite component shouldn't expose the fact that subpipeline is involved var seq = Generators.Sequence(p, new[] { 1, 2, 3 }, TimeSpan.FromTicks(1)); seq.PipeTo(doubler.In); var results = doubler.Out.ToObservable().ToListObservable(); p.Run(); // note that parent pipeline stops once sources complete (reactive composite-component subpipeline doesn't "hold open") Assert.IsTrue(Enumerable.SequenceEqual(new int[] { 2, 4, 6 }, results.AsEnumerable())); } } public class TestFiniteSourceCompositeComponent : Subpipeline { public TestFiniteSourceCompositeComponent(Pipeline parent) : base(parent, "TestFiniteSourceCompositeComponent") { var output = this.CreateOutputConnectorTo<int>(parent, "Output"); this.Out = output.Out; Generators.Range(this, 0, 10, TimeSpan.FromTicks(1)).Out.PipeTo(output); } public Emitter<int> Out { get; private set; } } [TestMethod] [Timeout(60000)] public void SubpipelineAsFiniteSourceComponent() { using (var p = Pipeline.Create("root")) { var finite = new TestFiniteSourceCompositeComponent(p); Assert.AreEqual(p, finite.Out.Pipeline); // composite component shouldn't expose the fact that subpipeline is involved var results = finite.Out.ToObservable().ToListObservable(); p.Run(); // note that parent pipeline stops once finite source composite-component subpipeline completes Assert.IsTrue(Enumerable.SequenceEqual(new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, results.AsEnumerable())); } } public class TestInfiniteSourceCompositeComponent : Subpipeline { public TestInfiniteSourceCompositeComponent(Pipeline parent) : base(parent, "TestInfiniteSourceCompositeComponent") { var output = this.CreateOutputConnectorTo<int>(parent, "Output"); this.Out = output.Out; var timer = Timers.Timer(this, TimeSpan.FromMilliseconds(10)); timer.Aggregate(0, (i, _) => i + 1).PipeTo(output); } public Emitter<int> Out { get; private set; } } [TestMethod] [Timeout(60000)] public void SubpipelineAsInfiniteSourceComponent() { ListObservable<int> results; var completed = false; using (var p = Pipeline.Create("root")) { var infinite = new TestInfiniteSourceCompositeComponent(p); Assert.AreEqual(p, infinite.Out.Pipeline); // composite component shouldn't expose the fact that subpipeline is involved results = infinite.Out.ToObservable().ToListObservable(); p.PipelineCompleted += (_, __) => completed = true; p.RunAsync(); Thread.Sleep(200); Assert.IsFalse(completed); // note that infinite source composite-component subpipeline never completes (parent pipeline must be disposed explicitly) } Assert.IsTrue(completed); // note that infinite source composite-component subpipeline never completes (parent pipeline must be disposed explicitly) Assert.IsTrue(Enumerable.SequenceEqual(new int[] { 1, 2, 3 }, results.AsEnumerable().Take(3))); // compare first few only } [TestMethod] [Timeout(60000)] public void SubpipelineWithinSubpipeline() { using (var p = Pipeline.Create()) { var subpipeline0 = Subpipeline.Create(p, "subpipeline0"); var connectorIn0 = subpipeline0.CreateInputConnectorFrom<int>(p, "connectorIn0"); var connectorOut0 = subpipeline0.CreateOutputConnectorTo<int>(p, "connectorOut0"); var subpipeline1 = Subpipeline.Create(p, "subpipeline1"); var connectorIn1 = subpipeline1.CreateInputConnectorFrom<int>(subpipeline0, "connectorIn1"); var connectorOut1 = subpipeline1.CreateOutputConnectorTo<int>(subpipeline0, "connectorOut1"); var results = new List<int>(); Generators.Sequence(p, new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, TimeSpan.FromTicks(1)).PipeTo(connectorIn0.In); connectorIn0.Out.PipeTo(connectorIn1.In); connectorIn1.Out.PipeTo(connectorOut1.In); connectorOut1.Out.PipeTo(connectorOut0.In); connectorOut0.Out.Do(x => results.Add(x)); p.Run(); CollectionAssert.AreEqual(new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, results); } } [TestMethod] [Timeout(60000)] public void SubpipelineWithinSubpipelineWithFiniteSource() { using (var p = Pipeline.Create()) { var subpipeline0 = Subpipeline.Create(p, "subpipeline0"); var connectorIn0 = subpipeline0.CreateInputConnectorFrom<int>(p, "connectorIn0"); var connectorOut0 = subpipeline0.CreateOutputConnectorTo<int>(p, "connectorOut0"); var subpipeline1 = Subpipeline.Create(p, "subpipeline1"); var connectorIn1 = subpipeline1.CreateInputConnectorFrom<int>(subpipeline0, "connectorIn1"); var connectorOut1 = subpipeline1.CreateOutputConnectorTo<int>(subpipeline0, "connectorOut1"); // add a dummy finite source component to each subpipeline Generators.Return(subpipeline0, 0); Generators.Return(subpipeline1, 1); var results = new List<int>(); Generators.Sequence(p, new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, TimeSpan.FromTicks(1)).PipeTo(connectorIn0.In); connectorIn0.Out.PipeTo(connectorIn1.In); connectorIn1.Out.PipeTo(connectorOut1.In); connectorOut1.Out.PipeTo(connectorOut0.In); connectorOut0.Out.Do(x => results.Add(x)); p.Run(); CollectionAssert.AreEqual(new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, results); } } [TestMethod] [Timeout(60000)] public void SubpipelineWithinSubpipelineWithInfiniteSource() { using (var p = Pipeline.Create()) { var subpipeline0 = Subpipeline.Create(p, "subpipeline0"); var connectorIn0 = subpipeline0.CreateInputConnectorFrom<int>(p, "connectorIn0"); var connectorOut0 = subpipeline0.CreateOutputConnectorTo<int>(p, "connectorOut0"); var subpipeline1 = Subpipeline.Create(p, "subpipeline1"); var connectorIn1 = subpipeline1.CreateInputConnectorFrom<int>(subpipeline0, "connectorIn1"); var connectorOut1 = subpipeline1.CreateOutputConnectorTo<int>(subpipeline0, "connectorOut1"); // add a dummy infinite source component to each subpipeline var infinite0 = new InfiniteTestComponent(subpipeline0); var infinite1 = new InfiniteTestComponent(subpipeline1); var results = new List<int>(); Generators.Sequence(p, new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, TimeSpan.FromTicks(1)).PipeTo(connectorIn0.In); connectorIn0.Out.PipeTo(connectorIn1.In); connectorIn1.Out.PipeTo(connectorOut1.In); connectorOut1.Out.PipeTo(connectorOut0.In); connectorOut0.Out.Do(x => results.Add(x)); p.Run(); CollectionAssert.AreEqual(new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, results); } } [TestMethod] [Timeout(60000)] public void SubpipelineClock() { // This test verifies that a running sub-pipeline's clock is in sync with its parent. // There were cases in the past where this was not the case, leading to unwanted delays. using (var p = Pipeline.Create("parent")) { Clock clock1 = null; Clock clock2 = null; // Capture the clock from within a Do() operator to ensure that we get the clock // that is used when the pipeline is running since the clock could change as the // pipeline transitions from not_started -> running -> stopped states. Generators.Return(p, 0).Do(_ => clock1 = p.Clock); // create a sub-pipeline and capture its running clock var sub = Subpipeline.Create(p, "sub"); Generators.Return(sub, 0).Do(_ => clock2 = sub.Clock); // run the pipeline to capture the clocks p.Run(ReplayDescriptor.ReplayAllRealTime); // now check the two clocks for equivalence var now = DateTime.UtcNow; Assert.AreEqual(clock1.Origin, clock2.Origin); Assert.AreEqual(clock1.RealTimeOrigin, clock2.RealTimeOrigin); Assert.AreEqual(clock1.ToVirtualTime(now), clock2.ToVirtualTime(now)); } } [TestMethod] [Timeout(60000)] public void ComponentInitStartOrderingWhenExceedingSchedulerThreadPool() { // Starting this many generators will easily exceed the `maxThreadCount` and start filling the global queue // This used to cause an issue in which component start/initialize would be scheduled out of order and crash using (var pipeline = Pipeline.Create()) { for (int i = 0; i < 1000; i++) { var p = Generators.Sequence(pipeline, new int[] { }, TimeSpan.FromTicks(1)); } pipeline.Run(); } } private class FiniteToInfiniteTestComponent : ISourceComponent { private Action<DateTime> notifyCompletionTime; private ManualResetEvent started = new ManualResetEvent(false); public FiniteToInfiniteTestComponent(Pipeline pipeline) { // this component declares itself finite by may later switch to infinite pipeline.CreateEmitter<int>(this, "not really used"); } public void Start(Action<DateTime> notifyCompletionTime) { this.notifyCompletionTime = notifyCompletionTime; this.started.Set(); } public void Stop(DateTime finalOriginatingTime, Action notifyCompleted) { this.started.Reset(); notifyCompleted(); } public void SwitchToInfinite() { this.started.WaitOne(); this.notifyCompletionTime(DateTime.MaxValue); } } private class InfiniteTestComponent : ISourceComponent { public InfiniteTestComponent(Pipeline pipeline) { // this component declares itself infinite pipeline.CreateEmitter<int>(this, "not really used"); } public void Start(Action<DateTime> notifyCompletionTime) { notifyCompletionTime(DateTime.MaxValue); } public void Stop(DateTime finalOriginatingTime, Action notifyCompleted) { notifyCompleted(); } } [TestMethod] [Timeout(60000)] public void PipelineShutdownWithFiniteAndInfiniteSourceComponents() { // pipeline containing finite source should stop once completed using (var pipeline = Pipeline.Create()) { Generators.Return(pipeline, 123); pipeline.RunAsync(); var stopped = pipeline.WaitAll(1000); Assert.IsTrue(stopped); } // pipeline containing *no* finite sources should run until explicitly stopped using (var pipeline = Pipeline.Create()) { pipeline.RunAsync(); var stopped = pipeline.WaitAll(1000); Assert.IsFalse(stopped); } // pipeline containing finite and infinite sources, but infinite notifying last should complete using (var pipeline = Pipeline.Create()) { Generators.Return(pipeline, 123); // finite var finiteToInfinite = new FiniteToInfiniteTestComponent(pipeline); pipeline.RunAsync(); var stopped = pipeline.WaitAll(1000); Assert.IsFalse(stopped); // waiting for remaining "finite" component finiteToInfinite.SwitchToInfinite(); stopped = pipeline.WaitAll(1000); Assert.IsTrue(stopped); // now we complete } // pipeline containing finite and infinite sources should complete once all finite sources complete using (var pipeline = Pipeline.Create()) { Generators.Return(pipeline, 123); // finite var infinite = new InfiniteTestComponent(pipeline); pipeline.RunAsync(); var stopped = pipeline.WaitAll(1000); Assert.IsTrue(stopped); // should complete once finite component completes } // pipeline containing finite source that notifies as infinite, but no other finite sources have ever completed, should not complete using (var pipeline = Pipeline.Create()) { var finiteToInfinite = new FiniteToInfiniteTestComponent(pipeline); pipeline.RunAsync(); finiteToInfinite.SwitchToInfinite(); var stopped = pipeline.WaitAll(1000); Assert.IsFalse(stopped); // now should not complete because no previous finite sources have completed (or existed) } // pipeline containing subpipeline which in turn contains finite sources should stop once completed using (var pipeline = Pipeline.Create()) { var subpipeline = Subpipeline.Create(pipeline); Generators.Return(subpipeline, 123); pipeline.RunAsync(); var stopped = pipeline.WaitAll(1000); Assert.IsTrue(stopped); } // pipeline containing subpipeline which in turn contains *only* infinite sources should run until explicitly stopped using (var pipeline = Pipeline.Create()) { var subpipeline = Subpipeline.Create(pipeline); Generators.Repeat(subpipeline, 123, TimeSpan.FromMilliseconds(1)); pipeline.RunAsync(); var stopped = pipeline.WaitAll(1000); Assert.IsFalse(stopped); } // pipeline containing subpipeline which in turn contains *no* sources should run until explicitly stopped using (var pipeline = Pipeline.Create()) { var subpipeline = Subpipeline.Create(pipeline); pipeline.RunAsync(); var stopped = pipeline.WaitAll(1000); Assert.IsFalse(stopped); } } // A generator that provides a periodic stream with a configurable artificial latency public class GeneratorWithLatency : Generator { private readonly TimeSpan interval; private readonly TimeSpan latency; public GeneratorWithLatency(Pipeline pipeline, TimeSpan interval, TimeSpan latency) : base(pipeline, isInfiniteSource: true) { this.interval = interval; this.latency = latency; this.Out = pipeline.CreateEmitter<int>(this, nameof(this.Out)); } public Emitter<int> Out { get; } protected override DateTime GenerateNext(DateTime currentTime) { // introduce a delay (in wall-clock time) to artificially slow down the generator Thread.Sleep(this.latency); this.Out.Post(0, currentTime); return currentTime + this.interval; } } [TestMethod] [Timeout(60000)] public void PipelineShutdownWithLatency() { using (var p = Pipeline.Create("root")) { // input sequence var generator = Generators.Sequence(p, new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, TimeSpan.FromMilliseconds(50)); // use a generator (with artificial latency) as the clock for densification // increase the latency TimeSpan value to cause the test to fail when shutdown doesn't account for slow sources var clock = new GeneratorWithLatency(p, TimeSpan.FromMilliseconds(10), TimeSpan.FromMilliseconds(500)); // The densified stream which should contain five of every input value, except for the last value, // since the clock stream has a frequency of 5x the generated sequence stream. var densified = clock.Out.Join(generator.Out, RelativeTimeInterval.Past()).Select(x => x.Item2); var seq = densified.ToObservable().ToListObservable(); p.Run(); var results = seq.AsEnumerable().ToArray(); CollectionAssert.AreEqual( new[] { 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 10, }, results); } } // A composite component which contains a GeneratorWithLatency used to densify an input stream public class TestSourceComponentWithGenerator : Subpipeline { public TestSourceComponentWithGenerator(Pipeline parent, TimeSpan interval, TimeSpan latency) : base(parent, "sub") { var input = this.CreateInputConnectorFrom<int>(parent, "Input"); var output = this.CreateOutputConnectorTo<int>(parent, "Output"); this.In = input.In; this.Out = output.Out; // create a clock stream (with artificial latency) for densification of the input stream var clock = new GeneratorWithLatency(this, interval, latency); // densify the input stream by joining the clock stream with it var densified = clock.Out.Join(input.Out, RelativeTimeInterval.Past()).Select(x => x.Item2); densified.PipeTo(output.In); } public Receiver<int> In { get; } public Emitter<int> Out { get; } } [TestMethod] [Timeout(60000)] public void SubpipelineShutdownWithLatency() { using (var p = Pipeline.Create("root")) { // input sequence var generator = Generators.Sequence(p, new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, TimeSpan.FromMilliseconds(50)); // use a generator (with artificial latency) as the clock for densification // increase the latency TimeSpan value to cause the test to fail when shutdown doesn't account for slow sources var densifier = new TestSourceComponentWithGenerator(p, TimeSpan.FromMilliseconds(25), TimeSpan.FromMilliseconds(50)); generator.PipeTo(densifier.In); // the densified stream which should contain two of every input value, except for the last value var seq = densifier.Out.ToObservable().ToListObservable(); p.Run(); var results = seq.AsEnumerable().ToArray(); CollectionAssert.AreEqual(new[] { 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10 }, results); } } [TestMethod] [Timeout(60000)] public void PipelineShutdownWithPendingMessage() { var mre = new ManualResetEvent(false); var p = Pipeline.Create("root"); // Post two messages with an interval of 10 seconds Generators.Repeat(p, 0, 2, TimeSpan.FromSeconds(10000)).Do(_ => mre.Set()); // Run the pipeline, and stop it as soon as the first message is seen var stopwatch = System.Diagnostics.Stopwatch.StartNew(); p.RunAsync(); mre.WaitOne(); p.Dispose(); stopwatch.Stop(); // The pipeline should shutdown without waiting for the Generator's loopback message Assert.IsTrue(stopwatch.ElapsedMilliseconds < 5000); } [TestMethod] [Timeout(60000)] [ExpectedException(typeof(InvalidOperationException))] public void DisallowAddingComponentsToAlreadyRunningPipeline() { using (var p = Pipeline.Create()) { var gen = Generators.Range(p, 0, 10, TimeSpan.FromTicks(1)); p.RunAsync(); Assert.IsFalse(p.WaitAll(0)); // running // add generator while running Generators.Range(p, 0, 10, TimeSpan.FromTicks(1)); } } [TestMethod] [Timeout(60000)] public void FinalizationTestSimple() { var log = new List<string>(); using (var p = Pipeline.Create()) { /* * =---= =---= * | A |--->| B | * =---= =---= */ var b = new FinalizationTestComponent(p, "B", log); var a = new FinalizationTestComponent(p, "A", log); // finalized 1st although constructed 2nd a.Generator.PipeTo(b.ReceiverX); p.Run(); } // all emitters should have closed Assert.IsTrue(log.Contains("AEmitterAny Closed")); Assert.IsTrue(log.Contains("AEmitterX Closed")); Assert.IsTrue(log.Contains("AEmitterY Closed")); Assert.IsTrue(log.Contains("AEmitterZ Closed")); Assert.IsTrue(log.Contains("AEmitterGen Closed")); Assert.IsTrue(log.Contains("BEmitterAny Closed")); Assert.IsTrue(log.Contains("BEmitterX Closed")); Assert.IsTrue(log.Contains("BEmitterY Closed")); Assert.IsTrue(log.Contains("BEmitterZ Closed")); Assert.IsTrue(log.Contains("BEmitterGen Closed")); // A emitters should have closed before B emitters Assert.IsTrue(log.IndexOf("AEmitterAny Closed") < log.IndexOf("BEmitterAny Closed")); Assert.IsTrue(log.IndexOf("AEmitterX Closed") < log.IndexOf("BEmitterX Closed")); Assert.IsTrue(log.IndexOf("AEmitterY Closed") < log.IndexOf("BEmitterY Closed")); Assert.IsTrue(log.IndexOf("AEmitterZ Closed") < log.IndexOf("BEmitterZ Closed")); Assert.IsTrue(log.IndexOf("AEmitterGen Closed") < log.IndexOf("BEmitterGen Closed")); // subscribed receivers should have been unsubscribed Assert.IsTrue(log.Contains("BReceiverX Unsubscribed")); // non-subscribed receivers should have done *nothing* Assert.IsFalse(log.Contains("AReceiverX Unsubscribed")); Assert.IsFalse(log.Contains("AReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("AReceiverZ Unsubscribed")); Assert.IsFalse(log.Contains("BReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("BReceiverZ Unsubscribed")); } [TestMethod] [Timeout(60000)] public void FinalizationTestSelfCycle() { var log = new List<string>(); using (var p = Pipeline.Create()) { /* * =---= * | A |---+ * =---= | * ^ | * | | * +-----+ */ var a = new FinalizationTestComponent(p, "A", log); a.Generator.PipeTo(a.ReceiverX); // cycle to itself p.Run(); } // all emitters should have closed Assert.IsTrue(log.Contains("AEmitterAny Closed")); Assert.IsTrue(log.Contains("AEmitterX Closed")); Assert.IsTrue(log.Contains("AEmitterY Closed")); Assert.IsTrue(log.Contains("AEmitterZ Closed")); Assert.IsTrue(log.Contains("AEmitterGen Closed")); // subscribed receivers should have been unsubscribed Assert.IsTrue(log.Contains("AReceiverX Unsubscribed")); // non-subscribed receivers should have done *nothing* Assert.IsFalse(log.Contains("AReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("AReceiverZ Unsubscribed")); } [TestMethod] [Timeout(60000)] public void FinalizationTestLongCycle() { var log = new List<string>(); using (var p = Pipeline.Create()) { /* * =---= =---= =---= * | A |--->| B |--->| C |---+ * =---= =---= =---= | * ^ | * | | * +-----------------------+ */ var c = new FinalizationTestComponent(p, "C", log); var b = new FinalizationTestComponent(p, "B", log); var a = new FinalizationTestComponent(p, "A", log); a.Generator.PipeTo(b.ReceiverX); b.RelayFromX.PipeTo(c.ReceiverX); c.RelayFromX.PipeTo(a.ReceiverX); p.Run(); } // all emitters should have closed Assert.IsTrue(log.Contains("AEmitterAny Closed")); Assert.IsTrue(log.Contains("AEmitterX Closed")); Assert.IsTrue(log.Contains("AEmitterY Closed")); Assert.IsTrue(log.Contains("AEmitterZ Closed")); Assert.IsTrue(log.Contains("AEmitterGen Closed")); Assert.IsTrue(log.Contains("BEmitterAny Closed")); Assert.IsTrue(log.Contains("BEmitterX Closed")); Assert.IsTrue(log.Contains("BEmitterY Closed")); Assert.IsTrue(log.Contains("BEmitterZ Closed")); Assert.IsTrue(log.Contains("BEmitterGen Closed")); Assert.IsTrue(log.Contains("CEmitterAny Closed")); Assert.IsTrue(log.Contains("CEmitterX Closed")); Assert.IsTrue(log.Contains("CEmitterY Closed")); Assert.IsTrue(log.Contains("CEmitterZ Closed")); Assert.IsTrue(log.Contains("CEmitterGen Closed")); // Emitters should have closed in C, A, B order Assert.IsTrue(log.IndexOf("CEmitterAny Closed") < log.IndexOf("AEmitterAny Closed")); Assert.IsTrue(log.IndexOf("CEmitterX Closed") < log.IndexOf("AEmitterX Closed")); Assert.IsTrue(log.IndexOf("CEmitterY Closed") < log.IndexOf("AEmitterY Closed")); Assert.IsTrue(log.IndexOf("CEmitterZ Closed") < log.IndexOf("AEmitterZ Closed")); Assert.IsTrue(log.IndexOf("CEmitterGen Closed") < log.IndexOf("AEmitterGen Closed")); Assert.IsTrue(log.IndexOf("AEmitterAny Closed") < log.IndexOf("BEmitterAny Closed")); Assert.IsTrue(log.IndexOf("AEmitterX Closed") < log.IndexOf("BEmitterX Closed")); Assert.IsTrue(log.IndexOf("AEmitterY Closed") < log.IndexOf("BEmitterY Closed")); Assert.IsTrue(log.IndexOf("AEmitterZ Closed") < log.IndexOf("BEmitterZ Closed")); Assert.IsTrue(log.IndexOf("AEmitterGen Closed") < log.IndexOf("BEmitterGen Closed")); // subscribed receivers should have been unsubscribed Assert.IsTrue(log.Contains("AReceiverX Unsubscribed")); Assert.IsTrue(log.Contains("BReceiverX Unsubscribed")); Assert.IsTrue(log.Contains("CReceiverX Unsubscribed")); // non-subscribed receivers should have done *nothing* Assert.IsFalse(log.Contains("AReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("AReceiverZ Unsubscribed")); Assert.IsFalse(log.Contains("BReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("BReceiverZ Unsubscribed")); Assert.IsFalse(log.Contains("CReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("CReceiverZ Unsubscribed")); } [TestMethod] [Timeout(60000)] public void FinalizationTestDisjointCycles() { var log = new List<string>(); using (var p = Pipeline.Create()) { /* * =---= =---= =---= =---= * | A |--->| C | | B |--->| D | * =---= =---= =---= =---= * ^ | ^ | * | | | | * +--------+ +--------+ */ var d = new FinalizationTestComponent(p, "D", log); var c = new FinalizationTestComponent(p, "C", log); var b = new FinalizationTestComponent(p, "B", log); var a = new FinalizationTestComponent(p, "A", log); a.Generator.PipeTo(c.ReceiverX); b.Generator.PipeTo(d.ReceiverX); c.RelayFromX.PipeTo(a.ReceiverX); d.RelayFromX.PipeTo(b.ReceiverX); p.Run(); } // all emitters should have closed Assert.IsTrue(log.Contains("AEmitterAny Closed")); Assert.IsTrue(log.Contains("AEmitterX Closed")); Assert.IsTrue(log.Contains("AEmitterY Closed")); Assert.IsTrue(log.Contains("AEmitterZ Closed")); Assert.IsTrue(log.Contains("AEmitterGen Closed")); Assert.IsTrue(log.Contains("BEmitterAny Closed")); Assert.IsTrue(log.Contains("BEmitterX Closed")); Assert.IsTrue(log.Contains("BEmitterY Closed")); Assert.IsTrue(log.Contains("BEmitterZ Closed")); Assert.IsTrue(log.Contains("BEmitterGen Closed")); Assert.IsTrue(log.Contains("CEmitterAny Closed")); Assert.IsTrue(log.Contains("CEmitterX Closed")); Assert.IsTrue(log.Contains("CEmitterY Closed")); Assert.IsTrue(log.Contains("CEmitterZ Closed")); Assert.IsTrue(log.Contains("CEmitterGen Closed")); Assert.IsTrue(log.Contains("DEmitterAny Closed")); Assert.IsTrue(log.Contains("DEmitterX Closed")); Assert.IsTrue(log.Contains("DEmitterY Closed")); Assert.IsTrue(log.Contains("DEmitterZ Closed")); Assert.IsTrue(log.Contains("DEmitterGen Closed")); // Emitters should have closed in D, C, then B or A order Assert.IsTrue(log.IndexOf("DEmitterAny Closed") < log.IndexOf("CEmitterAny Closed")); Assert.IsTrue(log.IndexOf("DEmitterX Closed") < log.IndexOf("CEmitterX Closed")); Assert.IsTrue(log.IndexOf("DEmitterY Closed") < log.IndexOf("CEmitterY Closed")); Assert.IsTrue(log.IndexOf("DEmitterZ Closed") < log.IndexOf("CEmitterZ Closed")); Assert.IsTrue(log.IndexOf("DEmitterGen Closed") < log.IndexOf("CEmitterGen Closed")); Assert.IsTrue(log.IndexOf("CEmitterAny Closed") < log.IndexOf("BEmitterAny Closed")); Assert.IsTrue(log.IndexOf("CEmitterX Closed") < log.IndexOf("BEmitterX Closed")); Assert.IsTrue(log.IndexOf("CEmitterY Closed") < log.IndexOf("BEmitterY Closed")); Assert.IsTrue(log.IndexOf("CEmitterZ Closed") < log.IndexOf("BEmitterZ Closed")); Assert.IsTrue(log.IndexOf("CEmitterGen Closed") < log.IndexOf("BEmitterGen Closed")); Assert.IsTrue(log.IndexOf("CEmitterAny Closed") < log.IndexOf("AEmitterAny Closed")); Assert.IsTrue(log.IndexOf("CEmitterX Closed") < log.IndexOf("AEmitterX Closed")); Assert.IsTrue(log.IndexOf("CEmitterY Closed") < log.IndexOf("AEmitterY Closed")); Assert.IsTrue(log.IndexOf("CEmitterZ Closed") < log.IndexOf("AEmitterZ Closed")); Assert.IsTrue(log.IndexOf("CEmitterGen Closed") < log.IndexOf("AEmitterGen Closed")); // subscribed receivers should have been unsubscribed Assert.IsTrue(log.Contains("AReceiverX Unsubscribed")); Assert.IsTrue(log.Contains("BReceiverX Unsubscribed")); Assert.IsTrue(log.Contains("CReceiverX Unsubscribed")); Assert.IsTrue(log.Contains("DReceiverX Unsubscribed")); // non-subscribed receivers should have done *nothing* Assert.IsFalse(log.Contains("AReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("AReceiverZ Unsubscribed")); Assert.IsFalse(log.Contains("BReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("BReceiverZ Unsubscribed")); Assert.IsFalse(log.Contains("CReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("CReceiverZ Unsubscribed")); Assert.IsFalse(log.Contains("DReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("DReceiverZ Unsubscribed")); } [TestMethod] [Timeout(60000)] public void FinalizationTestDisjointUpstreamSelfCycles() { var log = new List<string>(); using (var p = Pipeline.Create()) { /* * =---= =---= =---= =---= * +-->| A |--->| B | +-->| C |--->| D | * | =---= =---= | =---= =---= * | | | | * +-----+ +-----+ */ var d = new FinalizationTestComponent(p, "D", log); var c = new FinalizationTestComponent(p, "C", log); // finalized 1st although constructed 2nd var b = new FinalizationTestComponent(p, "B", log); var a = new FinalizationTestComponent(p, "A", log); a.Generator.PipeTo(a.ReceiverX); a.RelayFromX.PipeTo(b.ReceiverX); c.Generator.PipeTo(c.ReceiverX); c.RelayFromX.PipeTo(d.ReceiverX); p.Run(); } // all emitters should have closed Assert.IsTrue(log.Contains("AEmitterAny Closed")); Assert.IsTrue(log.Contains("AEmitterX Closed")); Assert.IsTrue(log.Contains("AEmitterY Closed")); Assert.IsTrue(log.Contains("AEmitterZ Closed")); Assert.IsTrue(log.Contains("AEmitterGen Closed")); Assert.IsTrue(log.Contains("BEmitterAny Closed")); Assert.IsTrue(log.Contains("BEmitterX Closed")); Assert.IsTrue(log.Contains("BEmitterY Closed")); Assert.IsTrue(log.Contains("BEmitterZ Closed")); Assert.IsTrue(log.Contains("BEmitterGen Closed")); Assert.IsTrue(log.Contains("CEmitterAny Closed")); Assert.IsTrue(log.Contains("CEmitterX Closed")); Assert.IsTrue(log.Contains("CEmitterY Closed")); Assert.IsTrue(log.Contains("CEmitterZ Closed")); Assert.IsTrue(log.Contains("CEmitterGen Closed")); Assert.IsTrue(log.Contains("DEmitterAny Closed")); Assert.IsTrue(log.Contains("DEmitterX Closed")); Assert.IsTrue(log.Contains("DEmitterY Closed")); Assert.IsTrue(log.Contains("DEmitterZ Closed")); Assert.IsTrue(log.Contains("DEmitterGen Closed")); // Emitters should have closed in C, A, then D or B order Assert.IsTrue(log.IndexOf("CEmitterAny Closed") < log.IndexOf("AEmitterAny Closed")); Assert.IsTrue(log.IndexOf("CEmitterX Closed") < log.IndexOf("AEmitterX Closed")); Assert.IsTrue(log.IndexOf("CEmitterY Closed") < log.IndexOf("AEmitterY Closed")); Assert.IsTrue(log.IndexOf("CEmitterZ Closed") < log.IndexOf("AEmitterZ Closed")); Assert.IsTrue(log.IndexOf("CEmitterGen Closed") < log.IndexOf("AEmitterGen Closed")); Assert.IsTrue(log.IndexOf("AEmitterAny Closed") < log.IndexOf("DEmitterAny Closed")); Assert.IsTrue(log.IndexOf("AEmitterX Closed") < log.IndexOf("DEmitterX Closed")); Assert.IsTrue(log.IndexOf("AEmitterY Closed") < log.IndexOf("DEmitterY Closed")); Assert.IsTrue(log.IndexOf("AEmitterZ Closed") < log.IndexOf("DEmitterZ Closed")); Assert.IsTrue(log.IndexOf("AEmitterGen Closed") < log.IndexOf("DEmitterGen Closed")); Assert.IsTrue(log.IndexOf("AEmitterAny Closed") < log.IndexOf("BEmitterAny Closed")); Assert.IsTrue(log.IndexOf("AEmitterX Closed") < log.IndexOf("BEmitterX Closed")); Assert.IsTrue(log.IndexOf("AEmitterY Closed") < log.IndexOf("BEmitterY Closed")); Assert.IsTrue(log.IndexOf("AEmitterZ Closed") < log.IndexOf("BEmitterZ Closed")); Assert.IsTrue(log.IndexOf("AEmitterGen Closed") < log.IndexOf("BEmitterGen Closed")); // subscribed receivers should have been unsubscribed Assert.IsTrue(log.Contains("AReceiverX Unsubscribed")); Assert.IsTrue(log.Contains("BReceiverX Unsubscribed")); Assert.IsTrue(log.Contains("CReceiverX Unsubscribed")); Assert.IsTrue(log.Contains("DReceiverX Unsubscribed")); // non-subscribed receivers should have done *nothing* Assert.IsFalse(log.Contains("AReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("AReceiverZ Unsubscribed")); Assert.IsFalse(log.Contains("BReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("BReceiverZ Unsubscribed")); Assert.IsFalse(log.Contains("CReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("CReceiverZ Unsubscribed")); Assert.IsFalse(log.Contains("DReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("DReceiverZ Unsubscribed")); } [TestMethod] [Timeout(60000)] public void FinalizationTestMultiUpstream() { var log = new List<string>(); using (var p = Pipeline.Create()) { /* * =---= * | A |-- * =---= \ =---= * -->| | * | C | * -->| | * =---= / =---= * | B |-- * =---= */ var c = new FinalizationTestComponent(p, "C", log); // finalized last although constructed 1st var b = new FinalizationTestComponent(p, "B", log); var a = new FinalizationTestComponent(p, "A", log); a.Generator.PipeTo(c.ReceiverX); b.Generator.PipeTo(c.ReceiverY); p.Run(); } // all emitters should have closed Assert.IsTrue(log.Contains("AEmitterAny Closed")); Assert.IsTrue(log.Contains("AEmitterX Closed")); Assert.IsTrue(log.Contains("AEmitterY Closed")); Assert.IsTrue(log.Contains("AEmitterZ Closed")); Assert.IsTrue(log.Contains("AEmitterGen Closed")); Assert.IsTrue(log.Contains("BEmitterAny Closed")); Assert.IsTrue(log.Contains("BEmitterX Closed")); Assert.IsTrue(log.Contains("BEmitterY Closed")); Assert.IsTrue(log.Contains("BEmitterZ Closed")); Assert.IsTrue(log.Contains("BEmitterGen Closed")); Assert.IsTrue(log.Contains("CEmitterAny Closed")); Assert.IsTrue(log.Contains("CEmitterX Closed")); Assert.IsTrue(log.Contains("CEmitterY Closed")); Assert.IsTrue(log.Contains("CEmitterZ Closed")); Assert.IsTrue(log.Contains("CEmitterGen Closed")); // A and B emitters may close in any order relative to one another, but *before* C emitters Assert.IsTrue(log.IndexOf("AEmitterAny Closed") < log.IndexOf("CEmitterAny Closed")); Assert.IsTrue(log.IndexOf("AEmitterX Closed") < log.IndexOf("CEmitterX Closed")); Assert.IsTrue(log.IndexOf("AEmitterY Closed") < log.IndexOf("CEmitterY Closed")); Assert.IsTrue(log.IndexOf("AEmitterZ Closed") < log.IndexOf("CEmitterZ Closed")); Assert.IsTrue(log.IndexOf("AEmitterGen Closed") < log.IndexOf("CEmitterGen Closed")); Assert.IsTrue(log.IndexOf("BEmitterAny Closed") < log.IndexOf("CEmitterAny Closed")); Assert.IsTrue(log.IndexOf("BEmitterX Closed") < log.IndexOf("CEmitterX Closed")); Assert.IsTrue(log.IndexOf("BEmitterY Closed") < log.IndexOf("CEmitterY Closed")); Assert.IsTrue(log.IndexOf("BEmitterZ Closed") < log.IndexOf("CEmitterZ Closed")); Assert.IsTrue(log.IndexOf("BEmitterGen Closed") < log.IndexOf("CEmitterGen Closed")); // subscribed receivers should have been unsubscribed Assert.IsTrue(log.Contains("CReceiverX Unsubscribed")); Assert.IsTrue(log.Contains("CReceiverY Unsubscribed")); // non-subscribed receivers should have done *nothing* Assert.IsFalse(log.Contains("AReceiverX Unsubscribed")); Assert.IsFalse(log.Contains("AReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("AReceiverZ Unsubscribed")); Assert.IsFalse(log.Contains("BReceiverX Unsubscribed")); Assert.IsFalse(log.Contains("BReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("BReceiverZ Unsubscribed")); Assert.IsFalse(log.Contains("BReceiverZ Unsubscribed")); } [TestMethod] [Timeout(60000)] public void FinalizationTestFeedbackLoop() { // this exercises shutdown with active run-away feedback loops var log = new List<string>(); using (var p = Pipeline.Create()) { /* * =---= =---= * | |--->| | * | A | | B |---+ * | |--->| | | * =---= =---= | * ^ | * | | * +--------------+ * * Feeding time interval, plus feedback loop */ var b = new FinalizationTestComponent(p, "B", log); var a = new FinalizationTestComponent(p, "A", log); a.Generator.PipeTo(b.ReceiverY); // timer initiating on emitter Generator b.RelayFromAny.PipeTo(a.ReceiverX); // emitter RelayFromAny feeding back on receiver X a.RelayFromX.PipeTo(b.ReceiverX); p.Run(); } // There should be exactly 3 original messages var countY = log.Where(line => line.StartsWith("BReceiveY")).Count(); Assert.AreEqual(3, countY); // Additional are expected on X because of the feedback loop var countX = log.Where(line => line.StartsWith("BReceiveX")).Count(); Assert.IsTrue(countX >= 1); // all emitters should have closed Assert.IsTrue(log.Contains("AEmitterAny Closed")); Assert.IsTrue(log.Contains("AEmitterX Closed")); Assert.IsTrue(log.Contains("AEmitterY Closed")); Assert.IsTrue(log.Contains("AEmitterZ Closed")); Assert.IsTrue(log.Contains("AEmitterGen Closed")); Assert.IsTrue(log.Contains("BEmitterAny Closed")); Assert.IsTrue(log.Contains("BEmitterX Closed")); Assert.IsTrue(log.Contains("BEmitterY Closed")); Assert.IsTrue(log.Contains("BEmitterZ Closed")); Assert.IsTrue(log.Contains("BEmitterGen Closed")); // subscribed receivers should have been unsubscribed Assert.IsTrue(log.Contains("BReceiverX Unsubscribed")); Assert.IsTrue(log.Contains("BReceiverY Unsubscribed")); // non-subscribed receivers should have done *nothing* Assert.IsFalse(log.Contains("AReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("AReceiverZ Unsubscribed")); Assert.IsFalse(log.Contains("BReceiverZ Unsubscribed")); } [TestMethod] [Timeout(60000)] public void FinalizationTestWithSubpipeline() { // this exercises traversal of Connector cross-pipeline bridges // internally, a node (PipelineElement) is created on each side with a shared state object (the Connector component) // finalization traverses these boundaries var log = new List<string>(); using (var p = Pipeline.Create()) { /* * .................. * =---= . =---= =---= . =---= * | A |--->| B |--->| C |--->| D |---+ * =---= . =---= =---= . =---= | * ^ .................. | * | | * +--------------------------------+ * * With B & C in subpipeline */ var sub = new Subpipeline(p); var cIn = new Connector<int>(p, sub); var cOut = new Connector<int>(sub, p); var d = new FinalizationTestComponent(p, "D", log); var c = new FinalizationTestComponent(sub, "C", log); var b = new FinalizationTestComponent(sub, "B", log); var a = new FinalizationTestComponent(p, "A", log); a.Generator.PipeTo(cIn.In); cIn.Out.PipeTo(b.ReceiverX); b.RelayFromX.PipeTo(c.ReceiverX); c.RelayFromX.PipeTo(cOut.In); cOut.Out.PipeTo(d.ReceiverX); p.Run(); } // all emitters should have closed Assert.IsTrue(log.Contains("AEmitterAny Closed")); Assert.IsTrue(log.Contains("AEmitterX Closed")); Assert.IsTrue(log.Contains("AEmitterY Closed")); Assert.IsTrue(log.Contains("AEmitterZ Closed")); Assert.IsTrue(log.Contains("AEmitterGen Closed")); Assert.IsTrue(log.Contains("BEmitterAny Closed")); Assert.IsTrue(log.Contains("BEmitterX Closed")); Assert.IsTrue(log.Contains("BEmitterY Closed")); Assert.IsTrue(log.Contains("BEmitterZ Closed")); Assert.IsTrue(log.Contains("BEmitterGen Closed")); Assert.IsTrue(log.Contains("CEmitterAny Closed")); Assert.IsTrue(log.Contains("CEmitterX Closed")); Assert.IsTrue(log.Contains("CEmitterY Closed")); Assert.IsTrue(log.Contains("CEmitterZ Closed")); Assert.IsTrue(log.Contains("CEmitterGen Closed")); Assert.IsTrue(log.Contains("DEmitterAny Closed")); Assert.IsTrue(log.Contains("DEmitterX Closed")); Assert.IsTrue(log.Contains("DEmitterY Closed")); Assert.IsTrue(log.Contains("DEmitterZ Closed")); Assert.IsTrue(log.Contains("DEmitterGen Closed")); // Emitters should have closed in A to D order Assert.IsTrue(log.IndexOf("CEmitterAny Closed") < log.IndexOf("DEmitterAny Closed")); Assert.IsTrue(log.IndexOf("CEmitterX Closed") < log.IndexOf("DEmitterX Closed")); Assert.IsTrue(log.IndexOf("CEmitterY Closed") < log.IndexOf("DEmitterY Closed")); Assert.IsTrue(log.IndexOf("CEmitterZ Closed") < log.IndexOf("DEmitterZ Closed")); Assert.IsTrue(log.IndexOf("CEmitterGen Closed") < log.IndexOf("DEmitterGen Closed")); Assert.IsTrue(log.IndexOf("BEmitterAny Closed") < log.IndexOf("CEmitterAny Closed")); Assert.IsTrue(log.IndexOf("BEmitterX Closed") < log.IndexOf("CEmitterX Closed")); Assert.IsTrue(log.IndexOf("BEmitterY Closed") < log.IndexOf("CEmitterY Closed")); Assert.IsTrue(log.IndexOf("BEmitterZ Closed") < log.IndexOf("CEmitterZ Closed")); Assert.IsTrue(log.IndexOf("BEmitterGen Closed") < log.IndexOf("CEmitterGen Closed")); Assert.IsTrue(log.IndexOf("AEmitterAny Closed") < log.IndexOf("BEmitterAny Closed")); Assert.IsTrue(log.IndexOf("AEmitterX Closed") < log.IndexOf("BEmitterX Closed")); Assert.IsTrue(log.IndexOf("AEmitterY Closed") < log.IndexOf("BEmitterY Closed")); Assert.IsTrue(log.IndexOf("AEmitterZ Closed") < log.IndexOf("BEmitterZ Closed")); Assert.IsTrue(log.IndexOf("AEmitterGen Closed") < log.IndexOf("BEmitterGen Closed")); // subscribed receivers should have been unsubscribed Assert.IsTrue(log.Contains("BReceiverX Unsubscribed")); Assert.IsTrue(log.Contains("CReceiverX Unsubscribed")); Assert.IsTrue(log.Contains("DReceiverX Unsubscribed")); // non-subscribed receivers should have done *nothing* Assert.IsFalse(log.Contains("AReceiverX Unsubscribed")); Assert.IsFalse(log.Contains("AReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("AReceiverZ Unsubscribed")); Assert.IsFalse(log.Contains("BReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("BReceiverZ Unsubscribed")); Assert.IsFalse(log.Contains("CReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("CReceiverZ Unsubscribed")); Assert.IsFalse(log.Contains("DReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("DReceiverZ Unsubscribed")); } [TestMethod] [Timeout(60000)] public void FinalizationTestWithNestedSubpipelines() { // this exercises message traversal and pipeline shutdown across nested subpipelines var log = new List<string>(); using (var p = Pipeline.Create("pipeline")) { /* * ........................... * . ......... . * =---= . =---= . =---= . =---= . =---= * | A |--->| B |--->| C |--->| D |--->| E | * =---= . =---= . =---= . =---= . =---= * . ......... . * ........................... * * With B & D in subpipeline1 and C in subpipeline2 */ var sub1 = new Subpipeline(p, "subpipeline1"); var cIn1 = new Connector<int>(p, sub1); var cOut1 = new Connector<int>(sub1, p); var sub2 = new Subpipeline(sub1, "subpipeline2"); var cIn2 = new Connector<int>(sub1, sub2); var cOut2 = new Connector<int>(sub2, sub1); var e = new FinalizationTestComponent(p, "E", log); var d = new FinalizationTestComponent(sub1, "D", log); var c = new FinalizationTestComponent(sub2, "C", log); var b = new FinalizationTestComponent(sub1, "B", log); var a = new FinalizationTestComponent(p, "A", log); a.Generator.PipeTo(cIn1.In); cIn1.In.Unsubscribed += time => sub1.Stop(time); cIn1.Out.PipeTo(b.ReceiverX); b.RelayFromX.PipeTo(cIn2.In); cIn2.In.Unsubscribed += time => sub2.Stop(time); cIn2.Out.PipeTo(c.ReceiverX); c.RelayFromX.PipeTo(cOut2.In); cOut2.Out.PipeTo(d.ReceiverX); d.RelayFromX.PipeTo(cOut1.In); cOut1.Out.PipeTo(e.ReceiverX); p.Run(); } // all emitters should have closed Assert.IsTrue(log.Contains("AEmitterAny Closed")); Assert.IsTrue(log.Contains("AEmitterX Closed")); Assert.IsTrue(log.Contains("AEmitterY Closed")); Assert.IsTrue(log.Contains("AEmitterZ Closed")); Assert.IsTrue(log.Contains("AEmitterGen Closed")); Assert.IsTrue(log.Contains("BEmitterAny Closed")); Assert.IsTrue(log.Contains("BEmitterX Closed")); Assert.IsTrue(log.Contains("BEmitterY Closed")); Assert.IsTrue(log.Contains("BEmitterZ Closed")); Assert.IsTrue(log.Contains("BEmitterGen Closed")); Assert.IsTrue(log.Contains("CEmitterAny Closed")); Assert.IsTrue(log.Contains("CEmitterX Closed")); Assert.IsTrue(log.Contains("CEmitterY Closed")); Assert.IsTrue(log.Contains("CEmitterZ Closed")); Assert.IsTrue(log.Contains("CEmitterGen Closed")); Assert.IsTrue(log.Contains("DEmitterAny Closed")); Assert.IsTrue(log.Contains("DEmitterX Closed")); Assert.IsTrue(log.Contains("DEmitterY Closed")); Assert.IsTrue(log.Contains("DEmitterZ Closed")); Assert.IsTrue(log.Contains("DEmitterGen Closed")); Assert.IsTrue(log.Contains("EEmitterAny Closed")); Assert.IsTrue(log.Contains("EEmitterX Closed")); Assert.IsTrue(log.Contains("EEmitterY Closed")); Assert.IsTrue(log.Contains("EEmitterZ Closed")); Assert.IsTrue(log.Contains("EEmitterGen Closed")); // Emitters should have closed in A to E order Assert.IsTrue(log.IndexOf("DEmitterAny Closed") < log.IndexOf("EEmitterAny Closed")); Assert.IsTrue(log.IndexOf("DEmitterX Closed") < log.IndexOf("EEmitterX Closed")); Assert.IsTrue(log.IndexOf("DEmitterY Closed") < log.IndexOf("EEmitterY Closed")); Assert.IsTrue(log.IndexOf("DEmitterZ Closed") < log.IndexOf("EEmitterZ Closed")); Assert.IsTrue(log.IndexOf("DEmitterGen Closed") < log.IndexOf("EEmitterGen Closed")); Assert.IsTrue(log.IndexOf("CEmitterAny Closed") < log.IndexOf("DEmitterAny Closed")); Assert.IsTrue(log.IndexOf("CEmitterX Closed") < log.IndexOf("DEmitterX Closed")); Assert.IsTrue(log.IndexOf("CEmitterY Closed") < log.IndexOf("DEmitterY Closed")); Assert.IsTrue(log.IndexOf("CEmitterZ Closed") < log.IndexOf("DEmitterZ Closed")); Assert.IsTrue(log.IndexOf("CEmitterGen Closed") < log.IndexOf("DEmitterGen Closed")); Assert.IsTrue(log.IndexOf("BEmitterAny Closed") < log.IndexOf("CEmitterAny Closed")); Assert.IsTrue(log.IndexOf("BEmitterX Closed") < log.IndexOf("CEmitterX Closed")); Assert.IsTrue(log.IndexOf("BEmitterY Closed") < log.IndexOf("CEmitterY Closed")); Assert.IsTrue(log.IndexOf("BEmitterZ Closed") < log.IndexOf("CEmitterZ Closed")); Assert.IsTrue(log.IndexOf("BEmitterGen Closed") < log.IndexOf("CEmitterGen Closed")); Assert.IsTrue(log.IndexOf("AEmitterAny Closed") < log.IndexOf("BEmitterAny Closed")); Assert.IsTrue(log.IndexOf("AEmitterX Closed") < log.IndexOf("BEmitterX Closed")); Assert.IsTrue(log.IndexOf("AEmitterY Closed") < log.IndexOf("BEmitterY Closed")); Assert.IsTrue(log.IndexOf("AEmitterZ Closed") < log.IndexOf("BEmitterZ Closed")); Assert.IsTrue(log.IndexOf("AEmitterGen Closed") < log.IndexOf("BEmitterGen Closed")); // subscribed receivers should have been unsubscribed Assert.IsTrue(log.Contains("BReceiverX Unsubscribed")); Assert.IsTrue(log.Contains("CReceiverX Unsubscribed")); Assert.IsTrue(log.Contains("DReceiverX Unsubscribed")); Assert.IsTrue(log.Contains("EReceiverX Unsubscribed")); // non-subscribed receivers should have done *nothing* Assert.IsFalse(log.Contains("AReceiverX Unsubscribed")); Assert.IsFalse(log.Contains("AReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("AReceiverZ Unsubscribed")); Assert.IsFalse(log.Contains("BReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("BReceiverZ Unsubscribed")); Assert.IsFalse(log.Contains("CReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("CReceiverZ Unsubscribed")); Assert.IsFalse(log.Contains("DReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("DReceiverZ Unsubscribed")); Assert.IsFalse(log.Contains("EReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("EReceiverZ Unsubscribed")); } [TestMethod] [Timeout(60000)] public void FinalizationTestWithCycleAndUpstreamNonCycle() { // this exercises detection of upstream cycles to origin, but // unable to finalize until upstream *non*-cycles are handled var log = new List<string>(); using (var p = Pipeline.Create()) { /* * =---= =---= * | A |--->| B |-- * =---= =---= \ =---= * -->| | * | E | * -->| | * =---= =---= / =---= * | C |--->| D |-- | * =---= =---= | * ^ | * | | * +-------------------+ */ var e = new FinalizationTestComponent(p, "E", log); var d = new FinalizationTestComponent(p, "D", log); var c = new FinalizationTestComponent(p, "C", log); var b = new FinalizationTestComponent(p, "B", log); var a = new FinalizationTestComponent(p, "A", log); a.Generator.PipeTo(b.ReceiverX); c.RelayFromX.PipeTo(d.ReceiverX); b.RelayFromX.PipeTo(e.ReceiverX); d.RelayFromX.PipeTo(e.ReceiverY); e.Generator.PipeTo(c.ReceiverX); p.Run(); } // all emitters should have closed Assert.IsTrue(log.Contains("AEmitterAny Closed")); Assert.IsTrue(log.Contains("AEmitterX Closed")); Assert.IsTrue(log.Contains("AEmitterY Closed")); Assert.IsTrue(log.Contains("AEmitterZ Closed")); Assert.IsTrue(log.Contains("AEmitterGen Closed")); Assert.IsTrue(log.Contains("BEmitterAny Closed")); Assert.IsTrue(log.Contains("BEmitterX Closed")); Assert.IsTrue(log.Contains("BEmitterY Closed")); Assert.IsTrue(log.Contains("BEmitterZ Closed")); Assert.IsTrue(log.Contains("BEmitterGen Closed")); Assert.IsTrue(log.Contains("CEmitterAny Closed")); Assert.IsTrue(log.Contains("CEmitterX Closed")); Assert.IsTrue(log.Contains("CEmitterY Closed")); Assert.IsTrue(log.Contains("CEmitterZ Closed")); Assert.IsTrue(log.Contains("CEmitterGen Closed")); Assert.IsTrue(log.Contains("DEmitterAny Closed")); Assert.IsTrue(log.Contains("DEmitterX Closed")); Assert.IsTrue(log.Contains("DEmitterY Closed")); Assert.IsTrue(log.Contains("DEmitterZ Closed")); Assert.IsTrue(log.Contains("DEmitterGen Closed")); Assert.IsTrue(log.Contains("EEmitterAny Closed")); Assert.IsTrue(log.Contains("EEmitterX Closed")); Assert.IsTrue(log.Contains("EEmitterY Closed")); Assert.IsTrue(log.Contains("EEmitterZ Closed")); Assert.IsTrue(log.Contains("EEmitterGen Closed")); // Emitters should have closed in A, B then (E | C | D) order Assert.IsTrue(log.IndexOf("BEmitterAny Closed") < log.IndexOf("DEmitterAny Closed")); Assert.IsTrue(log.IndexOf("BEmitterX Closed") < log.IndexOf("DEmitterX Closed")); Assert.IsTrue(log.IndexOf("BEmitterY Closed") < log.IndexOf("DEmitterY Closed")); Assert.IsTrue(log.IndexOf("BEmitterZ Closed") < log.IndexOf("DEmitterZ Closed")); Assert.IsTrue(log.IndexOf("BEmitterGen Closed") < log.IndexOf("DEmitterGen Closed")); Assert.IsTrue(log.IndexOf("BEmitterAny Closed") < log.IndexOf("CEmitterAny Closed")); Assert.IsTrue(log.IndexOf("BEmitterX Closed") < log.IndexOf("CEmitterX Closed")); Assert.IsTrue(log.IndexOf("BEmitterY Closed") < log.IndexOf("CEmitterY Closed")); Assert.IsTrue(log.IndexOf("BEmitterZ Closed") < log.IndexOf("CEmitterZ Closed")); Assert.IsTrue(log.IndexOf("BEmitterGen Closed") < log.IndexOf("CEmitterGen Closed")); Assert.IsTrue(log.IndexOf("BEmitterAny Closed") < log.IndexOf("EEmitterAny Closed")); Assert.IsTrue(log.IndexOf("BEmitterX Closed") < log.IndexOf("EEmitterX Closed")); Assert.IsTrue(log.IndexOf("BEmitterY Closed") < log.IndexOf("EEmitterY Closed")); Assert.IsTrue(log.IndexOf("BEmitterZ Closed") < log.IndexOf("EEmitterZ Closed")); Assert.IsTrue(log.IndexOf("BEmitterGen Closed") < log.IndexOf("EEmitterGen Closed")); Assert.IsTrue(log.IndexOf("AEmitterAny Closed") < log.IndexOf("BEmitterAny Closed")); Assert.IsTrue(log.IndexOf("AEmitterX Closed") < log.IndexOf("BEmitterX Closed")); Assert.IsTrue(log.IndexOf("AEmitterY Closed") < log.IndexOf("BEmitterY Closed")); Assert.IsTrue(log.IndexOf("AEmitterZ Closed") < log.IndexOf("BEmitterZ Closed")); Assert.IsTrue(log.IndexOf("AEmitterGen Closed") < log.IndexOf("BEmitterGen Closed")); // subscribed receivers should have been unsubscribed Assert.IsTrue(log.Contains("BReceiverX Unsubscribed")); Assert.IsTrue(log.Contains("DReceiverX Unsubscribed")); Assert.IsTrue(log.Contains("EReceiverX Unsubscribed")); Assert.IsTrue(log.Contains("EReceiverY Unsubscribed")); Assert.IsTrue(log.Contains("CReceiverX Unsubscribed")); // non-subscribed receivers should have done *nothing* Assert.IsFalse(log.Contains("AReceiverX Unsubscribed")); Assert.IsFalse(log.Contains("AReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("AReceiverZ Unsubscribed")); Assert.IsFalse(log.Contains("BReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("BReceiverZ Unsubscribed")); Assert.IsFalse(log.Contains("CReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("CReceiverZ Unsubscribed")); Assert.IsFalse(log.Contains("DReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("DReceiverZ Unsubscribed")); Assert.IsFalse(log.Contains("EReceiverZ Unsubscribed")); } [TestMethod] [Timeout(60000)] public void FinalizationTestWithUpstreamCycle() { // this exercises cycle detection apart from cycle back to origin (no infinite exploration) var log = new List<string>(); using (var p = Pipeline.Create()) { /* * =---= =---= =---= * | |--->| B |--->| C | * | A | =---= =---= * | | | * =---= | * ^ | * | | * +--------+ */ var c = new FinalizationTestComponent(p, "C", log); var b = new FinalizationTestComponent(p, "B", log); // finalized 1st, though constructed second var a = new FinalizationTestComponent(p, "A", log); a.Generator.PipeTo(b.ReceiverX); b.RelayFromX.PipeTo(a.ReceiverX); b.RelayFromX.PipeTo(c.ReceiverX); p.Run(); } // all emitters should have closed Assert.IsTrue(log.Contains("AEmitterAny Closed")); Assert.IsTrue(log.Contains("AEmitterX Closed")); Assert.IsTrue(log.Contains("AEmitterY Closed")); Assert.IsTrue(log.Contains("AEmitterZ Closed")); Assert.IsTrue(log.Contains("AEmitterGen Closed")); Assert.IsTrue(log.Contains("BEmitterAny Closed")); Assert.IsTrue(log.Contains("BEmitterX Closed")); Assert.IsTrue(log.Contains("BEmitterY Closed")); Assert.IsTrue(log.Contains("BEmitterZ Closed")); Assert.IsTrue(log.Contains("BEmitterGen Closed")); Assert.IsTrue(log.Contains("CEmitterAny Closed")); Assert.IsTrue(log.Contains("CEmitterX Closed")); Assert.IsTrue(log.Contains("CEmitterY Closed")); Assert.IsTrue(log.Contains("CEmitterZ Closed")); Assert.IsTrue(log.Contains("CEmitterGen Closed")); // Emitters should have closed in B then (A | C) order Assert.IsTrue(log.IndexOf("BEmitterAny Closed") < log.IndexOf("CEmitterAny Closed")); Assert.IsTrue(log.IndexOf("BEmitterX Closed") < log.IndexOf("CEmitterX Closed")); Assert.IsTrue(log.IndexOf("BEmitterY Closed") < log.IndexOf("CEmitterY Closed")); Assert.IsTrue(log.IndexOf("BEmitterZ Closed") < log.IndexOf("CEmitterZ Closed")); Assert.IsTrue(log.IndexOf("BEmitterGen Closed") < log.IndexOf("CEmitterGen Closed")); Assert.IsTrue(log.IndexOf("BEmitterAny Closed") < log.IndexOf("AEmitterAny Closed")); Assert.IsTrue(log.IndexOf("BEmitterX Closed") < log.IndexOf("AEmitterX Closed")); Assert.IsTrue(log.IndexOf("BEmitterY Closed") < log.IndexOf("AEmitterY Closed")); Assert.IsTrue(log.IndexOf("BEmitterZ Closed") < log.IndexOf("AEmitterZ Closed")); Assert.IsTrue(log.IndexOf("BEmitterGen Closed") < log.IndexOf("AEmitterGen Closed")); // subscribed receivers should have been unsubscribed Assert.IsTrue(log.Contains("AReceiverX Unsubscribed")); Assert.IsTrue(log.Contains("BReceiverX Unsubscribed")); Assert.IsTrue(log.Contains("CReceiverX Unsubscribed")); // non-subscribed receivers should have done *nothing* Assert.IsFalse(log.Contains("AReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("AReceiverZ Unsubscribed")); Assert.IsFalse(log.Contains("BReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("BReceiverZ Unsubscribed")); Assert.IsFalse(log.Contains("CReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("CReceiverZ Unsubscribed")); } [TestMethod] [Timeout(60000)] public void FinalizationTestWithMultiCycles() { var log = new List<string>(); using (var p = Pipeline.Create()) { /* * +--------+ * | | * v | * =---= =---= =---= * | A |--->| B |--->| C | * =---= =---= =---= * ^ | * | | * +--------+ */ var c = new FinalizationTestComponent(p, "C", log); var b = new FinalizationTestComponent(p, "B", log); var a = new FinalizationTestComponent(p, "A", log); // finalized 1st, though constructed last a.Generator.PipeTo(b.ReceiverX); b.RelayFromAny.PipeTo(c.ReceiverX); c.RelayFromX.PipeTo(b.ReceiverY); c.RelayFromX.PipeTo(b.ReceiverZ); p.Run(); } // all emitters should have closed Assert.IsTrue(log.Contains("AEmitterAny Closed")); Assert.IsTrue(log.Contains("AEmitterX Closed")); Assert.IsTrue(log.Contains("AEmitterY Closed")); Assert.IsTrue(log.Contains("AEmitterZ Closed")); Assert.IsTrue(log.Contains("AEmitterGen Closed")); Assert.IsTrue(log.Contains("BEmitterAny Closed")); Assert.IsTrue(log.Contains("BEmitterX Closed")); Assert.IsTrue(log.Contains("BEmitterY Closed")); Assert.IsTrue(log.Contains("BEmitterZ Closed")); Assert.IsTrue(log.Contains("BEmitterGen Closed")); Assert.IsTrue(log.Contains("CEmitterAny Closed")); Assert.IsTrue(log.Contains("CEmitterX Closed")); Assert.IsTrue(log.Contains("CEmitterY Closed")); Assert.IsTrue(log.Contains("CEmitterZ Closed")); Assert.IsTrue(log.Contains("CEmitterGen Closed")); // Should finalize A first, then either B or C (in reality construction order: C then B) Assert.IsTrue(log.IndexOf("AEmitterAny Closed") < log.IndexOf("BEmitterAny Closed")); Assert.IsTrue(log.IndexOf("AEmitterX Closed") < log.IndexOf("BEmitterX Closed")); Assert.IsTrue(log.IndexOf("AEmitterY Closed") < log.IndexOf("BEmitterY Closed")); Assert.IsTrue(log.IndexOf("AEmitterZ Closed") < log.IndexOf("BEmitterZ Closed")); Assert.IsTrue(log.IndexOf("AEmitterGen Closed") < log.IndexOf("BEmitterGen Closed")); Assert.IsTrue(log.IndexOf("AEmitterAny Closed") < log.IndexOf("CEmitterAny Closed")); Assert.IsTrue(log.IndexOf("AEmitterX Closed") < log.IndexOf("CEmitterX Closed")); Assert.IsTrue(log.IndexOf("AEmitterY Closed") < log.IndexOf("CEmitterY Closed")); Assert.IsTrue(log.IndexOf("AEmitterZ Closed") < log.IndexOf("CEmitterZ Closed")); Assert.IsTrue(log.IndexOf("AEmitterGen Closed") < log.IndexOf("CEmitterGen Closed")); // subscribed receivers should have been unsubscribed Assert.IsTrue(log.Contains("BReceiverX Unsubscribed")); Assert.IsTrue(log.Contains("BReceiverY Unsubscribed")); Assert.IsTrue(log.Contains("BReceiverZ Unsubscribed")); // non-subscribed receivers should have done *nothing* Assert.IsFalse(log.Contains("AReceiverX Unsubscribed")); Assert.IsFalse(log.Contains("AReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("AReceiverZ Unsubscribed")); Assert.IsFalse(log.Contains("CReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("CReceiverZ Unsubscribed")); } [TestMethod] [Timeout(60000)] public void FinalizationTestWithNestedCycles() { var log = new List<string>(); using (var p = Pipeline.Create()) { /* * +--------------------------+ * | | * v | * =---= =---= =---= =---= =---= * | A |--->| B |--->| C |--->| D |--->| E | * =---= =---= =---= =---= =---= * ^ | * | | * +--------+ */ var e = new FinalizationTestComponent(p, "E", log); var d = new FinalizationTestComponent(p, "D", log); var c = new FinalizationTestComponent(p, "C", log); var b = new FinalizationTestComponent(p, "B", log); var a = new FinalizationTestComponent(p, "A", log); a.Generator.PipeTo(b.ReceiverX); b.RelayFromAny.PipeTo(c.ReceiverX); c.RelayFromAny.PipeTo(d.ReceiverX); d.RelayFromX.PipeTo(e.ReceiverX); d.RelayFromX.PipeTo(c.ReceiverY); e.RelayFromX.PipeTo(b.ReceiverY); p.Run(); } // all emitters should have closed Assert.IsTrue(log.Contains("AEmitterAny Closed")); Assert.IsTrue(log.Contains("AEmitterX Closed")); Assert.IsTrue(log.Contains("AEmitterY Closed")); Assert.IsTrue(log.Contains("AEmitterZ Closed")); Assert.IsTrue(log.Contains("AEmitterGen Closed")); Assert.IsTrue(log.Contains("BEmitterAny Closed")); Assert.IsTrue(log.Contains("BEmitterX Closed")); Assert.IsTrue(log.Contains("BEmitterY Closed")); Assert.IsTrue(log.Contains("BEmitterZ Closed")); Assert.IsTrue(log.Contains("BEmitterGen Closed")); Assert.IsTrue(log.Contains("CEmitterAny Closed")); Assert.IsTrue(log.Contains("CEmitterX Closed")); Assert.IsTrue(log.Contains("CEmitterY Closed")); Assert.IsTrue(log.Contains("CEmitterZ Closed")); Assert.IsTrue(log.Contains("CEmitterGen Closed")); Assert.IsTrue(log.Contains("DEmitterAny Closed")); Assert.IsTrue(log.Contains("DEmitterX Closed")); Assert.IsTrue(log.Contains("DEmitterY Closed")); Assert.IsTrue(log.Contains("DEmitterZ Closed")); Assert.IsTrue(log.Contains("DEmitterGen Closed")); Assert.IsTrue(log.Contains("EEmitterAny Closed")); Assert.IsTrue(log.Contains("EEmitterX Closed")); Assert.IsTrue(log.Contains("EEmitterY Closed")); Assert.IsTrue(log.Contains("EEmitterZ Closed")); Assert.IsTrue(log.Contains("EEmitterGen Closed")); // Emitter A should have closed first Assert.IsTrue(log.IndexOf("AEmitterAny Closed") < log.IndexOf("BEmitterAny Closed")); Assert.IsTrue(log.IndexOf("AEmitterX Closed") < log.IndexOf("BEmitterX Closed")); Assert.IsTrue(log.IndexOf("AEmitterY Closed") < log.IndexOf("BEmitterY Closed")); Assert.IsTrue(log.IndexOf("AEmitterZ Closed") < log.IndexOf("BEmitterZ Closed")); Assert.IsTrue(log.IndexOf("AEmitterGen Closed") < log.IndexOf("BEmitterGen Closed")); Assert.IsTrue(log.IndexOf("AEmitterAny Closed") < log.IndexOf("CEmitterAny Closed")); Assert.IsTrue(log.IndexOf("AEmitterX Closed") < log.IndexOf("CEmitterX Closed")); Assert.IsTrue(log.IndexOf("AEmitterY Closed") < log.IndexOf("CEmitterY Closed")); Assert.IsTrue(log.IndexOf("AEmitterZ Closed") < log.IndexOf("CEmitterZ Closed")); Assert.IsTrue(log.IndexOf("AEmitterGen Closed") < log.IndexOf("CEmitterGen Closed")); Assert.IsTrue(log.IndexOf("AEmitterAny Closed") < log.IndexOf("DEmitterAny Closed")); Assert.IsTrue(log.IndexOf("AEmitterX Closed") < log.IndexOf("DEmitterX Closed")); Assert.IsTrue(log.IndexOf("AEmitterY Closed") < log.IndexOf("DEmitterY Closed")); Assert.IsTrue(log.IndexOf("AEmitterZ Closed") < log.IndexOf("DEmitterZ Closed")); Assert.IsTrue(log.IndexOf("AEmitterGen Closed") < log.IndexOf("DEmitterGen Closed")); Assert.IsTrue(log.IndexOf("AEmitterAny Closed") < log.IndexOf("EEmitterAny Closed")); Assert.IsTrue(log.IndexOf("AEmitterX Closed") < log.IndexOf("EEmitterX Closed")); Assert.IsTrue(log.IndexOf("AEmitterY Closed") < log.IndexOf("EEmitterY Closed")); Assert.IsTrue(log.IndexOf("AEmitterZ Closed") < log.IndexOf("EEmitterZ Closed")); Assert.IsTrue(log.IndexOf("AEmitterGen Closed") < log.IndexOf("EEmitterGen Closed")); // subscribed receivers should have been unsubscribed Assert.IsTrue(log.Contains("BReceiverX Unsubscribed")); Assert.IsTrue(log.Contains("BReceiverY Unsubscribed")); Assert.IsTrue(log.Contains("CReceiverY Unsubscribed")); Assert.IsTrue(log.Contains("EReceiverX Unsubscribed")); // non-subscribed receivers should have done *nothing* Assert.IsFalse(log.Contains("AReceiverX Unsubscribed")); Assert.IsFalse(log.Contains("AReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("AReceiverZ Unsubscribed")); Assert.IsFalse(log.Contains("BReceiverZ Unsubscribed")); Assert.IsFalse(log.Contains("CReceiverZ Unsubscribed")); Assert.IsFalse(log.Contains("DReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("DReceiverZ Unsubscribed")); Assert.IsFalse(log.Contains("EReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("EReceiverZ Unsubscribed")); } [TestMethod] [Timeout(60000)] public void FinalizationTestWithSeparatedCycles() { var log = new List<string>(); using (var p = Pipeline.Create()) { /* * +----------+ * | +------+ | * | | | | * | v | v * =---= =---= =---= =---= * | A |--->| B |--->| C |--->| D | * =---= =---= =---= =---= * ^ | ^ | * | | | | * +--------+ +--------+ */ var d = new FinalizationTestComponent(p, "D", log); var c = new FinalizationTestComponent(p, "C", log); var b = new FinalizationTestComponent(p, "B", log); var a = new FinalizationTestComponent(p, "A", log); a.Generator.PipeTo(b.ReceiverX); b.RelayFromX.PipeTo(a.ReceiverX); c.Generator.PipeTo(d.ReceiverX); d.RelayFromX.PipeTo(c.ReceiverX); b.Generator.PipeTo(c.ReceiverY); c.Generator.PipeTo(b.ReceiverY); b.RelayFromY.PipeTo(c.ReceiverZ); p.Run(); } // all emitters should have closed Assert.IsTrue(log.Contains("AEmitterAny Closed")); Assert.IsTrue(log.Contains("AEmitterX Closed")); Assert.IsTrue(log.Contains("AEmitterY Closed")); Assert.IsTrue(log.Contains("AEmitterZ Closed")); Assert.IsTrue(log.Contains("AEmitterGen Closed")); Assert.IsTrue(log.Contains("BEmitterAny Closed")); Assert.IsTrue(log.Contains("BEmitterX Closed")); Assert.IsTrue(log.Contains("BEmitterY Closed")); Assert.IsTrue(log.Contains("BEmitterZ Closed")); Assert.IsTrue(log.Contains("BEmitterGen Closed")); Assert.IsTrue(log.Contains("CEmitterAny Closed")); Assert.IsTrue(log.Contains("CEmitterX Closed")); Assert.IsTrue(log.Contains("CEmitterY Closed")); Assert.IsTrue(log.Contains("CEmitterZ Closed")); Assert.IsTrue(log.Contains("CEmitterGen Closed")); Assert.IsTrue(log.Contains("DEmitterAny Closed")); Assert.IsTrue(log.Contains("DEmitterX Closed")); Assert.IsTrue(log.Contains("DEmitterY Closed")); Assert.IsTrue(log.Contains("DEmitterZ Closed")); Assert.IsTrue(log.Contains("DEmitterGen Closed")); // Should finalize B first since it has the most active outputs, then A, then either C or D (in reality construction order: D then C) Assert.IsTrue(log.IndexOf("BEmitterAny Closed") < log.IndexOf("AEmitterAny Closed")); Assert.IsTrue(log.IndexOf("BEmitterX Closed") < log.IndexOf("AEmitterX Closed")); Assert.IsTrue(log.IndexOf("BEmitterY Closed") < log.IndexOf("AEmitterY Closed")); Assert.IsTrue(log.IndexOf("BEmitterZ Closed") < log.IndexOf("AEmitterZ Closed")); Assert.IsTrue(log.IndexOf("BEmitterGen Closed") < log.IndexOf("AEmitterGen Closed")); Assert.IsTrue(log.IndexOf("AEmitterAny Closed") < log.IndexOf("CEmitterAny Closed")); Assert.IsTrue(log.IndexOf("AEmitterX Closed") < log.IndexOf("CEmitterX Closed")); Assert.IsTrue(log.IndexOf("AEmitterY Closed") < log.IndexOf("CEmitterY Closed")); Assert.IsTrue(log.IndexOf("AEmitterZ Closed") < log.IndexOf("CEmitterZ Closed")); Assert.IsTrue(log.IndexOf("AEmitterGen Closed") < log.IndexOf("CEmitterGen Closed")); Assert.IsTrue(log.IndexOf("AEmitterAny Closed") < log.IndexOf("DEmitterAny Closed")); Assert.IsTrue(log.IndexOf("AEmitterX Closed") < log.IndexOf("DEmitterX Closed")); Assert.IsTrue(log.IndexOf("AEmitterY Closed") < log.IndexOf("DEmitterY Closed")); Assert.IsTrue(log.IndexOf("AEmitterZ Closed") < log.IndexOf("DEmitterZ Closed")); Assert.IsTrue(log.IndexOf("AEmitterGen Closed") < log.IndexOf("DEmitterGen Closed")); // subscribed receivers should have been unsubscribed Assert.IsTrue(log.Contains("AReceiverX Unsubscribed")); Assert.IsTrue(log.Contains("BReceiverX Unsubscribed")); Assert.IsTrue(log.Contains("BReceiverY Unsubscribed")); Assert.IsTrue(log.Contains("CReceiverX Unsubscribed")); Assert.IsTrue(log.Contains("CReceiverY Unsubscribed")); Assert.IsTrue(log.Contains("CReceiverZ Unsubscribed")); Assert.IsTrue(log.Contains("DReceiverX Unsubscribed")); // non-subscribed receivers should have done *nothing* Assert.IsFalse(log.Contains("AReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("AReceiverZ Unsubscribed")); Assert.IsFalse(log.Contains("BReceiverZ Unsubscribed")); Assert.IsFalse(log.Contains("DReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("DReceiverZ Unsubscribed")); } [TestMethod] [Timeout(60000)] public void FinalizationTestUnsubscribedHandler() { // Tests delayed posting of messages during finalization var log = new List<string>(); var collector = new List<(int data, Envelope env)>(); var sequence = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; using (var p = Pipeline.Create()) { // receiver collects received messages in a list but doesn't post them until it is unsubscribed var receiver = p.CreateReceiver<int>(collector, (d, e) => collector.Add((d, e)), "Receiver"); var emitter = p.CreateEmitter<int>(collector, "Emitter"); // on unsubscribe, post collected messages (with an artificial latency to slow them down) receiver.Unsubscribed += _ => collector.ForEach( m => { Thread.Sleep(33); emitter.Post(m.data, m.env.OriginatingTime); }); // log posted messages emitter.Do((d, e) => log.Add($"{e.OriginatingTime.TimeOfDay}:{d}")); // generate a sequence of inputs to the receiver var generator = Generators.Sequence(p, sequence, TimeSpan.FromMilliseconds(10)); generator.PipeTo(receiver); p.Run(); } // all collected values should have been posted on unsubscribe CollectionAssert.AreEqual(collector.Select(m => string.Format($"{m.env.OriginatingTime.TimeOfDay}:{m.data}")).ToArray(), log); } [TestMethod] [Timeout(60000)] public void FinalizationTestStopFromHandler() { // Tests stopping a subpipeline from an unsubscribed handler during finalization // run test for a range of max worker thread counts for (int maxThreads = Environment.ProcessorCount * 2; maxThreads > 0; maxThreads >>= 1) { maxThreads = 1; var collector = new List<int>(); var sequence = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; using (var p = Pipeline.Create(null, null, maxThreads)) // should not block even if there is only a single worker thread { var sub = Subpipeline.Create(p); var cIn = new Connector<int>(p, sub); var generator = Generators.Sequence(p, sequence, TimeSpan.FromTicks(1)); var receiver = sub.CreateReceiver<int>(collector, (d, e) => collector.Add(d), "Receiver"); generator.PipeTo(cIn.In); cIn.Out.PipeTo(receiver); cIn.In.Unsubscribed += time => sub.Stop(time); p.Run(); } CollectionAssert.AreEqual(sequence, collector); } } [TestMethod] [Timeout(60000)] public void FinalizationTestConcurrentShutdown() { // This tests shutting down a subpipeline via an unsubscribed handler on either inputs from A or B. // Either (or both) may trigger shutdown of the subpipeline, while the main pipeline is also in the // process of shutting down. var log = new List<string>(); using (var p = Pipeline.Create()) { /* * =---= * | A |-- ........................... * =---= \ . =---= . * -->| | =---= =---= . * . | C |--->| D |--->| E | . * -->| | =---= =---= . * =---= / . =---= . * | B |-- ........................... * =---= * * With C, D and E in subpipeline, which will be stopped upon unsubscribing either of its two input connectors */ var sub = new Subpipeline(p); var cInA = new Connector<int>(p, sub); var cInB = new Connector<int>(p, sub); var e = new FinalizationTestComponent(sub, "E", log); var d = new FinalizationTestComponent(sub, "D", log); var c = new FinalizationTestComponent(sub, "C", log); var b = new FinalizationTestComponent(p, "B", log); var a = new FinalizationTestComponent(p, "A", log); a.Generator.PipeTo(cInA.In); cInA.In.Unsubscribed += time => sub.Stop(time); cInA.Out.PipeTo(c.ReceiverX); c.RelayFromX.PipeTo(d.ReceiverX); d.RelayFromX.PipeTo(e.ReceiverX); b.Generator.PipeTo(cInB.In); cInB.In.Unsubscribed += time => sub.Stop(time); cInB.Out.PipeTo(c.ReceiverY); c.RelayFromY.PipeTo(d.ReceiverY); d.RelayFromY.PipeTo(e.ReceiverY); p.Run(); } // all emitters should have closed Assert.IsTrue(log.Contains("AEmitterAny Closed")); Assert.IsTrue(log.Contains("AEmitterX Closed")); Assert.IsTrue(log.Contains("AEmitterY Closed")); Assert.IsTrue(log.Contains("AEmitterZ Closed")); Assert.IsTrue(log.Contains("AEmitterGen Closed")); Assert.IsTrue(log.Contains("BEmitterAny Closed")); Assert.IsTrue(log.Contains("BEmitterX Closed")); Assert.IsTrue(log.Contains("BEmitterY Closed")); Assert.IsTrue(log.Contains("BEmitterZ Closed")); Assert.IsTrue(log.Contains("BEmitterGen Closed")); Assert.IsTrue(log.Contains("CEmitterAny Closed")); Assert.IsTrue(log.Contains("CEmitterX Closed")); Assert.IsTrue(log.Contains("CEmitterY Closed")); Assert.IsTrue(log.Contains("CEmitterZ Closed")); Assert.IsTrue(log.Contains("CEmitterGen Closed")); Assert.IsTrue(log.Contains("DEmitterAny Closed")); Assert.IsTrue(log.Contains("DEmitterX Closed")); Assert.IsTrue(log.Contains("DEmitterY Closed")); Assert.IsTrue(log.Contains("DEmitterZ Closed")); Assert.IsTrue(log.Contains("DEmitterGen Closed")); Assert.IsTrue(log.Contains("EEmitterAny Closed")); Assert.IsTrue(log.Contains("EEmitterX Closed")); Assert.IsTrue(log.Contains("EEmitterY Closed")); Assert.IsTrue(log.Contains("EEmitterZ Closed")); Assert.IsTrue(log.Contains("EEmitterGen Closed")); // Emitters should have closed in (A | B), then C to E order Assert.IsTrue(log.IndexOf("DEmitterAny Closed") < log.IndexOf("EEmitterAny Closed")); Assert.IsTrue(log.IndexOf("DEmitterX Closed") < log.IndexOf("EEmitterX Closed")); Assert.IsTrue(log.IndexOf("DEmitterY Closed") < log.IndexOf("EEmitterY Closed")); Assert.IsTrue(log.IndexOf("DEmitterZ Closed") < log.IndexOf("EEmitterZ Closed")); Assert.IsTrue(log.IndexOf("DEmitterGen Closed") < log.IndexOf("EEmitterGen Closed")); Assert.IsTrue(log.IndexOf("CEmitterAny Closed") < log.IndexOf("DEmitterAny Closed")); Assert.IsTrue(log.IndexOf("CEmitterX Closed") < log.IndexOf("DEmitterX Closed")); Assert.IsTrue(log.IndexOf("CEmitterY Closed") < log.IndexOf("DEmitterY Closed")); Assert.IsTrue(log.IndexOf("CEmitterZ Closed") < log.IndexOf("DEmitterZ Closed")); Assert.IsTrue(log.IndexOf("CEmitterGen Closed") < log.IndexOf("DEmitterGen Closed")); Assert.IsTrue(log.IndexOf("BEmitterAny Closed") < log.IndexOf("CEmitterAny Closed")); Assert.IsTrue(log.IndexOf("BEmitterX Closed") < log.IndexOf("CEmitterX Closed")); Assert.IsTrue(log.IndexOf("BEmitterY Closed") < log.IndexOf("CEmitterY Closed")); Assert.IsTrue(log.IndexOf("BEmitterZ Closed") < log.IndexOf("CEmitterZ Closed")); Assert.IsTrue(log.IndexOf("BEmitterGen Closed") < log.IndexOf("CEmitterGen Closed")); Assert.IsTrue(log.IndexOf("AEmitterAny Closed") < log.IndexOf("CEmitterAny Closed")); Assert.IsTrue(log.IndexOf("AEmitterX Closed") < log.IndexOf("CEmitterX Closed")); Assert.IsTrue(log.IndexOf("AEmitterY Closed") < log.IndexOf("CEmitterY Closed")); Assert.IsTrue(log.IndexOf("AEmitterZ Closed") < log.IndexOf("CEmitterZ Closed")); Assert.IsTrue(log.IndexOf("AEmitterGen Closed") < log.IndexOf("CEmitterGen Closed")); // subscribed receivers should have been unsubscribed Assert.IsTrue(log.Contains("CReceiverX Unsubscribed")); Assert.IsTrue(log.Contains("CReceiverY Unsubscribed")); Assert.IsTrue(log.Contains("DReceiverX Unsubscribed")); Assert.IsTrue(log.Contains("DReceiverY Unsubscribed")); Assert.IsTrue(log.Contains("EReceiverX Unsubscribed")); Assert.IsTrue(log.Contains("EReceiverY Unsubscribed")); // non-subscribed receivers should have done *nothing* Assert.IsFalse(log.Contains("AReceiverX Unsubscribed")); Assert.IsFalse(log.Contains("AReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("AReceiverZ Unsubscribed")); Assert.IsFalse(log.Contains("BReceiverX Unsubscribed")); Assert.IsFalse(log.Contains("BReceiverY Unsubscribed")); Assert.IsFalse(log.Contains("BReceiverZ Unsubscribed")); Assert.IsFalse(log.Contains("CReceiverZ Unsubscribed")); Assert.IsFalse(log.Contains("DReceiverZ Unsubscribed")); Assert.IsFalse(log.Contains("EReceiverZ Unsubscribed")); } [TestMethod] [Timeout(60000)] public void DiagnosticsTest() { var log = new List<string>(); PipelineDiagnostics graph = null; using (var p = Pipeline.Create(enableDiagnostics: true, diagnosticsConfiguration: new DiagnosticsConfiguration() { SamplingInterval = TimeSpan.FromMilliseconds(1) })) { /* * ......... * =---= . =---= . =---= * | A |--->| B |--->| D |---+ * =---= . =---= . =---= | * ^ ......... | * | | * +-----------------------+ */ var sub = new Subpipeline(p); var cIn = new Connector<int>(p, sub); var cOut = new Connector<int>(sub, p); var d = new FinalizationTestComponent(p, "C", log); var b = new FinalizationTestComponent(sub, "B", log); var a = new FinalizationTestComponent(p, "A", log); var timer = Generators.Range(p, 0, 100, TimeSpan.FromMilliseconds(10)); timer.PipeTo(cIn.In); cIn.Out.PipeTo(b.ReceiverX); b.RelayFromX.PipeTo(cOut.In); cOut.Out.PipeTo(d.ReceiverX); p.Diagnostics.Do(diag => graph = diag.DeepClone()); p.RunAsync(); while (graph == null) { Thread.Sleep(10); } } Assert.AreEqual(2, graph.GetPipelineCount()); // total graphs Assert.AreEqual(11, graph.GetPipelineElementCount()); // total pipeline elements Assert.AreEqual(21, graph.GetEmitterCount()); // total emitters (not necessarily connected) Assert.AreEqual(6, graph.GetAllEmitterDiagnostics().Where(e => e.Targets.Length != 0).Count()); // total _connected_ emitters Assert.AreEqual(13, graph.GetReceiverCount()); // total receivers (not necessarily connected) Assert.AreEqual(6, graph.GetAllReceiverDiagnostics().Where(r => r.Source != null).Count()); // total _connected_ receivers Assert.IsTrue(graph.GetAllReceiverDiagnostics().Select(r => r.AvgDeliveryQueueSize).Sum() > 0); // usually 50+ Assert.AreEqual(0, graph.GetDroppedMessageCount()); // total dropped Assert.AreEqual(0, graph.GetThrottledReceiverCount()); // total throttled receivers // example complex query: average latency at emitter across reactive components in leaf subpipelines var complex = graph.GetAllPipelineDiagnostics() .Where(p => p.SubpipelineDiagnostics.Length == 0) // leaf subpipelines .GetAllPipelineElements() .Where(e => e.Kind == PipelineElementKind.Reactive) // reactive components .GetAllReceiverDiagnostics() .Select(r => r.AvgMessageCreatedLatency); // average creation latency into each component's receivers Assert.AreEqual("default", graph.Name); Assert.IsTrue(graph.IsPipelineRunning); Assert.AreEqual(8, graph.PipelineElements.Length); Assert.AreEqual(1, graph.SubpipelineDiagnostics.Length); } [TestMethod] [Timeout(60000)] public void PipelineProgressTestInfiniteReplay() { var progress = new List<double>(); using (var pipeline = Pipeline.Create()) { // pipeline with infinite source Generators.Repeat(pipeline, 0, TimeSpan.FromMilliseconds(10)) .Select(x => x) .Do(x => { }); // increase report frequency for testing purposes pipeline.ProgressReportInterval = TimeSpan.FromMilliseconds(50); // run pipeline for a bit pipeline.RunAsync(null, new Progress<double>(x => progress.Add(x))); pipeline.WaitAll(200); // pipeline is still running and latest progress should reflect this Assert.IsTrue(pipeline.IsRunning); Assert.IsTrue(progress[progress.Count - 1] < 1.0); } // Progress<T>.Report() is invoked on the thread-pool since this is a non-UI app, // so wait for a bit to ensure that the last progress report action completes. Thread.Sleep(100); double lastValue = 0; foreach (double value in progress) { Console.WriteLine($"Progress: {value * 100}%"); // verify progress increases Assert.IsTrue(value >= lastValue); lastValue = value; } // verify final progress is 1.0 Assert.AreEqual(1.0, lastValue); } [TestMethod] [Timeout(60000)] public void PipelineProgressTestFiniteReplay() { var progress = new List<double>(); using (var pipeline = Pipeline.Create()) { // pipeline with infinite source Generators.Repeat(pipeline, 0, 50, TimeSpan.FromMilliseconds(10)) .Select(x => x) .Do(x => { }); // increase report frequency for testing purposes pipeline.ProgressReportInterval = TimeSpan.FromMilliseconds(50); // create a finite replay descriptor var replay = new ReplayDescriptor(DateTime.UtcNow, DateTime.UtcNow.AddMilliseconds(200)); // run and wait for pipeline to complete pipeline.RunAsync(replay, new Progress<double>(x => progress.Add(x))); pipeline.WaitAll(); } // Progress<T>.Report() is invoked on the thread-pool since this is a non-UI app, // so wait for a bit to ensure that the last progress report action completes. Thread.Sleep(100); double lastValue = 0; foreach (double value in progress) { Console.WriteLine($"Progress: {value * 100}%"); // verify progress increases Assert.IsTrue(value >= lastValue); lastValue = value; } // verify final progress is 1.0 Assert.AreEqual(1.0, lastValue); } [TestMethod] [Timeout(60000)] public void PipelineProgressTestSubpipeline() { var progress = new List<double>(); using (var pipeline = Pipeline.Create()) { // pipeline with finite source Generators.Repeat(pipeline, 0, 50, TimeSpan.FromMilliseconds(10)) .Select(x => x) .Do(x => { }); // subpipeline containing finite source var subpipeline = Subpipeline.Create(pipeline, "subpipeline"); Generators.Repeat(subpipeline, 0, 100, TimeSpan.FromMilliseconds(1)); // increase report frequency for testing purposes pipeline.ProgressReportInterval = TimeSpan.FromMilliseconds(50); // create a finite replay descriptor var replay = new ReplayDescriptor(DateTime.UtcNow, DateTime.UtcNow.AddMilliseconds(200)); // run and wait for pipeline to complete pipeline.RunAsync(replay, new Progress<double>(x => progress.Add(x))); // test adding a dynamic subpipeline after main pipeline has started var subpipeline2 = Subpipeline.Create(pipeline, "subpipeline2"); pipeline.WaitAll(); } // Progress<T>.Report() is invoked on the thread-pool since this is a non-UI app, // so wait for a bit to ensure that the last progress report action completes. Thread.Sleep(100); double lastValue = 0; foreach (double value in progress) { Console.WriteLine($"Progress: {value * 100}%"); // verify progress increases Assert.IsTrue(value >= lastValue); lastValue = value; } // verify final progress is 1.0 Assert.AreEqual(1.0, lastValue); } [TestMethod] [Timeout(60000)] public void SubpipelineWiringOnPipelineRun() { var results = new List<int>(); using (var pipeline = Pipeline.Create()) { var inputs = Generators.Range(pipeline, 0, 10, TimeSpan.FromTicks(1)); var subSquare = Subpipeline.Create(pipeline); var connSquare = subSquare.CreateInputConnectorFrom<int>(pipeline, "square"); var square = new Processor<int, int>(subSquare, (x, e, emitter) => emitter.Post(x * x, e.OriginatingTime)); var subAddOne = Subpipeline.Create(pipeline); // wiring between parent pipeline and first child subpipeline subSquare.PipelineRun += (_, __) => { connSquare.PipeTo(square); inputs.PipeTo(connSquare); }; // second child subpipeline creates grandchild subpipeline subAddOne.PipelineRun += (_, __) => { var subSubAddOne = Subpipeline.Create(subAddOne); // wiring from first child subpipeline to grandchild subpipeline, the back to parent pipeline subSubAddOne.PipelineRun += (s, e) => { var connAddOne = subSubAddOne.CreateInputConnectorFrom<int>(subSquare, "addOne"); var addOne = new Processor<int, int>(subSubAddOne, (x, env, emitter) => emitter.Post(x + 1, env.OriginatingTime)); var connResult = subSubAddOne.CreateOutputConnectorTo<int>(pipeline, "result"); square.PipeTo(connAddOne); connAddOne.PipeTo(addOne); addOne.PipeTo(connResult); // capture result stream connResult.Do(x => results.Add(x)); }; }; pipeline.Run(); } // verify result stream y = x^2 + 1 CollectionAssert.AreEqual(Enumerable.Range(0, 10).Select(x => (x * x) + 1).ToArray(), results); } [TestMethod] public void OnPipelineCompleted() { var output = new List<string>(); using (var p = Pipeline.Create()) { Generators.Return(p, 0); p.PipelineCompleted += (_, __) => { // slow handler to test that it completes execution before Pipeline.Run() returns Thread.Sleep(100); output.Add("Completed"); }; p.Run(); } output.Add("Disposed"); CollectionAssert.AreEqual(new[] { "Completed", "Disposed" }, output); } [TestMethod] [Timeout(60000)] public void NestedOnPipelineRun() { using (var pipeline = Pipeline.Create()) { Generators.Range(pipeline, 0, 10, TimeSpan.FromTicks(1)); var fired = false; pipeline.PipelineRun += (_, __) => { // additional handlers added *while* handling event must work pipeline.PipelineRun += (_, __) => { fired = true; }; }; pipeline.Run(); Assert.IsTrue(fired); } } [TestMethod] [Timeout(60000)] public void PipelineDispose() { var log = new List<string>(); var p = Pipeline.Create(); var c = new FinalizationTestComponent(p, "C", log); var b = new FinalizationTestComponent(p, "B", log); var a = new FinalizationTestComponent(p, "A", log); Assert.IsTrue(p.IsInitial); // Test dispose before starting the pipeline p.Dispose(); Assert.IsTrue(p.IsCompleted); Assert.IsTrue(log.Count == 0); log.Clear(); p = Pipeline.Create(); c = new FinalizationTestComponent(p, "C", log); b = new FinalizationTestComponent(p, "B", log); a = new FinalizationTestComponent(p, "A", log); p.RunAsync(); Assert.IsTrue(p.IsRunning); // Tests for resilience to double-dispose Parallel.For(0, 10, _ => p.Dispose()); Assert.IsTrue(p.IsCompleted); Assert.IsTrue(log.Count == 15); } private class FinalizationTestComponent : ISourceComponent { private readonly Pipeline pipeline; private readonly string name; private readonly List<string> log; private Action<DateTime> notifyCompletionTime; private int count = 0; private System.Timers.Timer timer; private long lastTicks = 0; public FinalizationTestComponent(Pipeline pipeline, string name, List<string> log) { this.pipeline = pipeline; this.name = name; this.log = log; this.RelayFromAny = pipeline.CreateEmitter<int>(this, $"{name}EmitterAny"); this.RelayFromAny.Closed += _ => this.Log($"{this.name}EmitterAny Closed"); this.RelayFromX = pipeline.CreateEmitter<int>(this, $"{name}EmitterX"); this.RelayFromX.Closed += _ => this.Log($"{this.name}EmitterX Closed"); this.RelayFromY = pipeline.CreateEmitter<int>(this, $"{name}EmitterY"); this.RelayFromY.Closed += _ => this.Log($"{this.name}EmitterY Closed"); this.RelayFromZ = pipeline.CreateEmitter<int>(this, $"{name}EmitterZ"); this.RelayFromZ.Closed += _ => this.Log($"{this.name}EmitterZ Closed"); this.Generator = pipeline.CreateEmitter<int>(this, $"{name}EmitterGen"); this.Generator.Closed += _ => this.Log($"{this.name}EmitterGen Closed"); this.ReceiverX = pipeline.CreateReceiver<int>(this, this.ReceiveX, $"{name}ReceiverX"); this.ReceiverX.Unsubscribed += _ => this.Log($"{this.name}ReceiverX Unsubscribed"); this.ReceiverY = pipeline.CreateReceiver<int>(this, this.ReceiveY, $"{name}ReceiverY"); this.ReceiverY.Unsubscribed += _ => this.Log($"{this.name}ReceiverY Unsubscribed"); this.ReceiverZ = pipeline.CreateReceiver<int>(this, this.ReceiveZ, $"{name}ReceiverZ"); this.ReceiverZ.Unsubscribed += _ => this.Log($"{this.name}ReceiverZ Unsubscribed"); } public Receiver<int> ReceiverX { get; private set; } // relays to EmitterX and W public Receiver<int> ReceiverY { get; private set; } // relays to EmitterY and W public Receiver<int> ReceiverZ { get; private set; } // relays to EmitterY and W public Emitter<int> RelayFromAny { get; private set; } // relays from ReceiverX or Y public Emitter<int> RelayFromX { get; private set; } // relays from ReceiverX public Emitter<int> RelayFromY { get; private set; } // relays from ReceiverY public Emitter<int> RelayFromZ { get; private set; } // relays from ReceiverY public Emitter<int> Generator { get; private set; } // emits at 10ms intervals public void Start(Action<DateTime> notifyCompletionTime) { this.notifyCompletionTime = notifyCompletionTime; if (this.Generator.HasSubscribers) { this.timer = new System.Timers.Timer(1) { Enabled = true }; this.timer.Elapsed += this.Elapsed; } else { notifyCompletionTime(DateTime.MaxValue); } } public void Stop(DateTime finalOriginatingTime, Action notifyCompleted) { if (this.timer != null) { this.timer.Elapsed -= this.Elapsed; } notifyCompleted(); } public override string ToString() { return this.name; // useful for debug logging } private void Elapsed(object sender, System.Timers.ElapsedEventArgs e) { lock (this) { if (this.Generator.HasSubscribers && this.count < 3) { this.Generator.Post(this.count++, this.pipeline.GetCurrentTime()); } else { this.timer.Enabled = false; this.notifyCompletionTime(this.pipeline.GetCurrentTime()); } } } private void EmitFromEach(int m, DateTime time) { Thread.Sleep(1); this.lastTicks = Math.Max(time.Ticks + TimeSpan.TicksPerMillisecond, this.lastTicks + TimeSpan.TicksPerMillisecond); this.RelayFromAny.Post(m, new DateTime(this.lastTicks)); } private void ReceiveX(int m, Envelope e) { this.Log($"{this.name}ReceiveX {m}"); this.EmitFromEach(m, e.OriginatingTime); this.RelayFromX.Post(m, e.OriginatingTime); } private void ReceiveY(int m, Envelope e) { this.Log($"{this.name}ReceiveY {m}"); this.EmitFromEach(m, e.OriginatingTime); this.RelayFromY.Post(m, e.OriginatingTime); } private void ReceiveZ(int m, Envelope e) { this.Log($"{this.name}ReceiveZ {m}"); this.EmitFromEach(m, e.OriginatingTime); this.RelayFromZ.Post(m, e.OriginatingTime); } private void Log(string entry) { lock (this.log) { this.log.Add(entry); } } } } }
48.612691
179
0.544756
[ "MIT" ]
Microsoft/psi
Sources/Runtime/Test.Psi/PipelineTest.cs
117,985
C#
using System.Net; using System.Net.Http; namespace Commons.Extensions { public static class HttpStatusCodeExtensions { public static bool IsSuccessStatusCode(this HttpStatusCode statusCode) => (int) statusCode is >= 200 and < 300; public static void EnsureSuccessStatusCode(this HttpStatusCode statusCode) { if (!IsSuccessStatusCode(statusCode)) { throw new HttpRequestException($"{statusCode} is not a success status code"); } } } }
28.578947
93
0.635359
[ "MIT" ]
ChaucerLib/Commons
Commons/Extensions/HttpStatusCodeExtensions.cs
543
C#
/* MIT License Copyright (c) 2011-2019 Markus Wendt (http://www.dodoni-project.net) All rights reserved. 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. Please see http://www.dodoni-project.net/ for more information concerning the Dodoni.net project. */ using System; using NUnit.Framework; namespace Dodoni.MathLibrary.NumericalIntegrators { /// <summary>Serves as unit test class for <see cref="GaussTschebyscheffIntegrator"/>. /// </summary> public class GaussTschebyscheffIntegratorTests { /// <summary>A test function for the calculation of the estimated integration value w.r.t. a specific test case. /// </summary> /// <param name="initialOrder">The initial order of the Gauss-Tschebyscheff approach, i.e. the order in the first iteration step.</param> /// <param name="orderStepSize">The step size of the order, i.e. in each iteration step the order will be increased by the specified number.</param> [Test, Combinatorial] public void GetValueWithState_OneOverWeightfunction_BenchmarkResult( [Values(10, 25, 50, 100)] int initialOrder, [Values(5, 10, 25)] int orderStepSize) { var gaussTschebyscheffIntegrator = new GaussTschebyscheffIntegrator(initialOrder, orderStepSize); var numericalIntegrator = gaussTschebyscheffIntegrator.Create(); double lowerBound = -1.0; double upperBound = 1.0; Assert.That(numericalIntegrator.TrySetBounds(lowerBound, upperBound) == true, String.Format("1-dimensional Integrator {0} does not support individual lower/upper bounds", numericalIntegrator.Factory.Name.String)); numericalIntegrator.FunctionToIntegrate = x => Math.Sqrt(1.0 - x * x); // for Tschebyscheff Integrator, the integrator is 1 in this case! double expected = upperBound - lowerBound; double actual; OneDimNumericalIntegrator.State state = numericalIntegrator.GetValue(out actual); Assert.That(actual, Is.EqualTo(expected).Within(1E-4), String.Format("1-dimensional integrator {0}; state: {1}.", numericalIntegrator.Factory.Name, state.ToString())); } /// <summary>A test function for the calculation of the estimated integration value w.r.t. a specific test case. /// </summary> /// <param name="initialOrder">The initial order of the Gauss-Tschebyscheff approach, i.e. the order in the first iteration step.</param> /// <param name="orderStepSize">The step size of the order, i.e. in each iteration step the order will be increased by the specified number.</param> /// <param name="lowerBound">The lower integration bound.</param> /// <param name="upperBound">The upper integration bound.</param> [Test, Combinatorial] public void GetValueWithState_OneOverWeightfunction_BenchmarkResult( [Values(10, 25, 50, 100)] int initialOrder, [Values(5, 10, 25)] int orderStepSize, [Values(-1.0, 2.5)] double lowerBound, [Values(1.0, 6.4)] double upperBound) { var gaussTschebyscheffIntegrator = new GaussTschebyscheffIntegrator(initialOrder, orderStepSize); var numericalIntegrator = gaussTschebyscheffIntegrator.Create(); Assert.That(numericalIntegrator.TrySetBounds(lowerBound, upperBound) == true, String.Format("1-dimensional Integrator {0} does not support individual lower/upper bounds", numericalIntegrator.Factory.Name.String)); numericalIntegrator.FunctionToIntegrate = x => 1.0 / numericalIntegrator.WeightFunction.GetValue(x); double expected = upperBound - lowerBound; double actual; OneDimNumericalIntegrator.State state = numericalIntegrator.GetValue(out actual); Assert.That(actual, Is.EqualTo(expected).Within(1E-4), String.Format("1-dimensional integrator {0}; state: {1}.", numericalIntegrator.Factory.Name, state.ToString())); } /// <summary>A test function for the calculation of the estimated integration value w.r.t. a specific test case. /// </summary> /// <param name="initialOrder">The initial order of the Gauss-Tschebyscheff approach, i.e. the order in the first iteration step.</param> /// <param name="orderStepSize">The step size of the order, i.e. in each iteration step the order will be increased by the specified number.</param> [Test, Combinatorial] public void GetValue_OneOverWeightfunction_BenchmarkResult( [Values(10, 25, 50, 100)] int initialOrder, [Values(5, 10, 25)] int orderStepSize) { var gaussTschebyscheffIntegrator = new GaussTschebyscheffIntegrator(initialOrder, orderStepSize); var numericalIntegrator = gaussTschebyscheffIntegrator.Create(); double lowerBound = -1.0; double upperBound = 1.0; Assert.That(numericalIntegrator.TrySetBounds(lowerBound, upperBound) == true, String.Format("1-dimensional Integrator {0} does not support individual lower/upper bounds", numericalIntegrator.Factory.Name.String)); numericalIntegrator.FunctionToIntegrate = x => Math.Sqrt(1.0 - x * x); // for Tschebyscheff Integrator, the integrator is 1 in this case! double expected = upperBound - lowerBound; double actual = numericalIntegrator.GetValue(); Assert.That(actual, Is.EqualTo(expected).Within(1E-4), String.Format("1-dimensional integrator {0}.", numericalIntegrator.Factory.Name)); } /// <summary>A test function for the calculation of the estimated integration value w.r.t. a specific test case. /// </summary> /// <param name="initialOrder">The initial order of the Gauss-Tschebyscheff approach, i.e. the order in the first iteration step.</param> /// <param name="orderStepSize">The step size of the order, i.e. in each iteration step the order will be increased by the specified number.</param> /// <param name="lowerBound">The lower integration bound.</param> /// <param name="upperBound">The upper integration bound.</param> [Test, Combinatorial] public void GetValue_OneOverWeightfunction_BenchmarkResult( [Values(10, 25, 50, 100)] int initialOrder, [Values(5, 10, 25)] int orderStepSize, [Values(-1.0, 2.5)] double lowerBound, [Values(1.0, 6.4)] double upperBound) { var gaussTschebyscheffIntegrator = new GaussTschebyscheffIntegrator(initialOrder, orderStepSize); var numericalIntegrator = gaussTschebyscheffIntegrator.Create(); Assert.That(numericalIntegrator.TrySetBounds(lowerBound, upperBound) == true, String.Format("1-dimensional Integrator {0} does not support individual lower/upper bounds", numericalIntegrator.Factory.Name.String)); numericalIntegrator.FunctionToIntegrate = x => 1.0/numericalIntegrator.WeightFunction.GetValue(x); double expected = upperBound - lowerBound; double actual = numericalIntegrator.GetValue(); Assert.That(actual, Is.EqualTo(expected).Within(1E-4), String.Format("1-dimensional integrator {0}.", numericalIntegrator.Factory.Name)); } /// <summary>A test function for the calculation of the estimated integration value w.r.t. a specific test case. /// </summary> /// <param name="initialOrder">The initial order of the Gauss-Tschebyscheff approach, i.e. the order in the first iteration step.</param> /// <param name="orderStepSize">The step size of the order, i.e. in each iteration step the order will be increased by the specified number.</param> [Test, Combinatorial] public void GetValueWithState_ThreeTimesXToThePowerOf3_BenchmarkResult( [Values(10, 25, 50, 100)] int initialOrder, [Values(5, 10, 25)] int orderStepSize) { var gaussTschebyscheffIntegrator = new GaussTschebyscheffIntegrator(initialOrder, orderStepSize); var numericalIntegrator = gaussTschebyscheffIntegrator.Create(); double lowerBound = -1.0; double upperBound = 1.0; Assert.That(numericalIntegrator.TrySetBounds(lowerBound, upperBound) == true, String.Format("1-dimensional Integrator {0} does not support individual lower/upper bounds", numericalIntegrator.Factory.Name.String)); numericalIntegrator.FunctionToIntegrate = x => 3.0 * x * x * x; double a = 1.0; // see §21.5.25 in "Taschenbuch der Mathematik", Bronstein, Semendjajew, Musiol, Mühlig, 1995 double expected = 3.0 / 5.0 * Math.Sqrt(Math.Pow(a * a - upperBound * upperBound, 5)) - a * a * Math.Sqrt(Math.Pow(a * a - upperBound * upperBound, 3)) - 3.0 / 5.0 * Math.Sqrt(Math.Pow(a * a - lowerBound * lowerBound, 5)) - a * a * Math.Sqrt(Math.Pow(a * a - lowerBound * lowerBound, 3)); double actual; OneDimNumericalIntegrator.State state = numericalIntegrator.GetValue(out actual); Assert.That(actual, Is.EqualTo(expected).Within(1E-6), String.Format("1-dimensional integrator {0}; state: {1}.", numericalIntegrator.Factory.Name, state.ToString())); } /// <summary>A test function for the calculation of the estimated integration value w.r.t. a specific test case. /// </summary> /// <param name="initialOrder">The initial order of the Gauss-Tschebyscheff approach, i.e. the order in the first iteration step.</param> /// <param name="orderStepSize">The step size of the order, i.e. in each iteration step the order will be increased by the specified number.</param> [Test, Combinatorial] public void GetValue_ThreeTimesXToThePowerOf3_BenchmarkResult( [Values(10, 25, 50, 100)] int initialOrder, [Values(5, 10, 25)] int orderStepSize) { var gaussTschebyscheffIntegrator = new GaussTschebyscheffIntegrator(initialOrder, orderStepSize); var numericalIntegrator = gaussTschebyscheffIntegrator.Create(); double lowerBound = -1.0; double upperBound = 1.0; Assert.That(numericalIntegrator.TrySetBounds(lowerBound, upperBound) == true, String.Format("1-dimensional Integrator {0} does not support individual lower/upper bounds", numericalIntegrator.Factory.Name.String)); numericalIntegrator.FunctionToIntegrate = x => 3.0 * x * x * x; double a = 1.0; // see §21.5.25 in "Taschenbuch der Mathematik", Bronstein, Semendjajew, Musiol, Mühlig, 1995 double expected = 3.0 / 5.0 * Math.Sqrt(Math.Pow(a * a - upperBound * upperBound, 5)) - a * a * Math.Sqrt(Math.Pow(a * a - upperBound * upperBound, 3)) - 3.0 / 5.0 * Math.Sqrt(Math.Pow(a * a - lowerBound * lowerBound, 5)) - a * a * Math.Sqrt(Math.Pow(a * a - lowerBound * lowerBound, 3)); double actual = numericalIntegrator.GetValue(); Assert.That(actual, Is.EqualTo(expected).Within(1E-6), String.Format("1-dimensional integrator {0}.", numericalIntegrator.Factory.Name)); } } }
58.526066
300
0.679002
[ "MIT" ]
dodoni/dodoni.net
CommonMathLibrary.Tests.Unit/NumericalIntegrators/GaussTschebyscheffIntegratorTests.cs
12,355
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("OptimizedQualityCodeLook")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("OptimizedQualityCodeLook")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e93fd59e-c15d-4729-9ed4-272ef514cc1d")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.405405
84
0.749472
[ "MIT" ]
martinmihov/Programming-Fundamentals
Methods. Debugging and Troubleshooting Code/OptimizedQualityCodeLook/Properties/AssemblyInfo.cs
1,424
C#
using System; using System.Collections.Generic; namespace _06.MathPotato { class MathPotato { static void Main(string[] args) { var input = Console.ReadLine(); var queue = new Queue<string>(input.Split(' ')); var number = int.Parse(Console.ReadLine()); int cycle = 1; while (queue.Count > 1) { for (int i = 0; i < number - 1; i++) { string reminder = queue.Dequeue(); queue.Enqueue(reminder); } if (PrimeTool.IsPrime(cycle)) { Console.WriteLine($"Prime {queue.Peek()}"); } else { Console.WriteLine($"Removed {queue.Dequeue()}"); } cycle++; } Console.WriteLine($"Last is {queue.Dequeue()}"); } public static class PrimeTool { public static bool IsPrime(int candidate) { if ((candidate & 1) == 0) { if (candidate == 2) { return true; } else { return false; } } for (int i = 3; (i * i) <= candidate; i += 2) { if ((candidate % i) == 0) { return false; } } return candidate != 1; } } } }
26.746032
68
0.34362
[ "MIT" ]
vpaleshnikov/SoftUni-C-FundamentalsModule
C#Advanced/01.StacksAndQueues-Lab/06.MathPotato/MathPotato.cs
1,687
C#
using System; using System.Text.RegularExpressions; namespace ValidationPilotServices.DataTypes { public class Identifier : BaseValidator { public Identifier() { this.pattern = new Regex(@"(\w|\-)+",RegexOptions.Compiled); } public Identifier(int minLength, int maxLength) { this.pattern = new Regex(@"(\w|\-){" + $"1,{maxLength}" + "}",RegexOptions.Compiled); } } }
23.894737
97
0.5837
[ "Apache-2.0" ]
Ministerstvo-financi/hazard-komunikacni-rozhrani
csv-validator/PackageValidation/ValidationServices/DataTypes/Identifier.cs
456
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameManager : MonoBehaviour { public EnemyMove enemy; public EnemyData[] levelData; [Range(1,5)] public int level; void Awake() { if (level > levelData.Length) { level = levelData.Length; } enemy.data = levelData[level - 1]; } }
17.304348
42
0.60804
[ "MIT" ]
zulaldogan/saving-game-data
SoExample/Assets/Script/GameManager.cs
400
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.Network.V20190601.Inputs { /// <summary> /// ExpressRouteLink child resource definition. /// </summary> public sealed class ExpressRouteLinkArgs : Pulumi.ResourceArgs { /// <summary> /// Administrative state of the physical port. /// </summary> [Input("adminState")] public InputUnion<string, Pulumi.AzureNative.Network.V20190601.ExpressRouteLinkAdminState>? AdminState { get; set; } /// <summary> /// Resource ID. /// </summary> [Input("id")] public Input<string>? Id { get; set; } /// <summary> /// Name of child port resource that is unique among child port resources of the parent. /// </summary> [Input("name")] public Input<string>? Name { get; set; } public ExpressRouteLinkArgs() { } } }
29.170732
124
0.622074
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Network/V20190601/Inputs/ExpressRouteLinkArgs.cs
1,196
C#
using System; using Csla; using Invoices.DataAccess; namespace Invoices.DataAccess.Sql { public partial class ProductTypeDynaCollDal { } }
14.727273
48
0.697531
[ "MIT" ]
CslaGenFork/CslaGenFork
trunk/CoverageTest/Invoices-CS-DAL-DTO-INT64/Invoices.DataAccess.Sql/ProductTypeDynaCollDal.cs
162
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.Buffers.Binary; using System.Collections.Concurrent; using System.Diagnostics; namespace System.Security.Cryptography { internal sealed class RsaPaddingProcessor { // DigestInfo header values taken from https://tools.ietf.org/html/rfc3447#section-9.2, Note 1. private static readonly byte[] s_digestInfoMD5 = { 0x30, 0x20, 0x30, 0x0C, 0x06, 0x08, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x02, 0x05, 0x05, 0x00, 0x04, 0x10, }; private static readonly byte[] s_digestInfoSha1 = { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x0E, 0x03, 0x02, 0x1A, 0x05, 0x00, 0x04, 0x14, }; private static readonly byte[] s_digestInfoSha256 = { 0x30, 0x31, 0x30, 0x0D, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20, }; private static readonly byte[] s_digestInfoSha384 = { 0x30, 0x41, 0x30, 0x0D, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, 0x04, 0x30, }; private static readonly byte[] s_digestInfoSha512 = { 0x30, 0x51, 0x30, 0x0D, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, 0x00, 0x04, 0x40, }; private static readonly ConcurrentDictionary<HashAlgorithmName, RsaPaddingProcessor> s_lookup = new ConcurrentDictionary<HashAlgorithmName, RsaPaddingProcessor>(); private readonly HashAlgorithmName _hashAlgorithmName; private readonly int _hLen; private readonly ReadOnlyMemory<byte> _digestInfoPrefix; private RsaPaddingProcessor( HashAlgorithmName hashAlgorithmName, int hLen, ReadOnlyMemory<byte> digestInfoPrefix) { _hashAlgorithmName = hashAlgorithmName; _hLen = hLen; _digestInfoPrefix = digestInfoPrefix; } internal static int BytesRequiredForBitCount(int keySizeInBits) { return (int)(((uint)keySizeInBits + 7) / 8); } private static ReadOnlySpan<byte> EightZeros => new byte[8]; // rely on C# compiler optimization to eliminate allocation internal int HashLength => _hLen; internal static RsaPaddingProcessor OpenProcessor(HashAlgorithmName hashAlgorithmName) { return s_lookup.GetOrAdd( hashAlgorithmName, static hashAlgorithmName => { ReadOnlyMemory<byte> digestInfoPrefix; int digestLength; if (hashAlgorithmName == HashAlgorithmName.MD5) { digestInfoPrefix = s_digestInfoMD5; #pragma warning disable CA1416 // Unsupported on Browser. We just want the const here. digestLength = MD5.HashSizeInBytes; #pragma warning restore CA1416 } else if (hashAlgorithmName == HashAlgorithmName.SHA1) { digestInfoPrefix = s_digestInfoSha1; digestLength = SHA1.HashSizeInBytes; } else if (hashAlgorithmName == HashAlgorithmName.SHA256) { digestInfoPrefix = s_digestInfoSha256; digestLength = SHA256.HashSizeInBytes; } else if (hashAlgorithmName == HashAlgorithmName.SHA384) { digestInfoPrefix = s_digestInfoSha384; digestLength = SHA384.HashSizeInBytes; } else if (hashAlgorithmName == HashAlgorithmName.SHA512) { digestInfoPrefix = s_digestInfoSha512; digestLength = SHA512.HashSizeInBytes; } else { Debug.Fail("Unknown digest algorithm"); throw new CryptographicException(); } return new RsaPaddingProcessor(hashAlgorithmName, digestLength, digestInfoPrefix); }); } internal static void PadPkcs1Encryption( ReadOnlySpan<byte> source, Span<byte> destination) { // https://tools.ietf.org/html/rfc3447#section-7.2.1 int mLen = source.Length; int k = destination.Length; // 1. If mLen > k - 11, fail if (mLen > k - 11) { throw new CryptographicException(SR.Cryptography_KeyTooSmall); } // 2(b). EM is composed of 00 02 [PS] 00 [M] Span<byte> mInEM = destination.Slice(destination.Length - source.Length); Span<byte> ps = destination.Slice(2, destination.Length - source.Length - 3); destination[0] = 0; destination[1] = 2; destination[ps.Length + 2] = 0; // 2(a). Fill PS with random data from a CSPRNG, but no zero-values. FillNonZeroBytes(ps); source.CopyTo(mInEM); } internal void PadPkcs1Signature( ReadOnlySpan<byte> source, Span<byte> destination) { // https://tools.ietf.org/html/rfc3447#section-9.2 // 1. H = Hash(M) // Done by the caller. // 2. Encode the DigestInfo value ReadOnlySpan<byte> digestInfoPrefix = _digestInfoPrefix.Span; int expectedLength = digestInfoPrefix[^1]; if (source.Length != expectedLength) { throw new CryptographicException(SR.Cryptography_SignHash_WrongSize); } int tLen = digestInfoPrefix.Length + expectedLength; // 3. If emLen < tLen + 11, fail if (destination.Length - 11 < tLen) { throw new CryptographicException(SR.Cryptography_KeyTooSmall); } // 4. Generate emLen - tLen - 3 bytes of 0xFF as "PS" int paddingLength = destination.Length - tLen - 3; // 5. EM = 0x00 || 0x01 || PS || 0x00 || T destination[0] = 0; destination[1] = 1; destination.Slice(2, paddingLength).Fill(0xFF); destination[paddingLength + 2] = 0; digestInfoPrefix.CopyTo(destination.Slice(paddingLength + 3)); source.CopyTo(destination.Slice(paddingLength + 3 + digestInfoPrefix.Length)); } internal void PadOaep( ReadOnlySpan<byte> source, Span<byte> destination) { // https://tools.ietf.org/html/rfc3447#section-7.1.1 byte[]? dbMask = null; Span<byte> dbMaskSpan = Span<byte>.Empty; try { // Since the biggest known _hLen is 512/8 (64) and destination.Length is 0 or more, // this shouldn't underflow without something having severely gone wrong. int maxInput = checked(destination.Length - _hLen - _hLen - 2); // 1(a) does not apply, we do not allow custom label values. // 1(b) if (source.Length > maxInput) { throw new CryptographicException( SR.Format(SR.Cryptography_Encryption_MessageTooLong, maxInput)); } // The final message (step 2(i)) will be // 0x00 || maskedSeed (hLen long) || maskedDB (rest of the buffer) Span<byte> seed = destination.Slice(1, _hLen); Span<byte> db = destination.Slice(1 + _hLen); using (IncrementalHash hasher = IncrementalHash.CreateHash(_hashAlgorithmName)) { // DB = lHash || PS || 0x01 || M Span<byte> lHash = db.Slice(0, _hLen); Span<byte> mDest = db.Slice(db.Length - source.Length); Span<byte> ps = db.Slice(_hLen, db.Length - _hLen - 1 - mDest.Length); Span<byte> psEnd = db.Slice(_hLen + ps.Length, 1); // 2(a) lHash = Hash(L), where L is the empty string. if (!hasher.TryGetHashAndReset(lHash, out int hLen2) || hLen2 != _hLen) { Debug.Fail("TryGetHashAndReset failed with exact-size destination"); throw new CryptographicException(); } // 2(b) generate a padding string of all zeros equal to the amount of unused space. ps.Clear(); // 2(c) psEnd[0] = 0x01; // still 2(c) source.CopyTo(mDest); // 2(d) RandomNumberGenerator.Fill(seed); // 2(e) dbMask = CryptoPool.Rent(db.Length); dbMaskSpan = new Span<byte>(dbMask, 0, db.Length); Mgf1(hasher, seed, dbMaskSpan); // 2(f) Xor(db, dbMaskSpan); // 2(g) Span<byte> seedMask = stackalloc byte[_hLen]; Mgf1(hasher, db, seedMask); // 2(h) Xor(seed, seedMask); // 2(i) destination[0] = 0; } } catch (Exception e) when (!(e is CryptographicException)) { Debug.Fail("Bad exception produced from OAEP padding: " + e); throw new CryptographicException(); } finally { if (dbMask != null) { CryptographicOperations.ZeroMemory(dbMaskSpan); CryptoPool.Return(dbMask, clearSize: 0); } } } internal bool DepadOaep( ReadOnlySpan<byte> source, Span<byte> destination, out int bytesWritten) { // https://tools.ietf.org/html/rfc3447#section-7.1.2 using (IncrementalHash hasher = IncrementalHash.CreateHash(_hashAlgorithmName)) { Span<byte> lHash = stackalloc byte[_hLen]; if (!hasher.TryGetHashAndReset(lHash, out int hLen2) || hLen2 != _hLen) { Debug.Fail("TryGetHashAndReset failed with exact-size destination"); throw new CryptographicException(); } int y = source[0]; ReadOnlySpan<byte> maskedSeed = source.Slice(1, _hLen); ReadOnlySpan<byte> maskedDB = source.Slice(1 + _hLen); Span<byte> seed = stackalloc byte[_hLen]; // seedMask = MGF(maskedDB, hLen) Mgf1(hasher, maskedDB, seed); // seed = seedMask XOR maskedSeed Xor(seed, maskedSeed); byte[] tmp = CryptoPool.Rent(source.Length); try { Span<byte> dbMask = new Span<byte>(tmp, 0, maskedDB.Length); // dbMask = MGF(seed, k - hLen - 1) Mgf1(hasher, seed, dbMask); // DB = dbMask XOR maskedDB Xor(dbMask, maskedDB); ReadOnlySpan<byte> lHashPrime = dbMask.Slice(0, _hLen); int separatorPos = int.MaxValue; for (int i = dbMask.Length - 1; i >= _hLen; i--) { // if dbMask[i] is 1, val is 0. otherwise val is [01,FF] byte dbMinus1 = (byte)(dbMask[i] - 1); int val = dbMinus1; // if val is 0: FFFFFFFF & FFFFFFFF => FFFFFFFF // if val is any other byte value, val-1 will be in the range 00000000 to 000000FE, // and so the high bit will not be set. val = (~val & (val - 1)) >> 31; // if val is 0: separator = (0 & i) | (~0 & separator) => separator // else: separator = (~0 & i) | (0 & separator) => i // // Net result: non-branching "if (dbMask[i] == 1) separatorPos = i;" separatorPos = (val & i) | (~val & separatorPos); } bool lHashMatches = CryptographicOperations.FixedTimeEquals(lHash, lHashPrime); bool yIsZero = y == 0; bool separatorMadeSense = separatorPos < dbMask.Length; // This intentionally uses non-short-circuiting operations to hide the timing // differential between the three failure cases bool shouldContinue = lHashMatches & yIsZero & separatorMadeSense; if (!shouldContinue) { throw new CryptographicException(SR.Cryptography_OAEP_Decryption_Failed); } Span<byte> message = dbMask.Slice(separatorPos + 1); if (message.Length <= destination.Length) { message.CopyTo(destination); bytesWritten = message.Length; return true; } else { bytesWritten = 0; return false; } } finally { CryptoPool.Return(tmp, source.Length); } } } internal void EncodePss(ReadOnlySpan<byte> mHash, Span<byte> destination, int keySize) { // https://tools.ietf.org/html/rfc3447#section-9.1.1 int emBits = keySize - 1; int emLen = BytesRequiredForBitCount(emBits); if (mHash.Length != _hLen) { throw new CryptographicException(SR.Cryptography_SignHash_WrongSize); } // In this implementation, sLen is restricted to the length of the input hash. int sLen = _hLen; // 3. if emLen < hLen + sLen + 2, encoding error. // // sLen = hLen in this implementation. if (emLen < 2 + _hLen + sLen) { throw new CryptographicException(SR.Cryptography_KeyTooSmall); } // Set any leading bytes to zero, since that will be required for the pending // RSA operation. destination.Slice(0, destination.Length - emLen).Clear(); // 12. Let EM = maskedDB || H || 0xbc (H has length hLen) Span<byte> em = destination.Slice(destination.Length - emLen, emLen); int dbLen = emLen - _hLen - 1; Span<byte> db = em.Slice(0, dbLen); Span<byte> hDest = em.Slice(dbLen, _hLen); em[emLen - 1] = 0xBC; byte[] dbMaskRented = CryptoPool.Rent(dbLen); Span<byte> dbMask = new Span<byte>(dbMaskRented, 0, dbLen); using (IncrementalHash hasher = IncrementalHash.CreateHash(_hashAlgorithmName)) { // 4. Generate a random salt of length sLen Span<byte> salt = stackalloc byte[sLen]; RandomNumberGenerator.Fill(salt); // 5. Let M' = an octet string of 8 zeros concat mHash concat salt // 6. Let H = Hash(M') hasher.AppendData(EightZeros); hasher.AppendData(mHash); hasher.AppendData(salt); if (!hasher.TryGetHashAndReset(hDest, out int hLen2) || hLen2 != _hLen) { Debug.Fail("TryGetHashAndReset failed with exact-size destination"); throw new CryptographicException(); } // 7. Generate PS as zero-valued bytes of length emLen - sLen - hLen - 2. // 8. Let DB = PS || 0x01 || salt int psLen = emLen - sLen - _hLen - 2; db.Slice(0, psLen).Clear(); db[psLen] = 0x01; salt.CopyTo(db.Slice(psLen + 1)); // 9. Let dbMask = MGF(H, emLen - hLen - 1) Mgf1(hasher, hDest, dbMask); // 10. Let maskedDB = DB XOR dbMask Xor(db, dbMask); // 11. Set the "unused" bits in the leftmost byte of maskedDB to 0. int unusedBits = 8 * emLen - emBits; if (unusedBits != 0) { byte mask = (byte)(0xFF >> unusedBits); db[0] &= mask; } } CryptographicOperations.ZeroMemory(dbMask); CryptoPool.Return(dbMaskRented, clearSize: 0); } internal bool VerifyPss(ReadOnlySpan<byte> mHash, ReadOnlySpan<byte> em, int keySize) { // https://tools.ietf.org/html/rfc3447#section-9.1.2 int emBits = keySize - 1; int emLen = BytesRequiredForBitCount(emBits); if (mHash.Length != _hLen) { return false; } Debug.Assert(em.Length >= emLen); // In this implementation, sLen is restricted to hLen. int sLen = _hLen; // 3. If emLen < hLen + sLen + 2, output "inconsistent" and stop. if (emLen < _hLen + sLen + 2) { return false; } // 4. If the last byte is not 0xBC, output "inconsistent" and stop. if (em[em.Length - 1] != 0xBC) { return false; } // 5. maskedDB is the leftmost emLen - hLen -1 bytes, H is the next hLen bytes. int dbLen = emLen - _hLen - 1; ReadOnlySpan<byte> maskedDb = em.Slice(0, dbLen); ReadOnlySpan<byte> h = em.Slice(dbLen, _hLen); // 6. If the unused bits aren't zero, output "inconsistent" and stop. int unusedBits = 8 * emLen - emBits; byte usedBitsMask = (byte)(0xFF >> unusedBits); if ((maskedDb[0] & usedBitsMask) != maskedDb[0]) { return false; } // 7. dbMask = MGF(H, emLen - hLen - 1) byte[] dbMaskRented = CryptoPool.Rent(maskedDb.Length); Span<byte> dbMask = new Span<byte>(dbMaskRented, 0, maskedDb.Length); try { using (IncrementalHash hasher = IncrementalHash.CreateHash(_hashAlgorithmName)) { Mgf1(hasher, h, dbMask); // 8. DB = maskedDB XOR dbMask Xor(dbMask, maskedDb); // 9. Set the unused bits of DB to 0 dbMask[0] &= usedBitsMask; // 10 ("a"): If the emLen - hLen - sLen - 2 leftmost bytes are not 0, // output "inconsistent" and stop. // // Since signature verification is a public key operation there's no need to // use fixed time equality checking here. for (int i = emLen - _hLen - sLen - 2 - 1; i >= 0; --i) { if (dbMask[i] != 0) { return false; } } // 10 ("b") If the octet at position emLen - hLen - sLen - 1 (under a 1-indexed scheme) // is not 0x01, output "inconsistent" and stop. if (dbMask[emLen - _hLen - sLen - 2] != 0x01) { return false; } // 11. Let salt be the last sLen octets of DB. ReadOnlySpan<byte> salt = dbMask.Slice(dbMask.Length - sLen); // 12/13. Let H' = Hash(eight zeros || mHash || salt) hasher.AppendData(EightZeros); hasher.AppendData(mHash); hasher.AppendData(salt); Span<byte> hPrime = stackalloc byte[_hLen]; if (!hasher.TryGetHashAndReset(hPrime, out int hLen2) || hLen2 != _hLen) { Debug.Fail("TryGetHashAndReset failed with exact-size destination"); throw new CryptographicException(); } // 14. If H = H' output "consistent". Otherwise, output "inconsistent" // // Since this is a public key operation, no need to provide fixed time // checking. return h.SequenceEqual(hPrime); } } finally { CryptographicOperations.ZeroMemory(dbMask); CryptoPool.Return(dbMaskRented, clearSize: 0); } } // https://tools.ietf.org/html/rfc3447#appendix-B.2.1 private void Mgf1(IncrementalHash hasher, ReadOnlySpan<byte> mgfSeed, Span<byte> mask) { Span<byte> writePtr = mask; int count = 0; Span<byte> bigEndianCount = stackalloc byte[sizeof(int)]; while (writePtr.Length > 0) { hasher.AppendData(mgfSeed); BinaryPrimitives.WriteInt32BigEndian(bigEndianCount, count); hasher.AppendData(bigEndianCount); if (writePtr.Length >= _hLen) { if (!hasher.TryGetHashAndReset(writePtr, out int bytesWritten)) { Debug.Fail($"TryGetHashAndReset failed with sufficient space"); throw new CryptographicException(); } Debug.Assert(bytesWritten == _hLen); writePtr = writePtr.Slice(bytesWritten); } else { Span<byte> tmp = stackalloc byte[_hLen]; if (!hasher.TryGetHashAndReset(tmp, out int bytesWritten)) { Debug.Fail($"TryGetHashAndReset failed with sufficient space"); throw new CryptographicException(); } Debug.Assert(bytesWritten == _hLen); tmp.Slice(0, writePtr.Length).CopyTo(writePtr); break; } count++; } } // This is a copy of RandomNumberGeneratorImplementation.GetNonZeroBytes, but adapted // to the object-less RandomNumberGenerator.Fill. private static void FillNonZeroBytes(Span<byte> data) { while (data.Length > 0) { // Fill the remaining portion of the span with random bytes. RandomNumberGenerator.Fill(data); // Find the first zero in the remaining portion. int indexOfFirst0Byte = data.Length; for (int i = 0; i < data.Length; i++) { if (data[i] == 0) { indexOfFirst0Byte = i; break; } } // If there were any zeros, shift down all non-zeros. for (int i = indexOfFirst0Byte + 1; i < data.Length; i++) { if (data[i] != 0) { data[indexOfFirst0Byte++] = data[i]; } } // Request new random bytes if necessary; dont re-use // existing bytes since they were shifted down. data = data.Slice(indexOfFirst0Byte); } } /// <summary> /// Bitwise XOR of <paramref name="b"/> into <paramref name="a"/>. /// </summary> private static void Xor(Span<byte> a, ReadOnlySpan<byte> b) { if (a.Length != b.Length) { throw new InvalidOperationException(); } for (int i = 0; i < b.Length; i++) { a[i] ^= b[i]; } } } }
37.971168
128
0.486073
[ "MIT" ]
Faithlife/runtime
src/libraries/Common/src/System/Security/Cryptography/RsaPaddingProcessor.cs
25,023
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.Compute.Latest.Outputs { [OutputType] public sealed class SkuResponse { /// <summary> /// Specifies the number of virtual machines in the scale set. /// </summary> public readonly double? Capacity; /// <summary> /// The sku name. /// </summary> public readonly string? Name; /// <summary> /// Specifies the tier of virtual machines in a scale set.&lt;br /&gt;&lt;br /&gt; Possible Values:&lt;br /&gt;&lt;br /&gt; **Standard**&lt;br /&gt;&lt;br /&gt; **Basic** /// </summary> public readonly string? Tier; [OutputConstructor] private SkuResponse( double? capacity, string? name, string? tier) { Capacity = capacity; Name = name; Tier = tier; } } }
27.790698
178
0.579916
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/Compute/Latest/Outputs/SkuResponse.cs
1,195
C#
using System; using System.ComponentModel; using EfsTools.Attributes; using EfsTools.Utils; using Newtonsoft.Json; namespace EfsTools.Items.Nv { [Serializable] [NvItemId(2350)] [Attributes(9)] public class Gsm1900VlTlPrdi15 { [ElementsCount(30)] [ElementType("uint8")] [Description("")] public byte[] Value { get; set; } } }
19.571429
42
0.59854
[ "MIT" ]
HomerSp/EfsTools
EfsTools/Items/Nv/Gsm1900VlTlPrdi15I.cs
411
C#
#pragma checksum "C:\Users\Tran\Downloads\App_UW_Stupendous\App_UW_Stupendous\MainPage.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "520A410F578813AB564DD90E95DB5259" //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace App_UW_Stupendous { partial class MainPage : global::Windows.UI.Xaml.Controls.Page { [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")] private global::Windows.UI.Xaml.Controls.Frame rootFrame; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")] private global::Windows.UI.Xaml.Controls.Button Btn_Complete; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")] private global::Windows.UI.Xaml.Controls.Button Btn_Schedule; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")] private global::Windows.UI.Xaml.Controls.Button Btn_Coffee; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")] private global::Windows.UI.Xaml.Controls.Button Btn_Donuts; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")] private bool _contentLoaded; /// <summary> /// InitializeComponent() /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public void InitializeComponent() { if (_contentLoaded) return; _contentLoaded = true; global::System.Uri resourceLocator = new global::System.Uri("ms-appx:///MainPage.xaml"); global::Windows.UI.Xaml.Application.LoadComponent(this, resourceLocator, global::Windows.UI.Xaml.Controls.Primitives.ComponentResourceLocation.Application); } } }
48.54
169
0.652246
[ "Apache-2.0" ]
trungngotdt/App_UW_Stupendous
App_UW_Stupendous/obj/ARM/Debug/MainPage.g.i.cs
2,429
C#
using System; namespace Specs.Util { public static class Errors { /// <summary> /// Throws an exception if the specified parameter's value is null OR equal to Unity's fake /// null. /// </summary> /// <typeparam name="T">The type of the parameter.</typeparam> /// <param name="value">The value of the argument.</param> /// <param name="parameterName">The name of the parameter to include in any thrown /// exception.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is /// <c>null</c></exception> public static void CheckNotNull<T>(T value, string parameterName) where T : class // ensures value-types aren't passed to a null checking method { // value.Equals(null) checks for Unity's fake null object. if (IsNullOrUnityNull(value)) { throw new ArgumentNullException(parameterName); } } /// <summary> /// Throws an exception if the specified parameter's value is null. It passes through the /// specified value back as a return value. /// </summary> /// <typeparam name="T">The type of the parameter.</typeparam> /// <param name="value">The value of the argument.</param> /// <param name="parameterName">The name of the parameter to include in any thrown /// exception.</param> /// <returns>The value of the parameter.</returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is <c>null</c> /// </exception> public static T CheckNotNullPassthrough<T>(T value, string parameterName) where T : class // ensures value-types aren't passed to a null checking method { CheckNotNull(value, parameterName); return value; } /// <summary> /// Returns true if a value is null or is equal to Unity's fake null value. /// </summary> /// <typeparam name="T">The type of the parameter.</typeparam> /// <param name="value">The value to check.</param> /// <returns>True if <paramref name="value"/> is null or equal to Unity's null.</returns> public static bool IsNullOrUnityNull<T>(T value) where T : class => value == null || value.Equals(obj: null); public static Exception MountFailed(string objectName, string typeName) => new InvalidOperationException("[MountFailed] '" + objectName + " failed to create an instance of '" + typeName + "'"); public static Exception ChildNotFound(string parentName, string childName) => new InvalidOperationException("[ChildNotFound] '" + parentName + " does not contain a child named '" + childName + "'"); public static Exception UnknownEnumValue<T>(T value) => new InvalidOperationException("[UnknownEnumValue] Unknown " + value.GetType() + " enum value: " + Enum.GetName(value.GetType(), value)); public static Exception InvalidName(string name) => new ArgumentException("[InvalidName] '" + name + "' may not contain the character '/'."); public static Exception DuplicateChild(string parentName, string childName) => new InvalidOperationException("[DuplicateChild] '" + parentName + "' contains two children named '" + childName + "'. Provide a 'specId' to differentiate them."); } }
45.824324
108
0.63875
[ "Apache-2.0" ]
thurn/sagan
Assets/Specs/Util/Errors.cs
3,393
C#
namespace DeltaEngine.Input.Mocks { /// <summary> /// Mock keyboard for unit testing. /// </summary> public sealed class MockKeyboard : Keyboard { public MockKeyboard() { IsAvailable = true; } public override void Dispose() { IsAvailable = false; } public void SetKeyboardState(Key key, State state) { keyboardStates[(int)key] = state; if (state == State.Pressing) newlyPressedKeys.Add(key); } protected override void UpdateKeyStates() {} //ncrunch: no coverage protected override bool IsCapsLocked { get { return false; } } } }
19.21875
70
0.634146
[ "Apache-2.0" ]
DeltaEngine/DeltaEngine
Input/Mocks/MockKeyboard.cs
617
C#
using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("Punchkeyboard.Editor")]
31.666667
54
0.831579
[ "MIT" ]
Gusinuhe/Punchkeyboard
Runtime/AssemblyAttributes.cs
97
C#
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace SSPLibrary.Models { public interface IQueryParameters { PagingParameters PagingParameters { get; set; } string ActionName { get; set; } void ApplyQueryParameters( string sortParams, string searchOptions); } }
17.833333
49
0.760125
[ "MIT" ]
BorowskiKamil/SSPLibrary
src/SSPLibrary/Models/IQueryParameters.cs
321
C#
 namespace TagUIWordAddIn { partial class FormUpdate { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormUpdate)); this.buttonUpdate = new System.Windows.Forms.Button(); this.labelUpdateTerms = new System.Windows.Forms.Label(); this.buttonOk = new System.Windows.Forms.Button(); this.SuspendLayout(); // // buttonUpdate // this.buttonUpdate.Location = new System.Drawing.Point(207, 90); this.buttonUpdate.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); this.buttonUpdate.Name = "buttonUpdate"; this.buttonUpdate.Size = new System.Drawing.Size(95, 42); this.buttonUpdate.TabIndex = 0; this.buttonUpdate.Text = "Update"; this.buttonUpdate.UseVisualStyleBackColor = true; this.buttonUpdate.Click += new System.EventHandler(this.buttonUpdate_Click); // // labelUpdateTerms // this.labelUpdateTerms.AutoSize = true; this.labelUpdateTerms.Location = new System.Drawing.Point(11, 22); this.labelUpdateTerms.MaximumSize = new System.Drawing.Size(533, 0); this.labelUpdateTerms.Name = "labelUpdateTerms"; this.labelUpdateTerms.Size = new System.Drawing.Size(495, 34); this.labelUpdateTerms.TabIndex = 1; this.labelUpdateTerms.Text = "This pulls the latest TagUI update from the server and overwrites the existing ve" + "rsion. Internet access is required. Click on the Update button to start."; // // buttonOk // this.buttonOk.Location = new System.Drawing.Point(207, 90); this.buttonOk.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); this.buttonOk.Name = "buttonOk"; this.buttonOk.Size = new System.Drawing.Size(95, 42); this.buttonOk.TabIndex = 2; this.buttonOk.Text = "Ok"; this.buttonOk.UseVisualStyleBackColor = true; this.buttonOk.Visible = false; this.buttonOk.Click += new System.EventHandler(this.buttonOk_Click); // // FormUpdate // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(520, 148); this.Controls.Add(this.buttonOk); this.Controls.Add(this.labelUpdateTerms); this.Controls.Add(this.buttonUpdate); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "FormUpdate"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Update TagUI"; this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.FormUpdate_FormClosed); this.Load += new System.EventHandler(this.FormUpdate_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button buttonUpdate; private System.Windows.Forms.Label labelUpdateTerms; private System.Windows.Forms.Button buttonOk; } }
44.19
142
0.602625
[ "Apache-2.0" ]
aTiKhan/TagUI
src/office/word/TagUIWordAddIn/FormUpdate.Designer.cs
4,421
C#
using System; using System.IO; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Hosting; using WalletWasabi.Logging; using WalletWasabi.Gui.Models; namespace WalletWasabi.Gui.Rpc { public class JsonRpcServer : BackgroundService { private HttpListener Listener { get; } private WasabiJsonRpcService Service { get; } private JsonRpcServerConfiguration Config { get; } public JsonRpcServer(Global global, JsonRpcServerConfiguration config) { Config = config; Listener = new HttpListener(); Listener.AuthenticationSchemes = AuthenticationSchemes.Basic | AuthenticationSchemes.Anonymous; foreach (var prefix in Config.Prefixes) { Listener.Prefixes.Add(prefix); } Service = new WasabiJsonRpcService(global); } public override async Task StartAsync(CancellationToken cancellationToken) { Listener.Start(); await base.StartAsync(cancellationToken).ConfigureAwait(false); } public override async Task StopAsync(CancellationToken cancellationToken) { await base.StopAsync(cancellationToken).ConfigureAwait(false); Listener.Stop(); } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { var handler = new JsonRpcRequestHandler<WasabiJsonRpcService>(Service); while (!stoppingToken.IsCancellationRequested) { try { var context = await GetHttpContextAsync(stoppingToken).ConfigureAwait(false); var request = context.Request; var response = context.Response; if (request.HttpMethod == "POST") { using var reader = new StreamReader(request.InputStream); string body = await reader.ReadToEndAsync().ConfigureAwait(false); var identity = (HttpListenerBasicIdentity)context.User?.Identity; if (!Config.RequiresCredentials || CheckValidCredentials(identity)) { var result = await handler.HandleAsync(body, stoppingToken).ConfigureAwait(false); // result is null only when the request is a notification. if (!string.IsNullOrEmpty(result)) { response.ContentType = "application/json-rpc"; var output = response.OutputStream; var buffer = Encoding.UTF8.GetBytes(result); await output.WriteAsync(buffer, 0, buffer.Length, stoppingToken).ConfigureAwait(false); await output.FlushAsync(stoppingToken).ConfigureAwait(false); } } else { response.StatusCode = (int)HttpStatusCode.Unauthorized; } } else { response.StatusCode = (int)HttpStatusCode.MethodNotAllowed; } response.Close(); } catch (OperationCanceledException) { break; } catch (Exception ex) { Logger.LogError(ex); } } } private async Task<HttpListenerContext> GetHttpContextAsync(CancellationToken cancellationToken) { var getHttpContextTask = Listener.GetContextAsync(); var tcs = new TaskCompletionSource<bool>(); using (cancellationToken.Register(state => ((TaskCompletionSource<bool>)state).TrySetResult(true), tcs)) { var firstTaskToComplete = await Task.WhenAny(getHttpContextTask, tcs.Task).ConfigureAwait(false); if (getHttpContextTask != firstTaskToComplete) { cancellationToken.ThrowIfCancellationRequested(); } } return await getHttpContextTask.ConfigureAwait(false); } private bool CheckValidCredentials(HttpListenerBasicIdentity identity) { return identity is { } && (identity.Name == Config.JsonRpcUser && identity.Password == Config.JsonRpcPassword); } } }
30.389831
114
0.720859
[ "MIT" ]
adamlaska/WalletWasabi
WalletWasabi.Gui/Rpc/JsonRpcServer.cs
3,586
C#
using System; using System.Text; namespace _04_PeshoCode { class PeshoCode { static ulong sum = 0; static void Main() { string word = Console.ReadLine(); int linesCount = int.Parse(Console.ReadLine()); string text = ReadText(linesCount); int wordIndex = text.IndexOf(word); int indexOfDot = text.IndexOf('.', wordIndex); int indexOfQM = text.IndexOf('?', wordIndex); string substring = string.Empty; if (indexOfDot != -1 && (indexOfQM <= 0 || indexOfQM > indexOfDot)) { substring = GetSubstring(text, word, wordIndex, indexOfDot); foreach (var letter in substring) { if (letter != ' ' && letter != '.') { sum += letter; } } } if (indexOfQM != -1 && (indexOfDot <= 0 || indexOfDot > indexOfQM)) { substring = GetSubstring(text, word, wordIndex, indexOfQM); foreach (var letter in substring) { if (letter != ' ' && letter != '.' && letter != '?') { sum += letter; } } } Console.WriteLine(sum); } private static string ReadText(int lines) { StringBuilder text = new StringBuilder(); for (int i = 0; i < lines; i++) { text.Append(Console.ReadLine()); } return text.ToString(); } private static string GetSubstring(string text, string word, int wordIndex, int index) { string sub = string.Empty; if (text[index] == '?') { int startIndex = wordIndex + word.Length; sub = text.Substring(startIndex, index - startIndex + 1); } if (text[index] == '.') { int indexOfDot = text.LastIndexOf('.', wordIndex) > text.LastIndexOf('?', wordIndex) ? text.LastIndexOf('.', wordIndex) : text.LastIndexOf('?', wordIndex); sub = text.Substring(indexOfDot + 1, wordIndex - (indexOfDot + 1)); } return sub.ToUpper(); } } }
32.105263
100
0.445492
[ "MIT" ]
vasilvalkov/TA-2016-CSharp-Advanced
Exam/04_PeshoCode/PeshoCode.cs
2,442
C#
namespace AMLLinesEDMXCodeFirst { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class AML_PLC_BuildList { public decimal LineID { get; set; } [Key] [StringLength(10)] public string BuildNo { get; set; } public DateTime LastUpdated { get; set; } public decimal? EASERead { get; set; } } }
23.636364
55
0.661538
[ "MIT" ]
chrhodes/Applications
EASE/Data/AMLLinesEDMXCodeFirst/AML_PLC_BuildList.cs
520
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 devicefarm-2015-06-23.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.DeviceFarm.Model { /// <summary> /// Container for the parameters to the ListSamples operation. /// Gets information about samples, given an AWS Device Farm job ARN. /// </summary> public partial class ListSamplesRequest : AmazonDeviceFarmRequest { private string _arn; private string _nextToken; /// <summary> /// Gets and sets the property Arn. /// <para> /// The Amazon Resource Name (ARN) of the job used to list samples. /// </para> /// </summary> [AWSProperty(Required=true, Min=32, Max=1011)] 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 NextToken. /// <para> /// An identifier that was returned from the previous call to this operation, which can /// be used to return the next set of items in the list. /// </para> /// </summary> [AWSProperty(Min=4, Max=1024)] public string NextToken { get { return this._nextToken; } set { this._nextToken = value; } } // Check to see if NextToken property is set internal bool IsSetNextToken() { return this._nextToken != null; } } }
30.0375
108
0.617561
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/DeviceFarm/Generated/Model/ListSamplesRequest.cs
2,403
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 iotevents-2018-07-27.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.IoTEvents.Model { /// <summary> /// Information about the detector model. /// </summary> public partial class DetectorModelSummary { private DateTime? _creationTime; private string _detectorModelDescription; private string _detectorModelName; /// <summary> /// Gets and sets the property CreationTime. /// <para> /// The time the detector model was created. /// </para> /// </summary> public DateTime CreationTime { get { return this._creationTime.GetValueOrDefault(); } set { this._creationTime = value; } } // Check to see if CreationTime property is set internal bool IsSetCreationTime() { return this._creationTime.HasValue; } /// <summary> /// Gets and sets the property DetectorModelDescription. /// <para> /// A brief description of the detector model. /// </para> /// </summary> [AWSProperty(Max=128)] public string DetectorModelDescription { get { return this._detectorModelDescription; } set { this._detectorModelDescription = value; } } // Check to see if DetectorModelDescription property is set internal bool IsSetDetectorModelDescription() { return this._detectorModelDescription != null; } /// <summary> /// Gets and sets the property DetectorModelName. /// <para> /// The name of the detector model. /// </para> /// </summary> [AWSProperty(Min=1, Max=128)] public string DetectorModelName { get { return this._detectorModelName; } set { this._detectorModelName = value; } } // Check to see if DetectorModelName property is set internal bool IsSetDetectorModelName() { return this._detectorModelName != null; } } }
30.247423
107
0.620654
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/IoTEvents/Generated/Model/DetectorModelSummary.cs
2,934
C#
namespace OnlyT.Services.CountdownTimer { using System; using System.Collections.Generic; using System.Linq; using Options; using Options.MeetingStartTimes; // ReSharper disable once ClassNeverInstantiated.Global internal sealed class CountdownTimerTriggerService : ICountdownTimerTriggerService { private readonly object _locker = new object(); private readonly IOptionsService _optionsService; private List<CountdownTriggerPeriod> _triggerPeriods; public CountdownTimerTriggerService(IOptionsService optionsService) { _optionsService = optionsService; UpdateTriggerPeriods(); } public void UpdateTriggerPeriods() { var times = _optionsService.Options.MeetingStartTimes.Times; lock (_locker) { _triggerPeriods = null; if (times != null) { CalculateTriggerPeriods(times); } } } public bool IsInCountdownPeriod(out int secondsOffset) { lock (_locker) { if (_triggerPeriods != null) { var now = DateTime.Now; var trigger = _triggerPeriods.FirstOrDefault(x => x.Start <= now && x.End > now); if (trigger != null) { secondsOffset = (int)(now - trigger.Start).TotalSeconds; return true; } } } secondsOffset = 0; return false; } private void CalculateTriggerPeriods(IEnumerable<MeetingStartTime> meetingStartTimes) { var triggerPeriods = new List<CountdownTriggerPeriod>(); DateTime today = DateTime.Today; // local time int countdownDurationMins = _optionsService.Options.CountdownDurationMins; foreach (var time in meetingStartTimes) { if (time.DayOfWeek == null || time.DayOfWeek.Value == today.DayOfWeek) { triggerPeriods.Add(new CountdownTriggerPeriod { Start = today.Add( TimeSpan.FromMinutes( (time.StartTime.Hours * 60) + time.StartTime.Minutes - countdownDurationMins)), End = today.Add(new TimeSpan(time.StartTime.Hours, time.StartTime.Minutes, 0)) }); } } _triggerPeriods = triggerPeriods; } } }
32.743902
111
0.531844
[ "MIT" ]
diagdave1/OnlyT-1
OnlyT/Services/CountdownTimer/CountdownTimerTriggerService.cs
2,687
C#
using System; using System.Buffers; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace Cysharp.Text { public partial struct Utf8ValueStringBuilder : IDisposable, IBufferWriter<byte>, IResettableBufferWriter<byte> { public delegate bool TryFormat<T>(T value, Span<byte> destination, out int written, StandardFormat format); const int ThreadStaticBufferSize = 64444; const int DefaultBufferSize = 65536; // use 64K default buffer. static Encoding UTF8NoBom = new UTF8Encoding(false); static byte newLine1; static byte newLine2; static bool crlf; static Utf8ValueStringBuilder() { var newLine = UTF8NoBom.GetBytes(Environment.NewLine); if (newLine.Length == 1) { // cr or lf newLine1 = newLine[0]; crlf = false; } else { // crlf(windows) newLine1 = newLine[0]; newLine2 = newLine[1]; crlf = true; } } [ThreadStatic] static byte[]? scratchBuffer; [ThreadStatic] internal static bool scratchBufferUsed; byte[] buffer; int index; bool disposeImmediately; /// <summary>Length of written buffer.</summary> public int Length => index; /// <summary>Get the written buffer data.</summary> public ReadOnlySpan<byte> AsSpan() => buffer.AsSpan(0, index); /// <summary>Get the written buffer data.</summary> public ReadOnlyMemory<byte> AsMemory() => buffer.AsMemory(0, index); /// <summary>Get the written buffer data.</summary> public ArraySegment<byte> AsArraySegment() => new ArraySegment<byte>(buffer, 0, index); /// <summary> /// Initializes a new instance /// </summary> /// <param name="disposeImmediately"> /// If true uses thread-static buffer that is faster but must return immediately. /// </param> /// <exception cref="InvalidOperationException"> /// This exception is thrown when <c>new StringBuilder(disposeImmediately: true)</c> or <c>ZString.CreateUtf8StringBuilder(notNested: true)</c> is nested. /// See the README.md /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Utf8ValueStringBuilder(bool disposeImmediately) { if (disposeImmediately && scratchBufferUsed) { ThrowNestedException(); } byte[]? buf; if (disposeImmediately) { buf = scratchBuffer; if (buf == null) { buf = scratchBuffer = new byte[ThreadStaticBufferSize]; } scratchBufferUsed = true; } else { buf = ArrayPool<byte>.Shared.Rent(DefaultBufferSize); } buffer = buf; index = 0; this.disposeImmediately = disposeImmediately; } /// <summary> /// Return the inner buffer to pool. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Dispose() { if (buffer != null) { if (buffer.Length != ThreadStaticBufferSize) { ArrayPool<byte>.Shared.Return(buffer); } buffer = null!; index = 0; if (disposeImmediately) { scratchBufferUsed = false; } } } public void Clear() { index = 0; } public void TryGrow(int sizeHint) { if (buffer.Length < index + sizeHint) { Grow(sizeHint); } } public void Grow(int sizeHint) { var nextSize = buffer.Length * 2; if (sizeHint != 0) { nextSize = Math.Max(nextSize, index + sizeHint); } var newBuffer = ArrayPool<byte>.Shared.Rent(nextSize); buffer.CopyTo(newBuffer, 0); if (buffer.Length != ThreadStaticBufferSize) { ArrayPool<byte>.Shared.Return(buffer); } buffer = newBuffer; } /// <summary>Appends the default line terminator to the end of this instance.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendLine() { if (crlf) { if (buffer.Length - index < 2) Grow(2); buffer[index] = newLine1; buffer[index + 1] = newLine2; index += 2; } else { if (buffer.Length - index < 1) Grow(1); buffer[index] = newLine1; index += 1; } } /// <summary>Appends the string representation of a specified value to this instance.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe void Append(char value) { var maxLen = UTF8NoBom.GetMaxByteCount(1); if (buffer.Length - index < maxLen) { Grow(maxLen); } fixed (byte* bp = &buffer[index]) { index += UTF8NoBom.GetBytes(&value, 1, bp, maxLen); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Append(char value, int repeatCount) { if (repeatCount < 0) { throw new ArgumentOutOfRangeException(nameof(repeatCount)); } if (value <= 0x7F) // ASCII { GetSpan(repeatCount).Fill((byte)value); Advance(repeatCount); } else { var maxLen = UTF8NoBom.GetMaxByteCount(1); Span<byte> utf8Bytes = stackalloc byte[maxLen]; ReadOnlySpan<char> chars = stackalloc char[1] { value }; int len = UTF8NoBom.GetBytes(chars, utf8Bytes); TryGrow(len * repeatCount); for (int i = 0; i < repeatCount; i++) { utf8Bytes.CopyTo(GetSpan(len)); Advance(len); } } } /// <summary>Appends the string representation of a specified value followed by the default line terminator to the end of this instance.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendLine(char value) { Append(value); AppendLine(); } /// <summary>Appends the string representation of a specified value to this instance.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Append(string? value) { #if UNITY_2018_3_OR_NEWER var maxLen = UTF8NoBom.GetMaxByteCount(value.Length); if (buffer.Length - index < maxLen) { Grow(maxLen); } index += UTF8NoBom.GetBytes(value, 0, value.Length, buffer, index); #else Append(value.AsSpan()); #endif } /// <summary>Appends the string representation of a specified value followed by the default line terminator to the end of this instance.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendLine(string? value) { Append(value); AppendLine(); } /// <summary>Appends a contiguous region of arbitrary memory to this instance.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Append(ReadOnlySpan<char> value) { var maxLen = UTF8NoBom.GetMaxByteCount(value.Length); if (buffer.Length - index < maxLen) { Grow(maxLen); } index += UTF8NoBom.GetBytes(value, buffer.AsSpan(index)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendLine(ReadOnlySpan<char> value) { Append(value); AppendLine(); } /// <summary>Appends the string representation of a specified value to this instance.</summary> public void Append<T>(T value) { if (!FormatterCache<T>.TryFormatDelegate(value, buffer.AsSpan(index), out var written, default)) { Grow(written); if (!FormatterCache<T>.TryFormatDelegate(value, buffer.AsSpan(index), out written, default)) { ThrowArgumentException(nameof(value)); } } index += written; } /// <summary>Appends the string representation of a specified value followed by the default line terminator to the end of this instance.</summary> public void AppendLine<T>(T value) { Append(value); AppendLine(); } // Output /// <summary>Copy inner buffer to the bufferWriter.</summary> public void CopyTo(IBufferWriter<byte> bufferWriter) { var destination = bufferWriter.GetSpan(index); TryCopyTo(destination, out var written); bufferWriter.Advance(written); } /// <summary>Copy inner buffer to the destination span.</summary> public bool TryCopyTo(Span<byte> destination, out int bytesWritten) { if (destination.Length < index) { bytesWritten = 0; return false; } bytesWritten = index; buffer.AsSpan(0, index).CopyTo(destination); return true; } /// <summary>Write inner buffer to stream.</summary> public Task WriteToAsync(Stream stream) { return stream.WriteAsync(buffer, 0, index); } /// <summary>Encode the innner utf8 buffer to a System.String.</summary> public override string ToString() { if (index == 0) return string.Empty; return UTF8NoBom.GetString(buffer, 0, index); } // IBufferWriter /// <summary>IBufferWriter.GetMemory.</summary> public Memory<byte> GetMemory(int sizeHint) { if ((buffer.Length - index) < sizeHint) { Grow(sizeHint); } return buffer.AsMemory(index); } /// <summary>IBufferWriter.GetSpan.</summary> public Span<byte> GetSpan(int sizeHint) { if ((buffer.Length - index) < sizeHint) { Grow(sizeHint); } return buffer.AsSpan(index); } /// <summary>IBufferWriter.Advance.</summary> public void Advance(int count) { index += count; } void IResettableBufferWriter<byte>.Reset() { index = 0; } void ThrowArgumentException(string paramName) { throw new ArgumentException("Can't format argument.", paramName); } [DoesNotReturn] void ThrowFormatException() { throw new FormatException("Index (zero based) must be greater than or equal to zero and less than the size of the argument list."); } [DoesNotReturn] static void ThrowNestedException() { throw new NestedStringBuilderCreationException(nameof(Utf16ValueStringBuilder)); } private void AppendFormatInternal<T>(T arg, int width, StandardFormat format, string argName) { if (width <= 0) // leftJustify { width *= -1; if (!FormatterCache<T>.TryFormatDelegate(arg, buffer.AsSpan(index), out var charsWritten, format)) { Grow(charsWritten); if (!FormatterCache<T>.TryFormatDelegate(arg, buffer.AsSpan(index), out charsWritten, format)) { ThrowArgumentException(argName); } } index += charsWritten; int padding = width - charsWritten; if (width > 0 && padding > 0) { Append(' ', padding); // TODO Fill Method is too slow. } } else // rightJustify { if (typeof(T) == typeof(string)) { var s = Unsafe.As<string>(arg); int padding = width - s.Length; if (padding > 0) { Append(' ', padding); // TODO Fill Method is too slow. } Append(s); } else { Span<byte> s = stackalloc byte[typeof(T).IsValueType ? Unsafe.SizeOf<T>() * 8 : 1024]; if (!FormatterCache<T>.TryFormatDelegate(arg, s, out var charsWritten, format)) { s = stackalloc byte[s.Length * 2]; if (!FormatterCache<T>.TryFormatDelegate(arg, s, out charsWritten, format)) { ThrowArgumentException(argName); } } int padding = width - charsWritten; if (padding > 0) { Append(' ', padding); // TODO Fill Method is too slow. } s.CopyTo(GetSpan(charsWritten)); Advance(charsWritten); } } } /// <summary> /// Register custom formatter /// </summary> public static void RegisterTryFormat<T>(TryFormat<T> formatMethod) { FormatterCache<T>.TryFormatDelegate = formatMethod; } static TryFormat<T?> CreateNullableFormatter<T>() where T : struct { return new TryFormat<T?>((T? x, Span<byte> destination, out int written, StandardFormat format) => { if (x == null) { written = 0; return true; } return FormatterCache<T>.TryFormatDelegate(x.Value, destination, out written, format); }); } /// <summary> /// Supports the Nullable type for a given struct type. /// </summary> public static void EnableNullableFormat<T>() where T : struct { RegisterTryFormat<T?>(CreateNullableFormatter<T>()); } public static class FormatterCache<T> { public static TryFormat<T> TryFormatDelegate; static FormatterCache() { var formatter = (TryFormat<T>?)CreateFormatter(typeof(T)); if (formatter == null) { if (typeof(T).IsEnum) { formatter = new TryFormat<T>(EnumUtil<T>.TryFormatUtf8); } else { formatter = new TryFormat<T>(TryFormatDefault); } } TryFormatDelegate = formatter; } static bool TryFormatDefault(T value, Span<byte> dest, out int written, StandardFormat format) { if (value == null) { written = 0; return true; } var s = typeof(T) == typeof(string) ? Unsafe.As<string>(value) : (value is IFormattable formattable && format != default) ? formattable.ToString(format.ToString(), null) : value.ToString(); // also use this length when result is false. written = UTF8NoBom.GetMaxByteCount(s.Length); if (dest.Length < written) { return false; } written = UTF8NoBom.GetBytes(s.AsSpan(), dest); return true; } } } }
32.176583
162
0.503758
[ "MIT" ]
udaken/ZString
src/ZString.Unity/Assets/Scripts/ZString/Utf8ValueStringBuilder.cs
16,766
C#
namespace System.Web { public static class HttpRequestExtensions { public static string GetBaseUrl(this HttpRequest request) { return request.Url.Scheme + "://" + request.Url.Authority + request.ApplicationPath.TrimEnd('/') + "/"; } } }
25.909091
115
0.617544
[ "Apache-2.0" ]
moein-shafiei/test
source/Src/Infra.Web/Extensions/HttpRequestExtensions.cs
285
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; namespace WebApiTests.Api { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } }
23.6
62
0.581356
[ "MIT" ]
danielplawgo/WebApiTests
WebApiTests/WebApiTests.Api/App_Start/WebApiConfig.cs
592
C#
namespace OOP1 { public class ArrayHelper { public static int[] Fibonacci(int n) { int[] F = new int[n]; F[0] = 0; if (n == 0) return F; F[1] = 1; if (n == 1) return F; int i = 1; while (i < n - 1) { i++; F[i] = F[i - 1] + F[i - 2]; } return F; } public static int Frecventa(int[] vector, int element) { int frecventa = 0; for (int i = 0; i < vector.Length; i++) { if (vector[i] == element) frecventa++; } return frecventa; } public static bool Identitate(int[,] matrix) { bool esteIdentitate = true; for (int row = 0; row < matrix.GetLength(0); row++) { for (int col = 0; col < matrix.GetLength(1); col++) { if (row != col) { if (matrix[row, col] != 0) { esteIdentitate = false; } } else if (matrix[row, col] != 1) { esteIdentitate = false; } } } if (esteIdentitate == true) return true; else return false; } } }
24.66129
67
0.323741
[ "MIT" ]
PetDama/oop
oop/oop/ArrayHelper.cs
1,531
C#
using EloBuddy.SDK; using System.Linq; using static SmartCast.Damages; using static SmartCast.Program; using static SmartCast.Settings; using static SmartCast.Logic.Abilities; using static SmartCast.Logic.ActiveItems; using static SmartCast.Logic.SummonerSpells; namespace SmartCast { internal class Modes { internal static void Combo() { CriticalShield(); if (!IsUnitsAround(Unit.Enemy)) return; UsePotions(Effect.Heal); UseIgnite(Effect.Killsteal); UseChillingSmite(Effect.Killsteal); UseChillingSmite(Effect.Slow, Mode.Combo); Stun(Mode.Combo); Shield(Mode.Combo); Attack(Mode.Combo); UseChallengingSmite(Mode.Combo); BasicAttack(Unit.Enemy); } internal static void Harass() { CriticalShield(); if (!IsUnitsAround(Unit.Enemy)) return; UsePotions(Effect.Heal); UseIgnite(Effect.Killsteal); UseChillingSmite(Effect.Killsteal); Stun(Mode.Harass); Shield(Mode.Harass); Attack(Mode.Harass); BasicAttack(Unit.Enemy); } internal static void LastHit() { CriticalShield(); if (!IsUnitsAround(Unit.Minion)) return; UsePotions(Effect.Heal); Shield(Mode.LastHit); Attack(Mode.LastHit); } internal static void JungleClear() { CriticalShield(); if (!IsUnitsAround(Unit.Monster)) return; UsePotions(Effect.Heal); UseSmite(Effect.Killsteal, Mode.JungleClear); UseSmite(Effect.Heal); Shield(Mode.JungleClear); Attack(Mode.JungleClear); BasicAttack(Unit.Monster); } internal static void LaneClear() { CriticalShield(); if (!IsUnitsAround(Unit.Minion)) return; UsePotions(Effect.Heal); UseSmite(Effect.Killsteal, Mode.LaneClear); UseSmite(Effect.Heal); Shield(Mode.LaneClear); Attack(Mode.LaneClear); BasicAttack(Unit.Minion); } internal static void Flee() { CriticalShield(); if (!IsUnitsAround(Unit.Enemy)) return; UsePotions(Effect.Heal); UseIgnite(Effect.Killsteal); UseChillingSmite(Effect.Killsteal); Stun(Mode.Flee); UseChillingSmite(Effect.Slow, Mode.Flee); UseChallengingSmite(Mode.Flee); Shield(Mode.Flee); Escape(); } private static bool IsUnitsAround(Unit unit) { if (unit == Unit.Enemy) return EntityManager.Heroes.Enemies.Where(Enemy => Enemy.IsInRange(Udyr, FULL_RANGE)).Any(); else if (unit == Unit.Minion) return EntityManager.MinionsAndMonsters.EnemyMinions.Where(Minion => Minion.IsInRange(Udyr, HALF_RANGE)).Any(); else if (unit == Unit.Monster) return EntityManager.MinionsAndMonsters.Monsters.Where(Monster => Monster.IsInRange(Udyr, HALF_RANGE)).Any(); return false; } } }
29.428571
128
0.534837
[ "MIT" ]
hazanpro/EloBuddy
SmartCast Udyr/Modes.cs
3,504
C#
// Based on: https://github.com/dotnet/machinelearning-samples/tree/main/samples/csharp/getting-started/DeepLearning_ImageClassification_Training using Deltatre.ModelFineTuningDemo.Common; using Deltatre.ModelFineTuningDemo.Common.Model; using Microsoft.ML; var datasetRelativePath = @"../../../../"; string datasetPath = GetAbsolutePath(datasetRelativePath); var datasetFolder = Path.Combine(datasetPath, "SampleData"); var outputFolder = Path.Combine(datasetPath, "SampleData", "Outputs"); var trainingDatasetFolder = Path.Combine(datasetFolder, "Training"); var validationDatasetFolder = Path.Combine(datasetFolder, "Validation"); var testDatasetFolder = Path.Combine(datasetFolder, "Test"); var modelFilePath = Path.Combine(datasetPath, "SampleData", "MLModels", "TF_Sport_Classification.zip"); try { var mlContext = new MLContext(seed: 678); Console.WriteLine($"Loading model from: {modelFilePath}"); // Load the model var loadedModel = mlContext.Model.Load(modelFilePath, out var modelInputSchema); // Create prediction engine var predictionEngine = mlContext.Model.CreatePredictionEngine<InMemoryImageData, ImagePrediction>(loadedModel); // Predict images in the folder var imagesToPredict = FileUtils.LoadInMemoryImagesFromDirectory(testDatasetFolder, true); // Measure prediction execution time var watch = System.Diagnostics.Stopwatch.StartNew(); // Predict all images in the folder Console.WriteLine(""); Console.WriteLine($"Predicting images from '{testDatasetFolder}'"); int counter = 0; foreach (var currentImageToPredict in imagesToPredict) { var currentPrediction = predictionEngine.Predict(currentImageToPredict); Console.WriteLine($"Image Filename : [{currentImageToPredict.ImageFileName}], Predicted Label : [{currentPrediction.PredictedLabel}], Probability : [{currentPrediction.Score.Max()}]"); counter++; } // Stop measuring time watch.Stop(); Console.WriteLine($"Predictions took {watch.ElapsedMilliseconds}ms ({watch.ElapsedMilliseconds / counter}ms per prediction)"); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } Console.WriteLine("Press any key to end the app..."); Console.ReadKey(); string GetAbsolutePath(string relativePath) { FileInfo _dataRoot = new(typeof(Program).Assembly.Location); string? assemblyFolderPath = _dataRoot?.Directory?.FullName; if (!string.IsNullOrWhiteSpace(assemblyFolderPath)) { return Path.Combine(assemblyFolderPath, relativePath); } return relativePath; }
34.986486
192
0.747779
[ "MIT" ]
deltatrelabs/deltatre-net-conf-2022-mlnet
src/ModelFineTuningDemo/Deltatre.ModelFineTuningDemo.Score.CLI/Program.cs
2,591
C#
using UnityEngine; using System.Collections; using System.Linq; namespace Crosstales.RTVoice.Provider { /// <summary>Android voice provider.</summary> public class VoiceProviderAndroid : BaseVoiceProvider { #region Variables #if UNITY_ANDROID || UNITY_EDITOR private static bool isInitialized = false; private static AndroidJavaObject TtsHandler; private readonly WaitForSeconds wfs = new WaitForSeconds(0.1f); #endif #endregion #region Constructor /// <summary> /// Constructor for VoiceProviderAndroid. /// </summary> /// <param name="obj">Instance of the speaker</param> public VoiceProviderAndroid(MonoBehaviour obj) : base(obj) { #if UNITY_ANDROID || UNITY_EDITOR if (!isInitialized) { initializeTTS(); } speakerObj.StartCoroutine(getVoices()); #endif } #endregion #region Implemented methods public override string AudioFileExtension { get { return ".wav"; } } public override AudioType AudioFileType { get { return AudioType.WAV; } } public override string DefaultVoiceName { get { return "English (United States)"; } } public override bool isWorkingInEditor { get { return false; } } public override int MaxTextLength { get { return 3999; } } public override bool isSpeakNativeSupported { get { return true; } } public override bool isSpeakSupported { get { return true; } } public override bool isPlatformSupported { get { return Util.Helper.isAndroidPlatform; } } public override bool isSSMLSupported { get { return false; } } public override IEnumerator SpeakNative(Model.Wrapper wrapper) { #if UNITY_ANDROID || UNITY_EDITOR if (wrapper == null) { Debug.LogWarning("'wrapper' is null!"); } else { if (string.IsNullOrEmpty(wrapper.Text)) { Debug.LogWarning("'wrapper.Text' is null or empty!"); } else { yield return null; //return to the main process (uid) if (!isInitialized) { do { // waiting... yield return wfs; } while (!(isInitialized = TtsHandler.CallStatic<bool>("isInitalized"))); } string voiceName = getVoiceName(wrapper); silence = false; onSpeakStart(wrapper); TtsHandler.CallStatic("SpeakNative", new object[] { wrapper.Text, wrapper.Rate, wrapper.Pitch, wrapper.Volume, voiceName }); do { yield return wfs; } while (!silence && TtsHandler.CallStatic<bool>("isWorking")); if (Util.Config.DEBUG) Debug.Log("Text spoken: " + wrapper.Text); onSpeakComplete(wrapper); } } #else yield return null; #endif } public override IEnumerator Speak(Model.Wrapper wrapper) { #if UNITY_ANDROID || UNITY_EDITOR if (wrapper == null) { Debug.LogWarning("'wrapper' is null!"); } else { if (string.IsNullOrEmpty(wrapper.Text)) { Debug.LogWarning("'wrapper.Text' is null or empty: " + wrapper); } else { if (wrapper.Source == null) { Debug.LogWarning("'wrapper.Source' is null: " + wrapper); } else { yield return null; //return to the main process (uid) if (!isInitialized) { do { // waiting... yield return wfs; } while (!(isInitialized = TtsHandler.CallStatic<bool>("isInitalized"))); } string voiceName = getVoiceName(wrapper); string outputFile = getOutputFile(wrapper.Uid, true); TtsHandler.CallStatic<string>("Speak", new object[] { wrapper.Text, wrapper.Rate, wrapper.Pitch, voiceName, outputFile }); silence = false; onSpeakAudioGenerationStart(wrapper); do { yield return wfs; } while (!silence && TtsHandler.CallStatic<bool>("isWorking")); yield return playAudioFile(wrapper, Util.Constants.PREFIX_FILE + outputFile, outputFile); } } } #else yield return null; #endif } public override IEnumerator Generate(Model.Wrapper wrapper) { #if UNITY_ANDROID || UNITY_EDITOR if (wrapper == null) { Debug.LogWarning("'wrapper' is null!"); } else { if (string.IsNullOrEmpty(wrapper.Text)) { Debug.LogWarning("'wrapper.Text' is null or empty: " + wrapper); } else { yield return null; //return to the main process (uid) if (!isInitialized) { do { // waiting... yield return wfs; } while (!(isInitialized = TtsHandler.CallStatic<bool>("isInitalized"))); } string voiceName = getVoiceName(wrapper); string outputFile = getOutputFile(wrapper.Uid, true); TtsHandler.CallStatic<string>("Speak", new object[] { wrapper.Text, wrapper.Rate, wrapper.Pitch, voiceName, outputFile }); silence = false; onSpeakAudioGenerationStart(wrapper); do { yield return wfs; } while (!silence && TtsHandler.CallStatic<bool>("isWorking")); processAudioFile(wrapper, outputFile); } } #else yield return null; #endif } public override void Silence() { silence = true; #if UNITY_ANDROID || UNITY_EDITOR TtsHandler.CallStatic("StopNative"); #endif } #endregion #region Public methods public void ShutdownTTS() { #if UNITY_ANDROID || UNITY_EDITOR TtsHandler.CallStatic("Shutdown"); #endif } #endregion #region Private methods private IEnumerator getVoices() { #if UNITY_ANDROID || UNITY_EDITOR yield return null; if (!isInitialized) { do { yield return wfs; } while (!(isInitialized = TtsHandler.CallStatic<bool>("isInitalized"))); } try { string[] myStringVoices = TtsHandler.CallStatic<string[]>("GetVoices"); System.Collections.Generic.List<Model.Voice> voices = new System.Collections.Generic.List<Model.Voice>(300); foreach (string voice in myStringVoices) { string[] currentVoiceData = voice.Split(';'); Model.Enum.Gender gender = Model.Enum.Gender.UNKNOWN; if (currentVoiceData[0].CTContains("#male")) { gender = Model.Enum.Gender.MALE; } else if (currentVoiceData[0].CTContains("#female")) { gender = Model.Enum.Gender.FEMALE; } Model.Voice newVoice = new Model.Voice(currentVoiceData[0], "Android voice: " + voice, gender, "unknown", currentVoiceData[1]); voices.Add(newVoice); } cachedVoices = voices.OrderBy(s => s.Name).ToList(); if (Util.Constants.DEV_DEBUG) Debug.Log("Voices read: " + cachedVoices.CTDump()); //onVoicesReady(); } catch (System.Exception ex) { string errorMessage = "Could not get any voices!" + System.Environment.NewLine + ex; Debug.LogError(errorMessage); onErrorInfo(null, errorMessage); } #else yield return null; #endif onVoicesReady(); } #if UNITY_ANDROID || UNITY_EDITOR private void initializeTTS() { AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity"); TtsHandler = new AndroidJavaObject("com.crosstales.RTVoice.RTVoiceAndroidBridge", new object[] { jo }); } #endif #endregion #region Editor-only methods #if UNITY_EDITOR public override void GenerateInEditor(Model.Wrapper wrapper) { Debug.LogError("GenerateInEditor is not supported for Unity Android!"); } public override void SpeakNativeInEditor(Model.Wrapper wrapper) { Debug.LogError("SpeakNativeInEditor is not supported for Unity Android!"); } #endif #endregion } } // © 2016-2019 crosstales LLC (https://www.crosstales.com)
27.089806
147
0.444942
[ "MIT" ]
Sadeqsoli/1100-Words
1100 Words/Assets/Plugins/crosstales/RTVoice/Scripts/Provider/VoiceProviderAndroid.cs
11,164
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.Confluent.Models.Api20200301 { using static Microsoft.Azure.PowerShell.Cmdlets.Confluent.Runtime.Extensions; /// <summary>The response of a list operation.</summary> public partial class OrganizationResourceListResult : Microsoft.Azure.PowerShell.Cmdlets.Confluent.Models.Api20200301.IOrganizationResourceListResult, Microsoft.Azure.PowerShell.Cmdlets.Confluent.Models.Api20200301.IOrganizationResourceListResultInternal { /// <summary>Backing field for <see cref="NextLink" /> property.</summary> private string _nextLink; /// <summary>Link to the next set of results, if any.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Confluent.Origin(Microsoft.Azure.PowerShell.Cmdlets.Confluent.PropertyOrigin.Owned)] public string NextLink { get => this._nextLink; set => this._nextLink = value; } /// <summary>Backing field for <see cref="Value" /> property.</summary> private Microsoft.Azure.PowerShell.Cmdlets.Confluent.Models.Api20200301.IOrganizationResource[] _value; /// <summary>Result of a list operation.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Confluent.Origin(Microsoft.Azure.PowerShell.Cmdlets.Confluent.PropertyOrigin.Owned)] public Microsoft.Azure.PowerShell.Cmdlets.Confluent.Models.Api20200301.IOrganizationResource[] Value { get => this._value; set => this._value = value; } /// <summary>Creates an new <see cref="OrganizationResourceListResult" /> instance.</summary> public OrganizationResourceListResult() { } } /// The response of a list operation. public partial interface IOrganizationResourceListResult : Microsoft.Azure.PowerShell.Cmdlets.Confluent.Runtime.IJsonSerializable { /// <summary>Link to the next set of results, if any.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Confluent.Runtime.Info( Required = false, ReadOnly = false, Description = @"Link to the next set of results, if any.", SerializedName = @"nextLink", PossibleTypes = new [] { typeof(string) })] string NextLink { get; set; } /// <summary>Result of a list operation.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Confluent.Runtime.Info( Required = false, ReadOnly = false, Description = @"Result of a list operation.", SerializedName = @"value", PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Confluent.Models.Api20200301.IOrganizationResource) })] Microsoft.Azure.PowerShell.Cmdlets.Confluent.Models.Api20200301.IOrganizationResource[] Value { get; set; } } /// The response of a list operation. internal partial interface IOrganizationResourceListResultInternal { /// <summary>Link to the next set of results, if any.</summary> string NextLink { get; set; } /// <summary>Result of a list operation.</summary> Microsoft.Azure.PowerShell.Cmdlets.Confluent.Models.Api20200301.IOrganizationResource[] Value { get; set; } } }
50.873016
161
0.687676
[ "MIT" ]
AverageDesigner/azure-powershell
src/Confluent/generated/api/Models/Api20200301/OrganizationResourceListResult.cs
3,143
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DTerrain { public interface IChunkCollider { void UpdateColliders(List<Column> pixelData, ITextureSource textureSource); } }
19.5
83
0.754579
[ "MIT" ]
Ideefixze/DTerrain
Destructible Terrain/Assets/Scripts/Chunk/PaintableChunk/CollidableChunk/ChunkCollider/IChunkCollider.cs
275
C#
using Haiku.Fluctuface.Server.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Haiku.Fluctuface.Server.Controllers { [Route("api/[controller]")] [ApiController] public class FluctuantVariablesController : ControllerBase { internal static FluctuantServer server; readonly FluctuantContext _context; public FluctuantVariablesController(FluctuantContext context) { _context = context; AddNew(); RemoveOld(); _context.SaveChanges(); } // GET: api/FluctuantVariables [HttpGet] public async Task<ActionResult<IEnumerable<FluctuantVariable>>> GetFluctuantVariables() { return await _context.FluctuantVariables.ToListAsync(); } // PUT: api/FluctuantVariables/5 // To protect from overposting attacks, enable the specific properties you want to bind to, for // more details, see https://go.microsoft.com/fwlink/?linkid=2123754. [HttpPut("{id}")] public async Task<IActionResult> PutFluctuantVariable(string id, FluctuantVariable fluctuantVariable) { if (id != fluctuantVariable.Id) { return BadRequest(); } _context.Entry(fluctuantVariable).State = EntityState.Modified; try { await _context.SaveChangesAsync().ContinueWith(task => { server.SendUpdateToPatron(fluctuantVariable); return task; }); } catch (DbUpdateConcurrencyException) { if (!FluctuantVariableExists(id)) { return NotFound(); } else { throw; } } return NoContent(); } void AddNew() { foreach (var fluct in server.flucts) { if (!FluctuantVariableExists(fluct.Id)) { _context.Add(fluct); } } } void RemoveOld() { var newIds = new HashSet<string>(server.flucts.Select(f => f.Id)); var deletedIds = new HashSet<string>(_context.FluctuantVariables.Select(v => v.Id)); deletedIds.ExceptWith(newIds); foreach (var id in deletedIds) { var fluct = _context.FluctuantVariables.FirstOrDefault(f => f.Id == id); if (fluct != null) { _context.Remove(fluct); } } } bool FluctuantVariableExists(string id) { return _context.FluctuantVariables.Any(e => e.Id == id); } } }
28.673077
109
0.529175
[ "MIT" ]
HaikuJock/Fluctuface
Fluctuface.Server/Controllers/FluctuantVariablesController.cs
2,984
C#
using Newtonsoft.Json.Linq; using Skybrud.Essentials.Json.Extensions; using Skybrud.Social.Google.Models; namespace Skybrud.Social.Google.YouTube.Models.PlaylistItems { /// <see> /// <cref>https://developers.google.com/youtube/v3/docs/playlistItems#contentDetails</cref> /// </see> public class YouTubePlaylistItemContentDetails : GoogleObject { #region Properties /// <summary> /// Gets the ID that YouTube uses to uniquely identify a video. /// </summary> public string VideoId { get; } #endregion #region Constructor /// <summary> /// Initializes a new instance from the specified <paramref name="json"/> object. /// </summary> /// <param name="json">The instance of <see cref="JObject"/> representing the object.</param> protected YouTubePlaylistItemContentDetails(JObject json) : base(json) { VideoId = json.GetString("videoId"); } #endregion #region Static methods /// <summary> /// Returns a new <see cref="YouTubePlaylistItemContentDetails"/> parsed from the specified <paramref name="json"/> object. /// </summary> /// <param name="json">The instance of <see cref="JObject"/> to parse.</param> /// <returns>An instance of <see cref="YouTubePlaylistItemContentDetails"/>.</returns> public static YouTubePlaylistItemContentDetails Parse(JObject json) { return json == null ? null : new YouTubePlaylistItemContentDetails(json); } #endregion } }
33.229167
131
0.636364
[ "MIT" ]
abjerner/Skybrud.Social.Google.YouTube
src/Skybrud.Social.Google.YouTube/Models/PlaylistItems/YouTubePlaylistItemContentDetails.cs
1,595
C#
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ namespace Microsoft.Azure.IIoT.Services.OpcUa.Registry.v2.Models { using Microsoft.Azure.IIoT.OpcUa.Registry.Models; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; /// <summary> /// Supervisor runtime status /// </summary> public class SupervisorStatusApiModel { /// <summary> /// Default constructor /// </summary> public SupervisorStatusApiModel() { } /// <summary> /// Create from service model /// </summary> /// <param name="model"></param> public SupervisorStatusApiModel(SupervisorStatusModel model) { if (model == null) { throw new ArgumentNullException(nameof(model)); } DeviceId = model.DeviceId; ModuleId = model.ModuleId; SiteId = model.SiteId; Endpoints = model.Endpoints? .Select(e => e == null ? null : new EndpointActivationStatusApiModel(e)) .ToList(); } /// <summary> /// Edge device id /// </summary> [JsonProperty(PropertyName = "deviceId")] [Required] public string DeviceId { get; set; } /// <summary> /// Module id /// </summary> [JsonProperty(PropertyName = "moduleId", NullValueHandling = NullValueHandling.Ignore)] public string ModuleId { get; set; } /// <summary> /// Site id /// </summary> [JsonProperty(PropertyName = "siteId", NullValueHandling = NullValueHandling.Ignore)] [DefaultValue(null)] public string SiteId { get; set; } /// <summary> /// Endpoint activation status /// </summary> [JsonProperty(PropertyName = "endpoints", NullValueHandling = NullValueHandling.Ignore)] [DefaultValue(null)] public List<EndpointActivationStatusApiModel> Endpoints { get; set; } } }
33.180556
99
0.55337
[ "MIT" ]
TheWaywardHayward/Industrial-IoT
services/src/Microsoft.Azure.IIoT.Services.OpcUa.Registry/src/v2/Models/SupervisorStatusApiModel.cs
2,389
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using AspNetCoreIdentityLocalization.Resources; namespace Microsoft.AspNetCore.Identity { /// <summary> /// Service to enable localization for application facing identity errors. /// </summary> /// <remarks> /// These errors are returned to controllers and are generally used as display messages to end users. /// </remarks> public class MultilanguageIdentityErrorDescriber : IdentityErrorDescriber { private readonly LocService _sharedLocalizer; public MultilanguageIdentityErrorDescriber(LocService sharedLocalizer) { _sharedLocalizer = sharedLocalizer; } /// <summary> /// Returns the default <see cref="IdentityError"/>. /// </summary> /// <returns>The default <see cref="IdentityError"/>.</returns> public override IdentityError DefaultError() { return new IdentityError { Code = nameof(DefaultError), Description = _sharedLocalizer.GetLocalizedHtmlString("An unknown failure has occurred.") }; } /// <summary> /// Returns an <see cref="IdentityError"/> indicating a concurrency failure. /// </summary> /// <returns>An <see cref="IdentityError"/> indicating a concurrency failure.</returns> public override IdentityError ConcurrencyFailure() { return new IdentityError { Code = nameof(ConcurrencyFailure), Description = _sharedLocalizer.GetLocalizedHtmlString("Optimistic concurrency failure, object has been modified.") }; } /// <summary> /// Returns an <see cref="IdentityError"/> indicating a password mismatch. /// </summary> /// <returns>An <see cref="IdentityError"/> indicating a password mismatch.</returns> public override IdentityError PasswordMismatch() { return new IdentityError { Code = nameof(PasswordMismatch), Description = _sharedLocalizer.GetLocalizedHtmlString("Incorrect password.") }; } /// <summary> /// Returns an <see cref="IdentityError"/> indicating an invalid token. /// </summary> /// <returns>An <see cref="IdentityError"/> indicating an invalid token.</returns> public override IdentityError InvalidToken() { return new IdentityError { Code = nameof(InvalidToken), Description = _sharedLocalizer.GetLocalizedHtmlString("InvalidToken") }; } /// <summary> /// Returns an <see cref="IdentityError"/> indicating a recovery code was not redeemed. /// </summary> /// <returns>An <see cref="IdentityError"/> indicating a recovery code was not redeemed.</returns> public override IdentityError RecoveryCodeRedemptionFailed() { return new IdentityError { Code = nameof(RecoveryCodeRedemptionFailed), Description = _sharedLocalizer.GetLocalizedHtmlString("RecoveryCodeRedemptionFailed") }; } /// <summary> /// Returns an <see cref="IdentityError"/> indicating an external login is already associated with an account. /// </summary> /// <returns>An <see cref="IdentityError"/> indicating an external login is already associated with an account.</returns> public override IdentityError LoginAlreadyAssociated() { return new IdentityError { Code = nameof(LoginAlreadyAssociated), Description = _sharedLocalizer.GetLocalizedHtmlString("LoginAlreadyAssociated") }; } /// <summary> /// Returns an <see cref="IdentityError"/> indicating the specified user <paramref name="userName"/> is invalid. /// </summary> /// <param name="userName">The user name that is invalid.</param> /// <returns>An <see cref="IdentityError"/> indicating the specified user <paramref name="userName"/> is invalid.</returns> public override IdentityError InvalidUserName(string userName) { return new IdentityError { Code = nameof(InvalidUserName), Description = _sharedLocalizer.GetLocalizedHtmlString("InvalidUserName", userName) }; } /// <summary> /// Returns an <see cref="IdentityError"/> indicating the specified <paramref name="email"/> is invalid. /// </summary> /// <param name="email">The email that is invalid.</param> /// <returns>An <see cref="IdentityError"/> indicating the specified <paramref name="email"/> is invalid.</returns> public override IdentityError InvalidEmail(string email) { return new IdentityError { Code = nameof(InvalidEmail), Description = _sharedLocalizer.GetLocalizedHtmlString("InvalidEmail", email) }; } /// <summary> /// Returns an <see cref="IdentityError"/> indicating the specified <paramref name="userName"/> already exists. /// </summary> /// <param name="userName">The user name that already exists.</param> /// <returns>An <see cref="IdentityError"/> indicating the specified <paramref name="userName"/> already exists.</returns> public override IdentityError DuplicateUserName(string userName) { return new IdentityError { Code = nameof(DuplicateUserName), Description = _sharedLocalizer.GetLocalizedHtmlString("DuplicateUserName", userName) }; } /// <summary> /// Returns an <see cref="IdentityError"/> indicating the specified <paramref name="email"/> is already associated with an account. /// </summary> /// <param name="email">The email that is already associated with an account.</param> /// <returns>An <see cref="IdentityError"/> indicating the specified <paramref name="email"/> is already associated with an account.</returns> public override IdentityError DuplicateEmail(string email) { return new IdentityError { Code = nameof(DuplicateEmail), Description = _sharedLocalizer.GetLocalizedHtmlString("DuplicateEmail", email) }; } /// <summary> /// Returns an <see cref="IdentityError"/> indicating the specified <paramref name="role"/> name is invalid. /// </summary> /// <param name="role">The invalid role.</param> /// <returns>An <see cref="IdentityError"/> indicating the specific role <paramref name="role"/> name is invalid.</returns> public override IdentityError InvalidRoleName(string role) { return new IdentityError { Code = nameof(InvalidRoleName), Description = _sharedLocalizer.GetLocalizedHtmlString("InvalidRoleName", role) }; } /// <summary> /// Returns an <see cref="IdentityError"/> indicating the specified <paramref name="role"/> name already exists. /// </summary> /// <param name="role">The duplicate role.</param> /// <returns>An <see cref="IdentityError"/> indicating the specific role <paramref name="role"/> name already exists.</returns> public override IdentityError DuplicateRoleName(string role) { return new IdentityError { Code = nameof(DuplicateRoleName), Description = _sharedLocalizer.GetLocalizedHtmlString("DuplicateRoleName", role) }; } /// <summary> /// Returns an <see cref="IdentityError"/> indicating a user already has a password. /// </summary> /// <returns>An <see cref="IdentityError"/> indicating a user already has a password.</returns> public override IdentityError UserAlreadyHasPassword() { return new IdentityError { Code = nameof(UserAlreadyHasPassword), Description = _sharedLocalizer.GetLocalizedHtmlString("UserlreadyHasPassword") }; } /// <summary> /// Returns an <see cref="IdentityError"/> indicating user lockout is not enabled. /// </summary> /// <returns>An <see cref="IdentityError"/> indicating user lockout is not enabled.</returns> public override IdentityError UserLockoutNotEnabled() { return new IdentityError { Code = nameof(UserLockoutNotEnabled), Description = _sharedLocalizer.GetLocalizedHtmlString("UserLockoutNotEnabled") }; } /// <summary> /// Returns an <see cref="IdentityError"/> indicating a user is already in the specified <paramref name="role"/>. /// </summary> /// <param name="role">The duplicate role.</param> /// <returns>An <see cref="IdentityError"/> indicating a user is already in the specified <paramref name="role"/>.</returns> public override IdentityError UserAlreadyInRole(string role) { return new IdentityError { Code = nameof(UserAlreadyInRole), Description = _sharedLocalizer.GetLocalizedHtmlString("UserAlreadyInRole", role) }; } /// <summary> /// Returns an <see cref="IdentityError"/> indicating a user is not in the specified <paramref name="role"/>. /// </summary> /// <param name="role">The duplicate role.</param> /// <returns>An <see cref="IdentityError"/> indicating a user is not in the specified <paramref name="role"/>.</returns> public override IdentityError UserNotInRole(string role) { return new IdentityError { Code = nameof(UserNotInRole), Description = _sharedLocalizer.GetLocalizedHtmlString("UserNotInRole", role) }; } /// <summary> /// Returns an <see cref="IdentityError"/> indicating a password of the specified <paramref name="length"/> does not meet the minimum length requirements. /// </summary> /// <param name="length">The length that is not long enough.</param> /// <returns>An <see cref="IdentityError"/> indicating a password of the specified <paramref name="length"/> does not meet the minimum length requirements.</returns> public override IdentityError PasswordTooShort(int length) { return new IdentityError { Code = nameof(PasswordTooShort), Description = _sharedLocalizer.GetLocalizedHtmlString("PasswordTooShort", length.ToString()) }; } /// <summary> /// Returns an <see cref="IdentityError"/> indicating a password does not meet the minimum number <paramref name="uniqueChars"/> of unique chars. /// </summary> /// <param name="uniqueChars">The number of different chars that must be used.</param> /// <returns>An <see cref="IdentityError"/> indicating a password does not meet the minimum number <paramref name="uniqueChars"/> of unique chars.</returns> public override IdentityError PasswordRequiresUniqueChars(int uniqueChars) { return new IdentityError { Code = nameof(PasswordRequiresUniqueChars), Description = _sharedLocalizer.GetLocalizedHtmlString("PasswordRequiresUniqueChars", uniqueChars.ToString()) }; } /// <summary> /// Returns an <see cref="IdentityError"/> indicating a password entered does not contain a non-alphanumeric character, which is required by the password policy. /// </summary> /// <returns>An <see cref="IdentityError"/> indicating a password entered does not contain a non-alphanumeric character.</returns> public override IdentityError PasswordRequiresNonAlphanumeric() { return new IdentityError { Code = nameof(PasswordRequiresNonAlphanumeric), Description = _sharedLocalizer.GetLocalizedHtmlString("PasswordRequiresNonAlphanumeric") }; } /// <summary> /// Returns an <see cref="IdentityError"/> indicating a password entered does not contain a numeric character, which is required by the password policy. /// </summary> /// <returns>An <see cref="IdentityError"/> indicating a password entered does not contain a numeric character.</returns> public override IdentityError PasswordRequiresDigit() { return new IdentityError { Code = nameof(PasswordRequiresDigit), Description = _sharedLocalizer.GetLocalizedHtmlString("PasswordRequiresDigit") }; } /// <summary> /// Returns an <see cref="IdentityError"/> indicating a password entered does not contain a lower case letter, which is required by the password policy. /// </summary> /// <returns>An <see cref="IdentityError"/> indicating a password entered does not contain a lower case letter.</returns> public override IdentityError PasswordRequiresLower() { return new IdentityError { Code = nameof(PasswordRequiresLower), Description = _sharedLocalizer.GetLocalizedHtmlString("PasswordRequiresLower") }; } /// <summary> /// Returns an <see cref="IdentityError"/> indicating a password entered does not contain an upper case letter, which is required by the password policy. /// </summary> /// <returns>An <see cref="IdentityError"/> indicating a password entered does not contain an upper case letter.</returns> public override IdentityError PasswordRequiresUpper() { return new IdentityError { Code = nameof(PasswordRequiresUpper), Description = _sharedLocalizer.GetLocalizedHtmlString("PasswordRequiresUpper") }; } } }
45.855346
173
0.612605
[ "MIT" ]
alekseyaz/AspNetCoreIdentityLocalizationTemplate
src/templates/AspNetCoreIdentityLocalizationTemplate/MultilanguageIdentityErrorDescriber.cs
14,582
C#
// This source code is dual-licensed under the Apache License, version // 2.0, and the Mozilla Public License, version 2.0. // // The APL v2.0: // //--------------------------------------------------------------------------- // Copyright (c) 2007-2020 VMware, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //--------------------------------------------------------------------------- // // The MPL v2.0: // //--------------------------------------------------------------------------- // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. // // Copyright (c) 2007-2020 VMware, Inc. All rights reserved. //--------------------------------------------------------------------------- using System; using RabbitMQ.Client.client.framing; using RabbitMQ.Client.Impl; namespace RabbitMQ.Client.Framing.Impl { internal sealed class BasicPublish : Client.Impl.MethodBase { // deprecated // ushort _reserved1 public string _exchange; public string _routingKey; public bool _mandatory; public bool _immediate; public BasicPublish() { } public BasicPublish(string Exchange, string RoutingKey, bool Mandatory, bool Immediate) { _exchange = Exchange; _routingKey = RoutingKey; _mandatory = Mandatory; _immediate = Immediate; } public BasicPublish(ReadOnlySpan<byte> span) { int offset = 2; offset += WireFormatting.ReadShortstr(span.Slice(offset), out _exchange); offset += WireFormatting.ReadShortstr(span.Slice(offset), out _routingKey); WireFormatting.ReadBits(span.Slice(offset), out _mandatory, out _immediate); } public override ProtocolCommandId ProtocolCommandId => ProtocolCommandId.BasicPublish; public override string ProtocolMethodName => "basic.publish"; public override int WriteArgumentsTo(Span<byte> span) { int length = span.Length; int offset = WireFormatting.WriteShort(ref span.GetStart(), default); offset += WireFormatting.WriteShortstr(ref span.GetOffset(offset), _exchange); offset += WireFormatting.WriteShortstr(ref span.GetOffset(offset), _routingKey); return offset + WireFormatting.WriteBits(ref span.GetOffset(offset), _mandatory, _immediate); } public override int GetRequiredBufferSize() { int bufferSize = 2 + 1 + 1 + 1; // bytes for _reserved1, length of _exchange, length of _routingKey, bit fields bufferSize += WireFormatting.GetByteCount(_exchange); // _exchange in bytes bufferSize += WireFormatting.GetByteCount(_routingKey); // _routingKey in bytes return bufferSize; } } internal sealed class BasicPublishMemory : Client.Impl.MethodBase { // deprecated // ushort _reserved1 public readonly ReadOnlyMemory<byte> _exchange; public readonly ReadOnlyMemory<byte> _routingKey; public readonly bool _mandatory; public readonly bool _immediate; public BasicPublishMemory(ReadOnlyMemory<byte> Exchange, ReadOnlyMemory<byte> RoutingKey, bool Mandatory, bool Immediate) { _exchange = Exchange; _routingKey = RoutingKey; _mandatory = Mandatory; _immediate = Immediate; } public override ProtocolCommandId ProtocolCommandId => ProtocolCommandId.BasicPublish; public override string ProtocolMethodName => "basic.publish"; public override int WriteArgumentsTo(Span<byte> span) { int offset = WireFormatting.WriteShort(ref span.GetStart(), default); offset += WireFormatting.WriteShortstr(ref span.GetOffset(offset), _exchange.Span); offset += WireFormatting.WriteShortstr(ref span.GetOffset(offset), _routingKey.Span); return offset + WireFormatting.WriteBits(ref span.GetOffset(offset), _mandatory, _immediate); } public override int GetRequiredBufferSize() { return 2 + 1 + 1 + 1 + // bytes for _reserved1, length of _exchange, length of _routingKey, bit fields _exchange.Length + _routingKey.Length; } } }
40.330645
129
0.621076
[ "MPL-2.0-no-copyleft-exception", "MPL-2.0", "Apache-2.0" ]
ArdeshirV/rabbitmq-dotnet-client
projects/RabbitMQ.Client/client/framing/BasicPublish.cs
5,001
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace PiCounter { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new PiDigitCounter()); } } }
23.434783
66
0.591837
[ "MIT" ]
oscargbeta/PiCounter
src/PiCounter/PiCounter/Program.cs
541
C#
using System.ComponentModel; using System.Collections.Generic; using Atlas.Interfaces; namespace Atlas.ModManager.Configs.Atlas { public class Scp096Configuration : IConfig { public List<RoleType> DisallowedRoles { get; set; } = new List<RoleType>() { RoleType.Tutorial }; public bool DisableBypass { get; set; } = false; public bool DisableGodMode { get; set; } = false; } }
26
105
0.6875
[ "MIT" ]
Semper00/Atlas
Atlas/ModManager/Configs/Atlas/Scp096Configuration.cs
418
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 inspector2-2020-06-08.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.Inspector2.Model { /// <summary> /// Container for the parameters to the GetMember operation. /// Gets member information for your organization. /// </summary> public partial class GetMemberRequest : AmazonInspector2Request { private string _accountId; /// <summary> /// Gets and sets the property AccountId. /// <para> /// The Amazon Web Services account ID of the member account to retrieve information on. /// </para> /// </summary> [AWSProperty(Required=true, Min=12, Max=12)] public string AccountId { get { return this._accountId; } set { this._accountId = value; } } // Check to see if AccountId property is set internal bool IsSetAccountId() { return this._accountId != null; } } }
30.135593
108
0.66198
[ "Apache-2.0" ]
EbstaLimited/aws-sdk-net
sdk/src/Services/Inspector2/Generated/Model/GetMemberRequest.cs
1,778
C#
namespace EZNEW.Cache.List { /// <summary> /// List insert before response /// </summary> public class ListInsertBeforeResponse : CacheResponse { /// <summary> /// Gets or sets the length of the list after the insert operation, or -1 when the value pivot was not found. /// </summary> public long NewListLength { get; set; } } }
28.5
118
0.586466
[ "MIT" ]
eznew-net/EZNEW.Develop
EZNEW/Cache/List/Response/ListInsertBeforeResponse.cs
401
C#
namespace KisekaeImporter.SubCodes { public class KisekaeShoe : KisekaeClothes { public int Top { get { return GetInt(4); } set { Set(4, value); } } public KisekaeColor TopColor1 { get { return new KisekaeColor(GetString(1)); } set { Set(1, value.ToString()); } } public KisekaeColor TopColor2 { get { return new KisekaeColor(GetString(2)); } set { Set(2, value.ToString()); } } public KisekaeColor TopColor3 { get { return new KisekaeColor(GetString(3)); } set { Set(3, value.ToString()); } } } }
17.870968
49
0.633574
[ "MIT" ]
laytonc32/spnati
editor source/KisekaeImporter/DataStructures/Kisekae/SubCodes/KisekaeShoe.cs
556
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using Gibbed.Spore.Helpers; namespace SporeMaster.RenderWare4 { public class ModelFormatException : FormatException { public string exception_type; public ModelFormatException(Stream r, string description, object argument) : base( String.Format("{0} {2} @0x{1:x}", description, r==null?0:r.Position, argument) ) { exception_type = description; } } public static class StreamHelpers { public static byte[] ReadBytes(this Stream r, int count) { var a = new byte[count]; if (r.Read(a, 0, count) != count) throw new EndOfStreamException(); return a; } public static void WriteU32s(this Stream w, UInt32[] values) { foreach (var v in values) w.WriteU32(v); } public static void ReadPadding(this Stream r, long pad) { if (pad < 0) throw new ModelFormatException(r, "Negative padding", pad); for(long i=0; i<pad; i++) if (r.ReadByte()!=0) throw new ModelFormatException(r, "Nonzero padding", null); } public static void WritePadding(this Stream w, long pad) { if (pad < 0) throw new ModelFormatException(w, "Negative padding", pad); for (long i = 0; i < pad; i++) w.WriteByte(0); } public static void expect(this Stream r, UInt32 value, string error) { var actual = r.ReadU32(); if (actual != value) throw new ModelFormatException(r, error, actual); } public static void expect(this Stream r, UInt32[] values, string error) { foreach (var v in values) r.expect(v, error); } }; public abstract class RW4Object { public RW4Section section; public abstract void Read(RW4Model m, RW4Section s, Stream r); public abstract void Write(RW4Model m, RW4Section s, Stream w); public virtual int ComputeSize() { return -1; } }; interface IRW4Struct { void Read(Stream r); void Write(Stream w); uint Size(); }; struct Triangle : IRW4Struct { public UInt32 i,j,k; public byte unk1; //< 4 bits found in "SimpleMesh", in a parallel section public void Read(Stream r) { i = r.ReadU16(); j = r.ReadU16(); k = r.ReadU16(); } public void Write(Stream w){ w.WriteU16((ushort)i); w.WriteU16((ushort)j); w.WriteU16((ushort)k); } public uint Size() { return 6; } } struct Vertex : IRW4Struct { public const int size = 36; public float x, y, z; public UInt32 normal, tangent; public float u, v; public UInt32 packed_bone_indices, packed_bone_weights; public uint Size() { return size; } public void Read(Stream r) { x = r.ReadF32(); y = r.ReadF32(); z = r.ReadF32(); normal = r.ReadU32(); tangent = r.ReadU32(); u = r.ReadF32(); v = r.ReadF32(); packed_bone_indices = r.ReadU32(); packed_bone_weights = r.ReadU32(); } public void Write(Stream w) { w.WriteF32(x); w.WriteF32(y); w.WriteF32(z); w.WriteU32(normal); w.WriteU32(tangent); w.WriteF32(u); w.WriteF32(v); w.WriteU32(packed_bone_indices); w.WriteU32(packed_bone_weights); } public void Read4(Stream r) { x = r.ReadF32(); y = r.ReadF32(); z = r.ReadF32(); r.expect(0, "4V001"); } public void Write4(Stream w) { w.WriteF32(x); w.WriteF32(y); w.WriteF32(z); w.WriteU32(0); } public static UInt32 PackNormal(float x, float y, float z) { float invl = 127.5F; var xb = (byte)(x*invl + 127.5); var yb = (byte)(y*invl + 127.5); var zb = (byte)(z*invl + 127.5); return ((UInt32)xb) + ((UInt32)yb << 8) + ((UInt32)zb << 16); } public static float UnpackNormal(UInt32 packed, int dim) { byte b = (byte)((packed >> (dim * 8)) & 0xff); return (((float)b) - 127.5f) / 127.5f; } }; struct Mat4x4 : IRW4Struct { public float[] m; public uint Size() { return 16 * 4; } public void Read(Stream s) { m = new float[16]; for (int i = 0; i < m.Length; i++) m[i] = s.ReadF32(); } public void Write(Stream s) { foreach (var f in m) s.WriteF32(f); } }; struct Mat4x3 : IRW4Struct { public float[] m; public uint Size() { return 12 * 4; } public void Read(Stream s) { m = new float[12]; for (int i = 0; i < m.Length; i++) m[i] = s.ReadF32(); } public void Write(Stream s) { foreach (var f in m) s.WriteF32(f); } }; class Buffer<T> : RW4Object, IEnumerable<T> where T : IRW4Struct, new() { public const uint type_code = 0x10030; static uint Tsize = (new T()).Size(); T[] items; public Buffer(int size) { items = new T[size]; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return ((IEnumerable<T>)this).GetEnumerator(); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { foreach (var t in items) yield return t; } public T this[int index] { get { return items[index]; } set { items[index] = value; } } public int Length { get { return items.Length; } set { var v = new T[value]; for(int i=0; i<value && i<items.Length; i++) v[i] = items[i]; items = v; } } public void Assign(IList<T> data) { items = data.ToArray(); } public override int ComputeSize() { return (int)(Tsize * items.Length); } public override void Read(RW4Model m, RW4Section s, Stream r) { if (s.type_code != type_code) throw new ModelFormatException(r, "VB000 Bad type code", s.type_code); for (int i = 0; i < items.Length; i++) items[i].Read(r); } public override void Write(RW4Model m, RW4Section s, Stream w) { for (int i = 0; i < items.Length; i++) items[i].Write(w); } }; class Matrices<T> : RW4Object where T : IRW4Struct, new() { static int Tsize = (int)(new T()).Size(); public T[] items; public override void Read(RW4Model m, RW4Section s, Stream r) { var p1 = r.ReadU32(); var count = r.ReadU32(); r.expect(0, "MS001"); /// These bytes are padding to 16 bytes, but this structure is itself always aligned r.expect(0, "MS002"); if (p1 != r.Position) throw new ModelFormatException(r, "MS001", p1); items = new T[count]; for (int i = 0; i < count; i++) items[i].Read(r); } public override void Write(RW4Model m, RW4Section s, Stream w) { var p1 = (uint)w.Position + 16; w.WriteU32(p1); w.WriteU32((uint)items.Length); w.WriteU32(0); w.WriteU32(0); foreach (var i in items) i.Write(w); } public override int ComputeSize() { return 16 + Tsize * items.Length; } }; class Matrices4x4 : Matrices<Mat4x4> { public const int type_code = 0x70003; }; class Matrices4x3 : Matrices<Mat4x3> { public const int type_code = 0x7000f; }; class RW4TriangleArray : RW4Object { public const int type_code = 0x20007; public Buffer<Triangle> triangles; public uint unk1; public override int ComputeSize() { return 4 * 7; } public override void Read(RW4Model m, RW4Section s, Stream r) { if (s.type_code != type_code) throw new ModelFormatException(r, "TA000 Bad type code", s.type_code); unk1 = r.ReadU32(); r.expect(0, "TA001"); var ind_count = r.ReadU32(); r.expect(8, "TA002"); r.expect(101, "TA003"); r.expect(4, "TA004"); var section_number = r.ReadS32(); if (ind_count % 3 != 0) throw new ModelFormatException(r, "TA010", ind_count); var tri_count = ind_count / 3; var section = m.Sections[section_number]; section.LoadObject(m, triangles = new Buffer<Triangle>((int)tri_count), r); } public override void Write(RW4Model m, RW4Section s, Stream w) { w.WriteU32(unk1); w.WriteU32(0); w.WriteU32((uint)triangles.Length * 3); w.WriteU32(8); w.WriteU32(101); w.WriteU32(4); w.WriteU32(triangles.section.number); } } class RW4VertexArray : RW4Object { public const uint type_code = 0x20005; public VertexFormat format; // Vertex format? public UInt32 unk2; // Dangling pointer from data structure?? public Buffer<Vertex> vertices; public override void Read(RW4Model m, RW4Section s, Stream r) { if (s.type_code != type_code) throw new ModelFormatException(r, "VA000 Bad type code", s.type_code); var section_1 = r.ReadS32(); this.unk2 = r.ReadU32(); r.expect(0, "VA001"); var vcount = r.ReadU32(); r.expect(8, "VA002"); var vertex_size = r.ReadU32(); if (vertex_size != Vertex.size) throw new ModelFormatException(r, "VA100 Unsupported vertex size", vertex_size); var section_number = r.ReadS32(); var section = m.Sections[section_number]; section.LoadObject(m, vertices=new Buffer<Vertex>((int)vcount), r); section = m.Sections[section_1]; if (section.type_code != VertexFormat.type_code) throw new ModelFormatException(r, "VA101 Bad section type code", section.type_code); section.GetObject(m, r, out format); } public override void Write(RW4Model m, RW4Section s, Stream w) { w.WriteU32(this.format.section.number); w.WriteU32(this.unk2); w.WriteU32(0); w.WriteU32((uint)vertices.Length); w.WriteU32(8); w.WriteU32(Vertex.size); w.WriteU32(vertices.section.number); } public override int ComputeSize() { return 4 * 7; } }; class RW4BBox : RW4Object { public const int type_code = 0x80005; //< When found alone. Also used in RW4SimpleMesh public float minx, miny, minz; public float maxx, maxy, maxz; public uint unk1, unk2; public bool IsIdentical (RW4BBox b) { return minx == b.minx && miny == b.miny && minz == b.minz && maxx == b.maxx && maxy == b.maxy && maxz == b.maxz && unk1 == b.unk1 && unk2 == b.unk2; } public override void Read(RW4Model m, RW4Section s, Stream r) { minx = r.ReadF32(); miny = r.ReadF32(); minz = r.ReadF32(); unk1 = r.ReadU32(); maxx = r.ReadF32(); maxy = r.ReadF32(); maxz = r.ReadF32(); unk2 = r.ReadU32(); if (minx > maxx || miny > maxy || minz > maxz) throw new ModelFormatException(r,"BBOX011",null); } public override void Write(RW4Model m, RW4Section s, Stream w) { w.WriteF32(minx); w.WriteF32(miny); w.WriteF32(minz); w.WriteU32(unk1); w.WriteF32(maxx); w.WriteF32(maxy); w.WriteF32(maxz); w.WriteU32(unk2); } public override int ComputeSize() { return 4 * 8; } }; class RW4SimpleMesh : RW4Object { public const int type_code = 0x80003; RW4BBox bbox = new RW4BBox(); uint unk1; public Vertex[] vertices; public Triangle[] triangles; uint[] unknown_data_2; public override void Read(RW4Model m, RW4Section s, Stream r) { var p0 = r.Position; bbox.Read(m, null, r); r.expect(0xd59208, "SM001"); // most but not all creature models this.unk1 = r.ReadU32(); var tri_count = r.ReadU32(); r.expect(0, "SM002"); var vertexcount = r.ReadU32(); var p2 = r.ReadU32(); var p1 = r.ReadU32(); var p4 = r.ReadU32(); var p3 = r.ReadU32(); if (p1 != (uint)((r.Position + 15) & ~15)) throw new ModelFormatException(r, "SM010", null); r.ReadPadding(p1 - r.Position); if (p2 != p1 + vertexcount * 16) throw new ModelFormatException(r, "SM101", null); if (p3 != p2 + tri_count * 16) throw new ModelFormatException(r, "SM102", null); if (p4 != p3 + (((tri_count/2)+15)&~15)) throw new ModelFormatException(r, "SM103", null); vertices = new Vertex[vertexcount]; for (int i = 0; i < vertexcount; i++) vertices[i].Read4(r); triangles = new Triangle[tri_count]; for (int t = 0; t < tri_count; t++) { var index = r.ReadU32(); if (index >= vertexcount) throw new ModelFormatException(r, "SM200", t); triangles[t].i = (UInt16)index; index = r.ReadU32(); if (index >= vertexcount) throw new ModelFormatException(r, "SM200", t); triangles[t].j = (UInt16)index; index = r.ReadU32(); if (index >= vertexcount) throw new ModelFormatException(r, "SM200", t); triangles[t].k = (UInt16)index; r.expect(0, "SM201"); } UInt32 x = 0; for (int t = 0; t < tri_count; t++) { if ((t & 7) == 0) x = r.ReadU32(); triangles[t].unk1 = (byte)((x >> ((t & 7) * 4)) & 0xf); } for (int t = (int)tri_count; t < ((tri_count + 7) & ~7); t++) if ((byte)((x >> ((t & 7) * 4)) & 0xf) != 0xf) throw new ModelFormatException(r, "SM210", t); r.ReadPadding(p4 - r.Position); //if (r.Position != p4) throw new ModelFormatException(r, "SM299", r.Position - p4); r.expect(p1 - 8 * 4, "SM301"); var u2_count = r.ReadU32(); r.expect(tri_count, "SM302"); r.expect(0, "SM303"); var bbox2 = new RW4BBox(); bbox2.Read(m, null, r); if (!bbox.IsIdentical(bbox2)) throw new ModelFormatException(r, "SM310", bbox2); unknown_data_2 = new uint[u2_count * 8]; // Actually this is int*6 + float*2 for (int i = 0; i < unknown_data_2.Length; i++) unknown_data_2[i] = r.ReadU32(); } public override void Write(RW4Model m, RW4Section s, Stream w) { var tri_count = triangles.Length; bbox.Write(m, null, w); w.WriteU32(0xd59208); w.WriteU32(this.unk1); w.WriteS32(tri_count); w.WriteU32(0); w.WriteS32(vertices.Length); long p1 = (w.Position + 4*4 + 15) & ~15; var p4 = p1 + vertices.Length * 16 + tri_count * 16 + (((tri_count / 2) + 15) & ~15); w.WriteU32((uint)(p1 + vertices.Length * 16)); w.WriteU32((uint)p1); w.WriteU32((uint)p4); w.WriteU32((uint)(p1 + vertices.Length * 16 + tri_count * 16)); w.WritePadding(p1 - w.Position); for (int i = 0; i < vertices.Length; i++) vertices[i].Write4(w); for (int t = 0; t < tri_count; t++) { w.WriteU32(triangles[t].i); w.WriteU32(triangles[t].j); w.WriteU32(triangles[t].k); w.WriteU32(0); } UInt32 pack = 0; for (int t = 0; t < tri_count; t++) { pack |= ((UInt32)triangles[t].unk1) << ((t & 7) * 4); if ((t & 7) == 7) { w.WriteU32(pack); pack = 0; } } for (int t = (int)tri_count; t < ((tri_count + 7) & ~7); t++) { pack |= 0xfU << ((t & 7) * 4); if ((t & 7) == 7) w.WriteU32(pack); } w.WritePadding(p4 - w.Position); w.WriteU32((uint)(p1 - 8 * 4)); w.WriteU32((uint)(unknown_data_2.Length / 8)); w.WriteU32((uint)tri_count); w.WriteU32(0); bbox.Write(m, null, w); w.WriteU32s(unknown_data_2); } }; class RW4Mesh : RW4Object { public const int type_code = 0x20009; public RW4VertexArray vertices = null; public RW4TriangleArray triangles = null; uint vert_count, tri_count; public override void Read(RW4Model m, RW4Section s, Stream r) { // TODO: some files have multiple meshes referencing the same vertex and/or triangle buffers r.expect(40, "ME001"); r.expect(4, "ME002"); var tri_section = r.ReadS32(); this.tri_count = r.ReadU32(); r.expect(1, "ME003"); r.expect(0, "ME004"); r.expect(tri_count * 3, "ME005"); r.expect(0, "ME006"); this.vert_count = r.ReadU32(); var vert_section = r.ReadS32(); m.Sections[tri_section].GetObject(m, r, out triangles); if (triangles.triangles.Length != tri_count) throw new ModelFormatException(r, "ME100 Triangle count mismatch", new KeyValuePair<uint,int>(tri_count,triangles.triangles.Length)); if (vert_section != 0x400000) { m.Sections[vert_section].GetObject(m, r, out vertices); if (vertices.vertices.Length != vert_count) throw new ModelFormatException(r, "ME200 Vertex count mismatch", new KeyValuePair<uint,int>(vert_count,vertices.vertices.Length)); } } public override void Write(RW4Model m, RW4Section s, Stream w) { if (vertices != null) vert_count = (uint)vertices.vertices.Length; if (triangles != null) tri_count = (uint)triangles.triangles.Length; w.WriteU32(40); w.WriteU32(4); w.WriteU32(triangles.section.number); w.WriteU32(tri_count); w.WriteU32(1); w.WriteU32(0); w.WriteU32(tri_count * 3); w.WriteU32(0); w.WriteU32(vert_count); w.WriteU32(vertices.section.number); } public override int ComputeSize() { return 4 * 10; } }; class Texture : RW4Object { public const int type_code = 0x20003; public const int DXT5 = 0x35545844; // 'DXT5' public TextureBlob texData; public UInt32 textureType; public UInt32 unk1; //< dead pointer? public UInt16 width, height; public UInt32 mipmapInfo; // 0x708 for 64x64 (7 mipmap levels); 0x808 for 128x128 (8 mipmap levels) public override void Read(RW4Model m, RW4Section s, Stream r) { if (s.type_code != type_code) throw new ModelFormatException(r, "T000", s.type_code); textureType = r.ReadU32(); r.expect(8, "T001"); unk1 = r.ReadU32(); width = r.ReadU16(); height = r.ReadU16(); mipmapInfo = r.ReadU32(); r.expect(0, "T002"); r.expect(0, "T003"); var sec = r.ReadS32(); m.Sections[sec].GetObject(m, r, out texData); } public override void Write(RW4Model m, RW4Section s, Stream w) { w.WriteU32(textureType); w.WriteU32(8); w.WriteU32(unk1); w.WriteU16(width); w.WriteU16(height); w.WriteU32(mipmapInfo); w.WriteU32(0); w.WriteU32(0); w.WriteU32(texData.section.number); } public override int ComputeSize() { return 4 * 7 + 2 * 2; } }; class RW4TexMetadata : RW4Object { public const int type_code = 0x2000b; public Texture texture; public byte[] unk_data_1; public Int32[] unk_data_2 = new Int32[36]; public override void Read(RW4Model m, RW4Section s, Stream r) { if (s.type_code != type_code) throw new ModelFormatException(r, "TM000", s.type_code); // This section is hard to really decode because it is almost constant across different models! var p = (long)s.size - (unk_data_2.Length) * 4 - 4; if (p < 0) throw new ModelFormatException(r, "TM001", p); unk_data_1 = r.ReadBytes((int)p); var sn = r.ReadS32(); for (int i = 0; i < unk_data_2.Length; i++) unk_data_2[i] = r.ReadS32(); m.Sections[sn].GetObject(m, r, out texture); } public override void Write(RW4Model m, RW4Section s, Stream w) { w.Write(unk_data_1, 0, unk_data_1.Length); w.WriteU32(texture.section.number); for (int i = 0; i < unk_data_2.Length; i++) w.WriteS32(unk_data_2[i]); } public override int ComputeSize() { return unk_data_1.Length + 4 + unk_data_2.Length * 4; } }; class RWMeshMaterialAssignment : RW4Object { public const int type_code = 0x2001a; public RW4Mesh mesh; public RW4TexMetadata[] mat; public override void Read(RW4Model m, RW4Section s, Stream r) { var sn1 = r.ReadS32(); var count = r.ReadU32(); // always exactly 1, so I am guessing var sns = new Int32[count]; for (int i = 0; i < count; i++) sns[i] = r.ReadS32(); m.Sections[sn1].GetObject(m, r, out mesh); mat = new RW4TexMetadata[count]; for (int i = 0; i < count; i++) m.Sections[sns[i]].GetObject(m, r, out mat[i]); } public override void Write(RW4Model m, RW4Section s, Stream w) { w.WriteU32(mesh.section.number); w.WriteU32((uint)mat.Length); foreach (var x in mat) w.WriteU32(x.section.number); } public override int ComputeSize() { return 8 + 4 * mat.Length; } }; class RW4Material : RW4Object { public const int type_code = 0x7000b; public RW4TexMetadata tex; public RW4HierarchyInfo names; //< Always a size 1 hierarchy information? (same type as RW4Skeleton.jointInfo) public UInt32 unk1; public override void Read(RW4Model m, RW4Section s, Stream r) { if (s.type_code != type_code) throw new ModelFormatException(r, "MT000", s.type_code); r.expect(0x400000, "MT001"); r.expect(unk1=0x63ffb0, "MT002"); //< TODO: Not universal, but not sure other decoding is robust with other values r.expect((uint)r.Position + 16, "MT003"); r.expect(0x400000, "MT004"); var s1 = r.ReadS32(); r.expect(1, "MT005"); var s2 = r.ReadS32(); r.expect(0, "MT006"); m.Sections[s1].GetObject(m, r, out names); m.Sections[s2].GetObject(m, r, out tex); if (names.items.Length != 1) throw new ModelFormatException(r, "MT100", names.items.Length); } public override void Write(RW4Model m, RW4Section s, Stream w) { w.WriteU32(0x400000); w.WriteU32(unk1); w.WriteU32((uint)w.Position + 16); w.WriteU32(0x400000); w.WriteU32(names.section.number); w.WriteU32(1); w.WriteU32(tex.section.number); w.WriteS32(0); } public override int ComputeSize() { return 4 * 8; } }; class RW4HierarchyInfo : RW4Object { public const int type_code = 0x70002; public class Item { public int index; public UInt32 name_fnv; // e.g. "joint1".fnv() public UInt32 flags; // probably; values are all 0 to 3. &1 might be "leaf" public Item parent; }; public Item[] items; public UInt32 id; // hash or guid, referenced by Anim to specify which bones to animate? public override void Read(RW4Model m, RW4Section s, Stream r) { if (s.type_code != type_code) throw new ModelFormatException(r, "HI000", s.type_code); var p2 = r.ReadU32(); var p3 = r.ReadU32(); var p1 = r.ReadU32(); var c1 = r.ReadU32(); id = r.ReadU32(); r.expect(c1, "HI001"); if (p1 != r.Position) throw new ModelFormatException(r, "HI010", p1); if (p2 != p1 + 4*c1) throw new ModelFormatException(r, "HI011", p2); if (p3 != p1 + 8*c1) throw new ModelFormatException(r, "HI012", p3); items = new Item[c1]; for(int i=0; i<c1; i++) items[i] = new Item { index = i, name_fnv = r.ReadU32() }; for(int i=0; i<c1; i++) items[i].flags = r.ReadU32(); for (int i = 0; i < c1; i++) { var pind = r.ReadS32(); if (pind == -1) items[i].parent = null; else items[i].parent = items[pind]; } } public override void Write(RW4Model m, RW4Section s, Stream w) { var c1 = (uint)items.Length; var p1 = (uint)w.Position + 6*4; w.WriteU32(p1 + 4 * c1); w.WriteU32(p1 + 8 * c1); w.WriteU32(p1); w.WriteU32(c1); w.WriteU32(id); w.WriteU32(c1); for (int i = 0; i < c1; i++) w.WriteU32(items[i].name_fnv); for (int i = 0; i < c1; i++) w.WriteU32(items[i].flags); for (int i = 0; i < c1; i++) w.WriteS32(items[i].parent==null ? -1 : items[i].parent.index); } public override int ComputeSize() { return 4 * 6 + 12 * items.Length; } }; class RW4Skeleton : RW4Object { public const int type_code = 0x7000c; public Matrices4x3 mat3; public Matrices4x4 mat4; public RW4HierarchyInfo jointInfo; public UInt32 unk1; public override void Read(RW4Model m, RW4Section s, Stream r) { if (s.type_code != type_code) throw new ModelFormatException(r, "SK000", s.type_code); r.expect(0x400000, "SK001"); r.expect(unk1=0x8d6da0, "SK002"); //< TODO: Not universal, but not sure other decoding is robust with other values var sn1 = r.ReadS32(); var sn2 = r.ReadS32(); var sn3 = r.ReadS32(); m.Sections[sn1].GetObject(m, r, out mat3); m.Sections[sn2].GetObject(m, r, out jointInfo); m.Sections[sn3].GetObject(m, r, out mat4); } public override void Write(RW4Model m, RW4Section s, Stream w) { w.WriteU32(0x400000); w.WriteU32(unk1); w.WriteU32(mat3.section.number); w.WriteU32(jointInfo.section.number); w.WriteU32(mat4.section.number); } public override int ComputeSize() { return 4 * 5; } }; class RW4Blob : RW4Object { public byte[] blob; public long required_position = -1; protected virtual bool Relocatable() { return false; } public override void Read(RW4Model m, RW4Section s, Stream r) { if (!Relocatable()) this.required_position = r.Position; blob = r.ReadBytes((int)s.size); } public override void Write(RW4Model m, RW4Section s, Stream w) { if (this.required_position >= 0 && w.Position != this.required_position) throw new ModelFormatException(w, "Unable to move unknown section", null); w.Write(blob, 0, blob.Length); } public override int ComputeSize() { return blob.Length; } }; class UnreferencedSection : RW4Blob { }; class TextureBlob : RW4Blob { public const uint type_code = 0x10030; protected override bool Relocatable() { return true; } }; struct JointPose : IRW4Struct { public const uint size = 12 * 4; public float qx, qy, qz, qs; //< Quaternion rotation. qx*qx + qy*qy + qz*qz + qs*qs == 1.0 public float tx, ty, tz; //< Vector translation public float sx, sy, sz; //< Vector scale public float time; public uint Size() { return size; } public void Read(Stream s) { qx = s.ReadF32(); qy = s.ReadF32(); qz = s.ReadF32(); qs = s.ReadF32(); tx = s.ReadF32(); ty = s.ReadF32(); tz = s.ReadF32(); sx = s.ReadF32(); sy = s.ReadF32(); sz = s.ReadF32(); s.expect(0, "JP001"); time = s.ReadF32(); } public void Write(Stream s) { s.WriteF32(qx); s.WriteF32(qy); s.WriteF32(qz); s.WriteF32(qs); s.WriteF32(tx); s.WriteF32(ty); s.WriteF32(tz); s.WriteF32(sx); s.WriteF32(sy); s.WriteF32(sz); s.WriteU32(0); s.WriteF32(time); } }; class Anim : RW4Object { public const int type_code = 0x70001; public UInt32 skeleton_id; // matches Skeleton.jointInfo.id (or something else sometimes!) public float length; // seconds? public UInt32 flags; // probably; generally 0-3 public UInt32[] channel_names; // duplicate Skeleton.jointInfo, I believe public JointPose[,] channel_frame_pose; public UInt32 padding; public override void Read(RW4Model m, RW4Section s, Stream r) { if (s.type_code != type_code) throw new ModelFormatException(r, "AN000", s.type_code); var p1 = r.ReadU32(); var channels = r.ReadU32(); skeleton_id = r.ReadU32(); r.expect(0, "AN001"); //< Usually zero.. always <= 10. Maybe a count of something? var p3 = r.ReadU32(); var p4 = r.ReadU32(); r.expect(channels, "AN002"); r.expect(0, "AN003"); length = r.ReadF32(); r.expect(12, "AN010"); flags = r.ReadU32(); var p2 = r.ReadU32(); if (p1 != r.Position) throw new ModelFormatException(r, "AN100", p1); if (p2 != p1 + channels * 4) throw new ModelFormatException(r, "AN101", p2); if (p3 != p2 + channels * 12) throw new ModelFormatException(r, "AN102", p3); //var keyframe_count = (p4 - p3) / (channels * JointPose.size * 3); uint keyframe_count = 0; channel_names = new UInt32[channels]; for (int i = 0; i < channels; i++) channel_names[i] = r.ReadU32(); for (int i = 0; i < channels; i++) { var p = r.ReadU32() - (12*4 + channels*4 + channels*12); var pose_size = r.ReadU32(); var pose_components = r.ReadU32(); if (pose_components != 0x601 || pose_size != JointPose.size) throw new ModelFormatException(r, "AN200 Pose format not supported", pose_components); if (i == 1) keyframe_count = p / JointPose.size; else if (i >= 1 && p != i * JointPose.size * keyframe_count) throw new ModelFormatException(r, "AN201", null); } if (channels == 1) keyframe_count = (p4 - p3) / (channels * JointPose.size); // Yuck! This is just a guess. channel_frame_pose = new JointPose[ channels, keyframe_count ]; for(int c=0; c<channels; c++) for (int f = 0; f < keyframe_count; f++) { channel_frame_pose[c, f].Read(r); if (channels == 1 && channel_frame_pose[c, f].time == length) { // We had to guess about the length, so now fix our guess :-( keyframe_count = (uint)f + 1; var t = new JointPose[channels, keyframe_count]; for (int c1 = 0; c1 < channels; c1++) for (int f1 = 0; f1 < keyframe_count; f1++) t[c1, f1] = channel_frame_pose[c1, f1]; channel_frame_pose = t; break; } } padding = p4 - p3 - channels * keyframe_count * JointPose.size; r.ReadPadding( padding ); //< Huge number of zeros very common } public override void Write(RW4Model m, RW4Section s, Stream w) { var channels = (uint)channel_names.Length; var keyframe_count = (uint)channel_frame_pose.GetLength(1); var p1 = (uint)w.Position + 12 * 4; w.WriteU32(p1); w.WriteU32(channels); w.WriteU32(skeleton_id); w.WriteU32(0); w.WriteU32(p1 + channels * 4 + channels * 12); w.WriteU32(p1 + channels * 4 + channels * 12 + channels * keyframe_count * JointPose.size + padding); w.WriteU32(channels); w.WriteU32(0); w.WriteF32(length); w.WriteU32(12); w.WriteU32(flags); w.WriteU32(p1 + channels * 4); w.WriteU32s(channel_names); for (int i = 0; i < channels; i++) { w.WriteU32((uint)(12*4 + channels*4 + channels*12 + i*JointPose.size*keyframe_count)); w.WriteU32(JointPose.size); w.WriteU32(0x601); } for (int c = 0; c < channels; c++) for (int f = 0; f < keyframe_count; f++) channel_frame_pose[c, f].Write(w); w.WritePadding(padding); } public override int ComputeSize() { var channels = channel_names.Length; var keyframe_count = channel_frame_pose.GetLength(1); return (int) (12 * 4 + channels * 4 + channels * 12 + channels * keyframe_count * JointPose.size + padding); } }; class Animations : RW4Blob { public const int type_code = 0xff0001; protected override bool Relocatable() { return true; } }; class ModelHandles : RW4Blob { public const int type_code = 0xff0000; protected override bool Relocatable() { return true; } // almost certainly }; class VertexFormat : RW4Blob { public const int type_code = 0x20004; protected override bool Relocatable() { return true; } // almost certainly }; public class RW4Section { public UInt32 number; public UInt32 pos; public UInt32 size; public UInt32 alignment; public UInt32 type_code; public UInt32 type_code_indirect; //< Index into header.section_types table public RW4Object obj; public List<UInt32> fixup_offsets = new List<UInt32>(); //< Something is inserted here at load time?? public void LoadHeader( Stream r, UInt32 number, UInt32 index_end ) { this.number = number; pos = r.ReadU32(); r.expect(0, "H201"); size = r.ReadU32(); alignment = r.ReadU32(); this.type_code_indirect = r.ReadU32(); this.type_code = r.ReadU32(); if (type_code == 0x10030) pos += index_end; } public void WriteHeader(Stream w, UInt32 index_end) { w.WriteU32(pos - (type_code==0x10030 ? index_end : 0)); w.WriteU32(0); w.WriteU32(size); w.WriteU32(alignment); w.WriteU32(type_code_indirect); w.WriteU32(type_code); } public void GetObject<T>(RW4Model model, Stream r, out T o) where T : RW4Object, new() { if (obj != null) { o = (T)obj; return; } o = new T(); LoadObject(model, o, r); } public void LoadObject(RW4Model model, RW4Object o, Stream r) { if (obj != null) throw new ModelFormatException(r, "Attempt to decode section twice.", number); long start = r.Position; obj = o; o.section = this; r.Seek(pos, SeekOrigin.Begin); obj.Read(model, this, r); if (r.Position != pos + size) throw new ModelFormatException(r, "Section incompletely read.", number); var cs = obj.ComputeSize(); if (cs != -1 && cs != size) throw new ModelFormatException(r, "Section size doesn't match computed size.", number); r.Seek(start, SeekOrigin.Begin); } public void Write(Stream w, RW4Model model) { w.WritePadding(pos - w.Position); obj.Write(model, this, w); if (w.Position != pos + size) throw new ModelFormatException(w, "Section incompletely written.", number); } }; class RW4Header { //"\x89RW4w32\x00\r\n\x1a\n\x00 \x04\x00454\x00000\x00\x00\x00\x00\x00"; readonly byte[] RW4_Magic = new byte[] { 137, 82, 87, 52, 119, 51, 50, 0, 13, 10, 26, 10, 0, 32, 4, 0, 52, 53, 52, 0, 48, 48, 48, 0, 0, 0, 0, 0 }; readonly UInt32[] fixed_section_types = new UInt32[] { 0, 0x10030, 0x10031, 0x10032, 0x10010 }; public RW4Model.FileTypes file_type; public UInt32 unknown_bits_030; public UInt32 section_index_begin; public UInt32 section_index_padding; public UInt32 section_index_end { get { return (uint)(section_index_begin + 6 * 4 * sections.Length + 8 * getFixupCount() + section_index_padding); } } public RW4Section[] sections = new RW4Section[0]; private uint getFixupCount() { uint total = 0; foreach (var s in sections) total += (uint)s.fixup_offsets.Count; return total; } public void Read(System.IO.Stream r) { var b = r.ReadBytes(RW4_Magic.Length); for (int i = 0; i < b.Length; i++) if (b[i] != RW4_Magic[i]) throw new ModelFormatException(r, "Not a RW4 file", b); var file_type_code = r.ReadU32(); if (file_type_code == 1) file_type = RW4Model.FileTypes.Model; else if (file_type_code == 0x04000000) file_type = RW4Model.FileTypes.Texture; else throw new ModelFormatException(r, "Unknown file type", file_type_code); var ft_const1 = (file_type == RW4Model.FileTypes.Model ? 16U : 4U); var section_count = r.ReadU32(); r.expect(section_count, "H001 Section count not repeated"); r.expect(ft_const1, "H002"); r.expect(0, "H003"); section_index_begin = r.ReadU32(); var first_header_section_begin = r.ReadU32(); // Always 0x98? r.expect(new UInt32[] {0, 0, 0}, "H010"); var section_index_end1 = r.ReadU32(); r.expect(ft_const1, "H011"); //this.unknown_size_or_offset_013 = r.ReadU32(); var file_size = r.ReadU32() + section_index_end1; if (r.Length != file_size) throw new ModelFormatException(r, "H012", file_size); //< TODO r.expect(new UInt32[]{4,0,1,0,1}, "H020"); this.unknown_bits_030 = r.ReadU32(); r.expect(new UInt32[] { 4, 0, 1, 0, 1 }, "H040"); r.expect(new UInt32[] { 0, 1, 0, 0, 0, 0, 0 }, "H041"); if (r.Position != 0x98) throw new ModelFormatException(r, "H099", r.Position); r.Seek(first_header_section_begin, SeekOrigin.Begin); r.expect(0x10004, "H140"); // Offsets of header sections relative to the 0x10004. 4, 12, 28, 28 + (12+4*section_type_count), ... + 36, ... + 28 var offsets = new UInt32[6]; for (int i = 0; i < offsets.Length; i++) offsets[i] = r.ReadU32() + first_header_section_begin; // A list of section types in the file? If so, redundant with section index if (offsets[2] != r.Position) throw new ModelFormatException(r, "H145", r.Position); r.expect(0x10005, "H150"); var count = r.ReadU32(); r.expect(12, "H151"); var section_types = new UInt32[count]; for (int i = 0; i < count; i++) section_types[i] = r.ReadU32(); if (offsets[3] != r.Position) throw new ModelFormatException(r, "H146", r.Position); r.expect(0x10006, "H160"); // TODO: I think this is actually a variable length structure, with 12 byte header and 3 being the length in qwords r.expect(new UInt32[] { 3, 0x18, file_type_code, 0xffb00000, file_type_code, 0, 0, 0 }, "H161" ); if (offsets[4] != r.Position) throw new ModelFormatException(r, "H147", r.Position); r.expect(0x10007, "H170"); var fixup_count = r.ReadU32(); r.expect(0, "H171"); r.expect(0, "H172"); // Fixup index always immediately follows section index r.expect(section_index_begin + section_count * 24 + fixup_count * 8, "H173"); r.expect(section_index_begin + section_count * 24, "H174"); r.expect(fixup_count, "H176"); if (offsets[5] != r.Position) throw new ModelFormatException(r, "H148", r.Position); r.expect(0x10008, "H180"); r.expect(new UInt32[] { 0, 0 }, "H181"); r.Seek(section_index_begin,SeekOrigin.Begin); this.sections = new RW4Section[section_count]; for (uint i = 0; i < section_count; i++) { this.sections[i] = new RW4Section(); this.sections[i].LoadHeader(r, i, section_index_end1); } for (int i = 0; i < fixup_count; i++) { var sind = r.ReadU32(); var offset = r.ReadU32(); this.sections[sind].fixup_offsets.Add(offset); } section_index_padding = section_index_end1 - (uint)r.Position; r.ReadPadding(section_index_padding); bool[] used = new bool[section_types.Length]; foreach (var s in sections) { used[s.type_code_indirect] = true; if (section_types[s.type_code_indirect] != s.type_code) throw new ModelFormatException(r, "H300", s.type_code_indirect); } for (int i = 0; i < fixed_section_types.Length; i++) if (section_types[i] != fixed_section_types[i]) throw new ModelFormatException(r, "H301", i); for (int i = fixed_section_types.Length; i < section_types.Length; i++) if (!used[i]) throw new ModelFormatException(r, "H302", section_types[i]); } private UInt32[] getSectionTypes() { Dictionary<UInt32, UInt32> stype = new Dictionary<uint, uint>(); for (uint i = 0; i < fixed_section_types.Length; i++) stype[fixed_section_types[i]] = i; for (int i = 0; i < sections.Length; i++) if (!stype.TryGetValue(sections[i].type_code, out sections[i].type_code_indirect)) stype.Add(sections[i].type_code, sections[i].type_code_indirect = (uint)stype.Count); return (from i in stype orderby i.Value select i.Key).ToArray(); } public void Write(Stream w) { var section_types = getSectionTypes(); uint file_type_code = file_type == RW4Model.FileTypes.Model ? 1U : 0x04000000U; w.Write(RW4_Magic, 0, RW4_Magic.Length); w.WriteU32(file_type_code); w.WriteU32((uint)sections.Length); w.WriteU32((uint)sections.Length); var ft_const1 = (file_type == RW4Model.FileTypes.Model ? 16U : 4U); w.WriteU32(ft_const1); w.WriteU32(0); w.WriteU32(section_index_begin); w.WriteU32(0x98); // pointer to section 10004 w.WriteU32s(new UInt32[] { 0, 0, 0 }); w.WriteU32((uint)section_index_end); w.WriteU32(ft_const1); var file_end = section_index_end; foreach (var s in sections) if (s.pos + s.size > file_end) file_end = s.pos + s.size; w.WriteU32(file_end - section_index_end); w.WriteU32s(new UInt32[] { 4, 0, 1, 0, 1 }); w.WriteU32(this.unknown_bits_030); w.WriteU32s(new UInt32[] { 4, 0, 1, 0, 1 }); w.WriteU32s(new UInt32[] { 0, 1, 0, 0, 0, 0, 0 }); if (w.Position != 0x98) throw new ModelFormatException(w, "WH099", w.Position); w.WriteU32(0x10004); var hs_sizes = new UInt32[] { 4, 8, 16, 12 + 4 * (uint)section_types.Length, 36, 28 }; for (int i = 1; i < hs_sizes.Length; i++) hs_sizes[i] += hs_sizes[i - 1]; w.WriteU32s(hs_sizes); w.WriteU32(0x10005); w.WriteU32((uint)section_types.Length); w.WriteU32(12); w.WriteU32s(section_types); w.WriteU32(0x10006); w.WriteU32s(new UInt32[] { 3, 0x18, file_type_code, 0xffb00000, file_type_code, 0, 0, 0 }); w.WriteU32(0x10007); int fixup_count = 0; foreach (var s in sections) fixup_count += s.fixup_offsets.Count; w.WriteU32((uint)fixup_count); w.WriteU32(0); w.WriteU32(0); w.WriteU32((uint)(section_index_begin + sections.Length * 24 + fixup_count * 8)); w.WriteU32((uint)(section_index_begin + sections.Length * 24)); w.WriteU32((uint)fixup_count); w.WriteU32(0x10008); w.WriteU32s(new UInt32[] { 0, 0 }); } public void WriteIndex(Stream w) { if (w.Position != this.section_index_begin) throw new ModelFormatException(w, "WH200", null); foreach (var s in sections) s.WriteHeader(w, (uint)section_index_end); foreach (var s in sections) foreach (var f in s.fixup_offsets) { w.WriteU32(s.number); w.WriteU32(f); } w.WritePadding(section_index_end - w.Position); if (w.Position != section_index_end) throw new ModelFormatException(w, "WH299", w.Position); } public UInt32 GetHeaderEnd() { return 0x98 + 104 + 4 * (uint)getSectionTypes().Length + 12; } }; public class RW4Model { RW4Header header; public enum FileTypes { Model, Texture }; public IList<RW4Section> Sections { get { return header.sections; } } public FileTypes FileType { get { return header.file_type; } set { header.file_type = value; } } public RW4Model() { } public IList<RW4Object> GetObjects(UInt32 type_code) { return (from s in header.sections where s.type_code == type_code select s.obj).ToList(); } public void AddObject(RW4Object obj, UInt32 type_code) { obj.section = InsertSection(header.sections.Length); obj.section.type_code = type_code; obj.section.obj = obj; obj.section.alignment = 0x10; // by default } public void RemoveSection(RW4Section section) { if (header.sections[section.number] != section) throw new ArgumentException("Attempt to remove invalid section."); var new_sections = new RW4Section[header.sections.Length - 1]; for (int i = 0; i < section.number; i++) new_sections[i] = header.sections[i]; for (int i = (int)section.number; i < new_sections.Length; i++ ) { new_sections[i] = header.sections[i + 1]; new_sections[i].number = (uint)i; } header.sections = new_sections; section.number = 0xffffffff; } public RW4Section InsertSection(int index) { var new_sections = new RW4Section[header.sections.Length + 1]; for (int i = 0; i < index; i++) new_sections[i] = header.sections[i]; for (int i = index + 1; i < new_sections.Length; i++) { new_sections[i] = header.sections[i - 1]; new_sections[i].number = (uint)i; } var s = new_sections[index] = new RW4Section(); s.number = (uint)index; header.sections = new_sections; return s; } void Pack() { foreach (var s in header.sections) { var cs = s.obj.ComputeSize(); if (cs != -1) s.size = (uint)cs; } var sections = header.sections; //(from s in header.sections orderby s.pos select s).ToArray(); uint p; p = header.GetHeaderEnd(); for (int i = 0; i < sections.Length; i++) { if (sections[i].type_code == 0x10030) continue; var np = (p + sections[i].alignment - 1) & ~(sections[i].alignment - 1); if (sections[i].pos != np) { sections[i].pos = np; } p = sections[i].pos + sections[i].size; } header.section_index_begin = p; p = header.section_index_end; for (int i = 0; i < sections.Length; i++) { if (sections[i].type_code != 0x10030) continue; var np = (p + sections[i].alignment - 1) & ~(sections[i].alignment - 1); if (sections[i].pos != np) { //System.Console.WriteLine(String.Format("Moving section {0} 0x{1:x} from 0x{2:x} to 0x{3:x}.", i, sections[i].type_code, sections[i].pos, np)); sections[i].pos = np; } p = sections[i].pos + sections[i].size; } } public void New() { header = new RW4Header(); } public void Read(System.IO.Stream r) { header = new RW4Header(); header.Read(r); foreach (var section in header.sections) { switch (section.type_code) { case RW4Mesh.type_code: { RW4Mesh t; section.GetObject(this, r, out t); break; } case RW4Material.type_code: { RW4Material t; section.GetObject(this, r, out t); break; } case RW4Skeleton.type_code: { RW4Skeleton t; section.GetObject(this, r, out t); break; } case Texture.type_code: { Texture t; section.GetObject(this, r, out t); break; } case RW4HierarchyInfo.type_code: { RW4HierarchyInfo t; section.GetObject(this, r, out t); break; } case RWMeshMaterialAssignment.type_code: { RWMeshMaterialAssignment t; section.GetObject(this, r, out t); break; } case RW4BBox.type_code: { RW4BBox b; section.GetObject(this, r, out b); break; } case ModelHandles.type_code: { ModelHandles t; section.GetObject(this, r, out t); break; } case Anim.type_code: { Anim t; section.GetObject(this, r, out t); break; } case Animations.type_code: { Animations t; section.GetObject(this, r, out t); break; } /*case Matrices4x4.type_code: { Matrices4x4 t; section.GetObject(this, r, out t); break; } case Matrices4x3.type_code: { Matrices4x3 t; section.GetObject(this, r, out t); break; }*/ } } foreach (var section in header.sections) if (section.obj == null) section.LoadObject( this, new UnreferencedSection(), r ); } public void Write(Stream w) { Pack(); header.Write(w); var sections = (from s in header.sections orderby s.pos select s).ToArray(); bool wrote_index = false; for(int i=0; i<sections.Length; i++) { sections[i].Write(w, this); if (wrote_index) continue; if (i + 1 == sections.Length || sections[i + 1].pos >= header.section_index_end) { w.WritePadding(header.section_index_begin - w.Position); header.WriteIndex(w); wrote_index = true; } } } public void Test() { } } }
39.457732
191
0.496333
[ "BSD-3-Clause" ]
Blackinator101/sporemaster
SporeMaster/SporeMaster/RenderWare4/RW4Model.cs
57,413
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.Consumption.V20190501Preview.Inputs { /// <summary> /// May be used to filter budgets by resource group, resource, or meter. /// </summary> public sealed class FiltersArgs : Pulumi.ResourceArgs { [Input("meters")] private InputList<string>? _meters; /// <summary> /// The list of filters on meters (GUID), mandatory for budgets of usage category. /// </summary> public InputList<string> Meters { get => _meters ?? (_meters = new InputList<string>()); set => _meters = value; } [Input("resourceGroups")] private InputList<string>? _resourceGroups; /// <summary> /// The list of filters on resource groups, allowed at subscription level only. /// </summary> public InputList<string> ResourceGroups { get => _resourceGroups ?? (_resourceGroups = new InputList<string>()); set => _resourceGroups = value; } [Input("resources")] private InputList<string>? _resources; /// <summary> /// The list of filters on resources. /// </summary> public InputList<string> Resources { get => _resources ?? (_resources = new InputList<string>()); set => _resources = value; } [Input("tags")] private InputMap<ImmutableArray<string>>? _tags; /// <summary> /// The dictionary of filters on tags. /// </summary> public InputMap<ImmutableArray<string>> Tags { get => _tags ?? (_tags = new InputMap<ImmutableArray<string>>()); set => _tags = value; } public FiltersArgs() { } } }
29.492958
91
0.578319
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Consumption/V20190501Preview/Inputs/FiltersArgs.cs
2,094
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. namespace System.Text.Json.Serialization.Converters { internal sealed class JsonConverterUInt16 : JsonConverter<ushort> { public override ushort Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return reader.GetUInt16(); } public override void Write(Utf8JsonWriter writer, ushort value, JsonSerializerOptions options) { writer.WriteNumberValue(value); } } }
34.2
113
0.703216
[ "MIT" ]
939481896/dotnet-corefx
src/System.Text.Json/src/System/Text/Json/Serialization/Converters/JsonValueConverterUInt16.cs
686
C#
using System; using System.Collections.Generic; using System.Text; namespace ShogiCore.Notation { /// <summary> /// 棋泉棋譜形式 /// </summary> public class KisenNotationReader : IBinaryNotationReader { #region IBinaryNotationReader メンバ public bool CanRead(byte[] data) { return data != null && data.Length % 512 == 0; } public IEnumerable<Notation> Read(byte[] data) { if (!CanRead(data)) { throw new NotationFormatException("棋泉棋譜データの読み込みに失敗しました"); } for (int i = 0; i < data.Length; i += 512) { Notation notation = LoadGame(data, i); if (notation == null) continue; yield return notation; } } #endregion /// <summary> /// 1ゲーム分の読み込み /// </summary> private unsafe Notation LoadGame(byte[] data, int i) { List<MoveDataEx> moves = new List<MoveDataEx>(); Piece* board = stackalloc Piece[82]; for (int j = 55; j <= 63; j++) board[j] = Piece.FU; for (int j = 19; j <= 27; j++) board[j] = Piece.EFU; board[73] = board[81] = Piece.KY; board[01] = board[9] = Piece.EKY; board[74] = board[80] = Piece.KE; board[02] = board[8] = Piece.EKE; board[75] = board[79] = Piece.GI; board[03] = board[07] = Piece.EGI; board[76] = board[78] = Piece.KI; board[04] = board[06] = Piece.EKI; board[71] = Piece.KA; board[11] = Piece.EKA; board[65] = Piece.HI; board[17] = Piece.EHI; board[77] = Piece.OU; board[05] = Piece.EOU; int** hand = stackalloc int*[2]; int* hand0 = stackalloc int[10]; int* hand1 = stackalloc int[10]; for (int j = 0; j < 10; j++) { hand0[j] = 0; hand1[j] = 0; } hand[0] = hand0; hand[1] = hand1; for (int j = 0; j < 512; j += 2) { int to = data[i + j]; if (to == 0x00 || to == 0xff) break; int from = data[i + j + 1]; if (from == 0x00 || from == 0xff) break; // 念のため。 // ※駒落ちなら1手目が0xffffらしい。IDXファイルも見ないとイカンので無視る。 int turn = moves.Count % 2; if (100 < from) { if (100 < to) break; // 裏返しに打っちゃった反則負け? // 持ち駒を使う手 // 飛車、角、金、銀、桂、香、歩の枚数? int k = 1; for (int sum = hand[turn][k]; ; sum += hand[turn][++k]) { if (from - 100 <= sum) break; } // kが1:飛車 2:角 3:金 4:銀 5:桂 6:香 7:歩 from = 100 + (8 - k); board[to] = (Piece)(8 - k); hand[turn][k]--; } else { int tt = 100 < to ? to - 100 : to; hand[turn][8 - (byte)(board[tt] & ~Piece.ENEMY)]++; board[tt] = board[from]; // 成るかどうかはここでは無視っちゃう。持ち駒の為の処理なので。 board[from] = Piece.EMPTY; } moves.Add(new MoveDataEx(new MoveData(from, to))); } if (moves.Count <= 0) { return null; } Notation notation = new Notation(); notation.Moves = moves.ToArray(); //notation.Winner = (moves.Count % 2) ^ 1; // 最後の手を指した方が勝者とする。(反則とかもあるのだが…) notation.Winner = -1; return notation; } #if false 564 名無し名人 : 02/11/12 14:55 ID:t7xodq8d -NUM- -R.DATE- -R.TIME- -SENDER- -CONTENTS- 00337 95-12-23 22:09:31 SHOP0008 棋泉6.0データ形式 棋泉(Version6.0)データ形式を公開いたします。5.6x形式からは上位互換性が あります。 ---------------------------- 棋泉(Version6.0)データ形式 ---------------------------- 棋泉データは拡張子"kif"と"idx"の2つのデータファイルからなっている: 1.KIFファイル   ◎機能:棋譜データ(手順)を格納する。   ◎1レコード(1局分のデータ)=512バイトのランダムアクセスファイル   ◎1手のデータは2バイトから成っており、1手目から指し手の順に格納    されている。最大256手までの棋譜が登録できる。    1手のデータは「元位置」、「移動先」からなる。       F E D C B A 9 8 7 6 5 4 3 2 1 0 (bit) ・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・ ・ ・ ・ ・ ・ ・ ・ ・ ・ ・ ・ ・ ・ ・ ・ ・ ・ ・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・       <------ 元位置 -------> <------ 移動先 -------> 565 名無し名人 : 02/11/12 14:56 ID:t7xodq8d  (1)元位置データ    ① 1~ 81の場合:盤上の駒の位置を意味する。               盤の位置の対応は以下のとおり。         9  8  7  6  5  4  3  2  1 ・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・ ・ 9 ・ 8 ・ 7 ・ 6 ・ 5 ・ 4 ・ 3 ・ 2 ・ 1 ・ 一 ・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・ ・ 18 ・ 17 ・ 16 ・ 15 ・ 14 ・ 13 ・ 12 ・ 11 ・ 10 ・ 二 ・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・ ・ 27 ・ 26 ・ 25 ・ 24 ・ 23 ・ 22 ・ 21 ・ 20 ・ 19 ・ 三 ・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・ ・ 36 ・ 35 ・ 34 ・ 33 ・ 32 ・ 31 ・ 30 ・ 29 ・ 28 ・ 四 ・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・ ・ 45 ・ 44 ・ 43 ・ 42 ・ 41 ・ 40 ・ 39 ・ 38 ・ 37 ・ 五 ・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・ 566 名無し名人 : 02/11/12 14:57 ID:t7xodq8d ・ 54 ・ 53 ・ 52 ・ 51 ・ 50 ・ 49 ・ 48 ・ 47 ・ 46 ・ 六 ・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・ ・ 63 ・ 62 ・ 61 ・ 60 ・ 59 ・ 58 ・ 57 ・ 56 ・ 55 ・ 七 ・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・ ・ 72 ・ 71 ・ 70 ・ 69 ・ 68 ・ 67 ・ 66 ・ 65 ・ 64 ・ 八 ・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・ ・ 81 ・ 80 ・ 79 ・ 78 ・ 77 ・ 76 ・ 75 ・ 74 ・ 73 ・ 九 ・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・    ②101~134の場合:持ち駒を使用したことを意味する     1から34までの持ち駒リストの位置を示す。持ち駒リストの中     では駒は飛、角、金、銀、桂、香、歩の順でソートされている。     例えば、持ち駒リストに       角金金桂香歩歩歩     とあった場合104は4番目の持ち駒:つまり桂を意味する。 567 名無し名人 : 02/11/12 14:57 ID:t7xodq8d  (2)移動先データ    ①  1~ 81の場合:移動先の盤上の位置を意味する。                盤の位置の対応は前述のとおり。    ②101~181の場合:移動先で駒が「成った」ことを意味する。                位置は-100した1~81を意味する。 568 名無し名人 : 02/11/12 14:58 ID:t7xodq8d 2.IDXファイル   ◎機能:棋士名・対局日・棋戦名などの管理情報を格納する。    1レコード=32バイト(16ワード)のランダムアクセスファイル    第1レコードの先頭4バイト(Intel形式:Little Endian)には登録されて    いる棋譜数が格納されている。       0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 (Word) ・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・ ・ ・ ・ ・ ・ ・ ・ ・ ・ ・ ・ ・ ・ ・ ・ ・ ・ ・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・       <---> <--------------- 未使用 ----------------> | +-----棋譜数(4byte) 569 名無し名人 : 02/11/12 14:58 ID:t7xodq8d    第2レコード以降のレコードは下図のようにワード単位で使用されて    いる:       0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 (Word) ・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・ ・ ・ ・ ・ ・ ・ ・ ・ ・ ・ ・ ・ ・ ・ ・ ・ ・ ・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・        | | | | | | | | | | | <---未使用---> | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | +----手合い割りコード | | | | | | | | | +---上位バイト:先手戦型番号 | | | | | | | | | 下位バイト:後手戦型番号 | | | | | | | | +--- 終局コード | | | | | | | +--- 戦型番号 | | | | | | +------ 日 | | | | | +--------- 月 | | | | +------------ 年 | | | +--------------- 局 | | +------------------ 棋戦名番号 | +--------------------- 後手棋士番号 +------------------------ 先手棋士番号    第2レコードから各棋譜の情報が入っている。    棋譜番号nの情報は第(n+1)レコードに格納されている。    従って、KIFファイルの第nレコードには、IDXファイルの第(n+1)レコード    が対応している。 570 名無し名人 : 02/11/12 14:58 ID:t7xodq8d   ◎終局コード    0:手数の偶奇(パリティ)で勝負を決める(Ver4.1形式)    1:まで先手勝ち    2:まで後手勝ち    3:まで千日手    4:まで持将棋    5:以下先手勝ち(256手を越える棋譜に使用)    6:以下後手勝ち(  〃     〃   )    7:以下千日手 (  〃     〃   )    8:以下持将棋 (  〃     〃   )   ◎手合い割りコード    0:平手    1:香落ち    2:角落ち    3:飛車落ち    4:飛香落ち    5:2枚落ち    6:4枚落ち    7:6枚落ち   ◎駒落ち棋譜の1手目のデータは0xffffとし使用しない。    (上手の第1手は2手目として記録する。) -・-・-・-・-・-・-・-・-・-・-・-・-・-・-・-・-・-・-・-・-・-・-・-・-・-・-・-・-・-・-・-・-・- 571 名無し名人 : 02/11/12 14:59 ID:t7xodq8d   棋泉5.6x形式との相違点    (1) 棋譜数:2byte(65535局)→ 4byte(2^31-1局)に拡張      昔の棋譜データでは第2ワード(3,4byte目)にゴミが入っている      可能性があるので当面(60000局を越えるまで)それは強制的にゼ      ロにすること。 (2) 駒落ち棋譜対応 Dec.23,1995SHOP0008 かかし -NUM- -R.DATE- -R.TIME- -SENDER- -CONTENTS- 572 名無し名人 : 02/11/12 15:00 ID:t7xodq8d と、以上です。 7年前ですがネット駒音で作者が公開されていました。 #endif /// <summary> /// 王が4段目以上に進入した棋譜なのかどうかを調べる。 /// </summary> public static unsafe bool IsNyuugyokuNotation(byte[] data, int i) { Piece* board = stackalloc Piece[82]; for (int j = 55; j <= 63; j++) board[j] = Piece.FU; for (int j = 19; j <= 27; j++) board[j] = Piece.EFU; board[73] = board[81] = Piece.KY; board[01] = board[9] = Piece.EKY; board[74] = board[80] = Piece.KE; board[02] = board[8] = Piece.EKE; board[75] = board[79] = Piece.GI; board[03] = board[07] = Piece.EGI; board[76] = board[78] = Piece.KI; board[04] = board[06] = Piece.EKI; board[71] = Piece.KA; board[11] = Piece.EKA; board[65] = Piece.HI; board[17] = Piece.EHI; board[77] = Piece.OU; board[05] = Piece.EOU; int** hand = stackalloc int*[2]; int* hand0 = stackalloc int[10]; int* hand1 = stackalloc int[10]; for (int j = 0; j < 10; j++) { hand0[j] = 0; hand1[j] = 0; } hand[0] = hand0; hand[1] = hand1; for (int j = 0, turn = 0; j < 512; j += 2, turn ^= 1) { int to = data[i + j]; if (to == 0x00 || to == 0xff) break; int from = data[i + j + 1]; if (from == 0x00 || from == 0xff) break; // 念のため。 // ※駒落ちなら1手目が0xffffらしい。IDXファイルも見ないとイカンので無視る。 if (100 < from) { if (100 < to) break; // 裏返しに打っちゃった反則負け? // 持ち駒を使う手 // 飛車、角、金、銀、桂、香、歩の枚数? int k = 1; for (int sum = hand[turn][k]; ; sum += hand[turn][++k]) { if (from - 100 <= sum) break; } // kが1:飛車 2:角 3:金 4:銀 5:桂 6:香 7:歩 board[to] = (Piece)(8 - k); hand[turn][k]--; } else { int tt = 100 < to ? to - 100 : to; hand[turn][8 - (byte)(board[tt] & ~Piece.ENEMY)]++; board[tt] = board[from]; // 成るかどうかはここでは無視っちゃう。持ち駒の為の処理なので。 board[from] = Piece.EMPTY; // 進入した? if ((board[tt] == Piece.OU && tt <= 36) || (board[tt] == Piece.EOU && 46 <= tt)) { return true; } } } // 進入しなかった return false; } } }
32.489552
87
0.395075
[ "MIT" ]
ak110/ShogiCore
ShogiCore/Notation/KisenNotationReader.cs
16,294
C#
using Parkner.Mobile.Services; using Parkner.Mobile.ViewModels; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace Parkner.Mobile.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class ClienteEstacionamientosVerPage : ContentPage { public ClienteEstacionamientosVerPage(string id) { this.InitializeComponent(); this.BindingContext = Dependencia.Obtener<ClienteEstacionamientosVerViewModel>(id); } } }
26.210526
95
0.726908
[ "MIT" ]
Bedolla/Parkner
Parkner.Mobile/Parkner.Mobile/Views/ClienteEstacionamientosVerPage.xaml.cs
500
C#
//------------------------------------------------------------------------------ // <auto-generated> // Dieser Code wurde von einem Tool generiert. // Laufzeitversion:4.0.30319.42000 // // Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn // der Code erneut generiert wird. // </auto-generated> //------------------------------------------------------------------------------ using NMF.Collections.Generic; using NMF.Collections.ObjectModel; using NMF.Expressions; using NMF.Expressions.Linq; using NMF.Models; using NMF.Models.Collections; using NMF.Models.Expressions; using NMF.Models.Meta; using NMF.Models.Repository; using NMF.Serialization; using NMF.Utilities; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Linq; using TTC2017.SmartGrids.SubstationStandard.Enumerations; namespace TTC2017.SmartGrids.SubstationStandard.Dataclasses { /// <summary> /// The public interface for Sequence /// </summary> [DefaultImplementationTypeAttribute(typeof(Sequence))] [XmlDefaultImplementationTypeAttribute(typeof(Sequence))] public interface ISequence : IModelElement { /// <summary> /// The val property /// </summary> Nullable<SequenceKind> Val { get; set; } /// <summary> /// Gets fired before the Val property changes its value /// </summary> event System.EventHandler<ValueChangedEventArgs> ValChanging; /// <summary> /// Gets fired when the Val property changed its value /// </summary> event System.EventHandler<ValueChangedEventArgs> ValChanged; } }
28.9375
96
0.62473
[ "MIT" ]
georghinkel/ttc2017smartGrids
generator/61850/Dataclasses/ISequence.cs
1,854
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Enemy : MonoBehaviour { private Animator animator; private int idleHash = Animator.StringToHash("Idle"); private int attackHash = Animator.StringToHash("Attack"); private int dieHash = Animator.StringToHash("Die"); private int blockHash = Animator.StringToHash("Block"); public ParticleSystem attackPS; // Use this for initialization void Start () { animator = GetComponent<Animator>(); } // Update is called once per frame void Update () { } public void HitHero() { GameObject.Find("ObstacleManager").GetComponent<CombatManager>().HeroHitByEnemy(); } public void Attack() { animator.SetTrigger(attackHash); } public void Idle() { animator.SetTrigger(idleHash); } public void Die() { animator.SetTrigger(dieHash); } public void Block() { animator.SetTrigger(blockHash); } public void StartAttackEffect() { attackPS.Play(); } public void StopAttackEffect() { attackPS.Stop(); } }
19.581818
86
0.688951
[ "MIT" ]
ElBruh/CDN_Game
Assets/Scripts/Enemy.cs
1,079
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using UniDi; namespace UniDi.Internal { public static class Assert { #if UNIDI_STRIP_ASSERTS_IN_BUILDS [Conditional("UNITY_EDITOR")] #endif public static void That(bool condition) { if (!condition) throw CreateException("Assert hit!"); } #if UNIDI_STRIP_ASSERTS_IN_BUILDS [Conditional("UNITY_EDITOR")] #endif public static void IsNotEmpty(string str) { if (string.IsNullOrEmpty(str)) throw CreateException("Unexpected null or empty string"); } #if UNIDI_STRIP_ASSERTS_IN_BUILDS [Conditional("UNITY_EDITOR")] #endif // This is better because IsEmpty with IEnumerable causes a memory alloc public static void IsEmpty<T>(IList<T> list) { if (list.Count != 0) throw CreateException( "Expected collection to be empty but instead found '{0}' elements", list.Count); } #if UNIDI_STRIP_ASSERTS_IN_BUILDS [Conditional("UNITY_EDITOR")] #endif public static void IsEmpty<T>(IEnumerable<T> sequence) { if (!sequence.IsEmpty()) throw CreateException("Expected collection to be empty but instead found '{0}' elements", sequence.Count()); } #if UNIDI_STRIP_ASSERTS_IN_BUILDS [Conditional("UNITY_EDITOR")] #endif public static void IsType<T>(object obj) { IsType<T>(obj, ""); } #if UNIDI_STRIP_ASSERTS_IN_BUILDS [Conditional("UNITY_EDITOR")] #endif public static void IsType<T>(object obj, string message) { if (!(obj is T)) throw CreateException( "Assert Hit! {0}\nWrong type found. Expected '{1}' (left) but found '{2}' (right). ", message, typeof(T).PrettyName(), obj.GetType().PrettyName()); } #if UNIDI_STRIP_ASSERTS_IN_BUILDS [Conditional("UNITY_EDITOR")] #endif public static void DerivesFrom<T>(Type type) { if (!type.DerivesFrom<T>()) throw CreateException("Expected type '{0}' to derive from '{1}'", type.Name, typeof(T).Name); } #if UNIDI_STRIP_ASSERTS_IN_BUILDS [Conditional("UNITY_EDITOR")] #endif public static void DerivesFromOrEqual<T>(Type type) { if (!type.DerivesFromOrEqual<T>()) throw CreateException("Expected type '{0}' to derive from or be equal to '{1}'", type.Name, typeof(T).Name); } #if UNIDI_STRIP_ASSERTS_IN_BUILDS [Conditional("UNITY_EDITOR")] #endif public static void DerivesFrom(Type childType, Type parentType) { if (!childType.DerivesFrom(parentType)) throw CreateException("Expected type '{0}' to derive from '{1}'", childType.Name, parentType.Name); } #if UNIDI_STRIP_ASSERTS_IN_BUILDS [Conditional("UNITY_EDITOR")] #endif public static void DerivesFromOrEqual(Type childType, Type parentType) { if (!childType.DerivesFromOrEqual(parentType)) throw CreateException("Expected type '{0}' to derive from or be equal to '{1}'", childType.Name, parentType.Name); } // Use AssertEquals to get better error output (with values) #if UNIDI_STRIP_ASSERTS_IN_BUILDS [Conditional("UNITY_EDITOR")] #endif public static void IsEqual(object left, object right) { IsEqual(left, right, ""); } // Use AssertEquals to get better error output (with values) #if UNIDI_STRIP_ASSERTS_IN_BUILDS [Conditional("UNITY_EDITOR")] #endif public static void IsEqual(object left, object right, Func<string> messageGenerator) { if (!Equals(left, right)) { left = left ?? "<NULL>"; right = right ?? "<NULL>"; throw CreateException("Assert Hit! {0}. Expected '{1}' (left) but found '{2}' (right). ", messageGenerator(), left, right); } } #if UNIDI_STRIP_ASSERTS_IN_BUILDS [Conditional("UNITY_EDITOR")] #endif public static void IsApproximately(float left, float right, float epsilon = 0.00001f) { var isEqual = Math.Abs(left - right) < epsilon; if (!isEqual) throw CreateException("Assert Hit! Expected '{0}' (left) but found '{1}' (right). ", left, right); } // Use AssertEquals to get better error output (with values) #if UNIDI_STRIP_ASSERTS_IN_BUILDS [Conditional("UNITY_EDITOR")] #endif public static void IsEqual(object left, object right, string message) { if (!Equals(left, right)) { left = left ?? "<NULL>"; right = right ?? "<NULL>"; throw CreateException("Assert Hit! {0}\nExpected '{1}' (left) but found '{2}' (right). ", message, left, right); } } // Use Assert.IsNotEqual to get better error output (with values) #if UNIDI_STRIP_ASSERTS_IN_BUILDS [Conditional("UNITY_EDITOR")] #endif public static void IsNotEqual(object left, object right) { IsNotEqual(left, right, ""); } // Use Assert.IsNotEqual to get better error output (with values) #if UNIDI_STRIP_ASSERTS_IN_BUILDS [Conditional("UNITY_EDITOR")] #endif public static void IsNotEqual(object left, object right, Func<string> messageGenerator) { if (Equals(left, right)) { left = left ?? "<NULL>"; right = right ?? "<NULL>"; throw CreateException("Assert Hit! {0}. Expected '{1}' (left) to differ from '{2}' (right). ", messageGenerator(), left, right); } } #if UNIDI_STRIP_ASSERTS_IN_BUILDS [Conditional("UNITY_EDITOR")] #endif public static void IsNull(object val) { if (val != null) throw CreateException( "Assert Hit! Expected null pointer but instead found '{0}'", val); } #if UNIDI_STRIP_ASSERTS_IN_BUILDS [Conditional("UNITY_EDITOR")] #endif public static void IsNull(object val, string message) { if (val != null) throw CreateException( "Assert Hit! {0}", message); } // We don't use params here to avoid the memory alloc #if UNIDI_STRIP_ASSERTS_IN_BUILDS [Conditional("UNITY_EDITOR")] #endif public static void IsNull(object val, string message, object p1) { if (val != null) throw CreateException( "Assert Hit! {0}", message.Fmt(p1)); } #if UNIDI_STRIP_ASSERTS_IN_BUILDS [Conditional("UNITY_EDITOR")] #endif public static void IsNotNull(object val) { if (val == null) throw CreateException("Assert Hit! Found null pointer when value was expected"); } #if UNIDI_STRIP_ASSERTS_IN_BUILDS [Conditional("UNITY_EDITOR")] #endif public static void IsNotNull(object val, string message) { if (val == null) throw CreateException("Assert Hit! {0}", message); } // We don't use params here to avoid the memory alloc #if UNIDI_STRIP_ASSERTS_IN_BUILDS [Conditional("UNITY_EDITOR")] #endif public static void IsNotNull(object val, string message, object p1) { if (val == null) throw CreateException("Assert Hit! {0}", message.Fmt(p1)); } // We don't use params here to avoid the memory alloc #if UNIDI_STRIP_ASSERTS_IN_BUILDS [Conditional("UNITY_EDITOR")] #endif public static void IsNotNull(object val, string message, object p1, object p2) { if (val == null) throw CreateException("Assert Hit! {0}", message.Fmt(p1, p2)); } #if UNIDI_STRIP_ASSERTS_IN_BUILDS [Conditional("UNITY_EDITOR")] #endif public static void IsNotEmpty<T>(IEnumerable<T> val, string message = "") { if (!val.Any()) throw CreateException("Assert Hit! Expected empty collection but found {0} values. {1}", val.Count(), message); } // Use Assert.IsNotEqual to get better error output (with values) #if UNIDI_STRIP_ASSERTS_IN_BUILDS [Conditional("UNITY_EDITOR")] #endif public static void IsNotEqual(object left, object right, string message) { if (Equals(left, right)) { left = left ?? "<NULL>"; right = right ?? "<NULL>"; throw CreateException("Assert Hit! {0}. Unexpected value found '{1}'. ", message, left); } } #if UNIDI_STRIP_ASSERTS_IN_BUILDS [Conditional("UNITY_EDITOR")] #endif public static void Warn(bool condition) { if (!condition) Log.Warn("Warning! See call stack"); } #if UNIDI_STRIP_ASSERTS_IN_BUILDS [Conditional("UNITY_EDITOR")] #endif public static void Warn(bool condition, Func<string> messageGenerator) { if (!condition) Log.Warn("Warning Assert hit! " + messageGenerator()); } #if UNIDI_STRIP_ASSERTS_IN_BUILDS [Conditional("UNITY_EDITOR")] #endif public static void That( bool condition, string message) { if (!condition) throw CreateException("Assert hit! " + message); } // We don't use params here to avoid the memory alloc #if UNIDI_STRIP_ASSERTS_IN_BUILDS [Conditional("UNITY_EDITOR")] #endif public static void That( bool condition, string message, object p1) { if (!condition) throw CreateException("Assert hit! " + message.Fmt(p1)); } // We don't use params here to avoid the memory alloc #if UNIDI_STRIP_ASSERTS_IN_BUILDS [Conditional("UNITY_EDITOR")] #endif public static void That( bool condition, string message, object p1, object p2) { if (!condition) throw CreateException("Assert hit! " + message.Fmt(p1, p2)); } // We don't use params here to avoid the memory alloc #if UNIDI_STRIP_ASSERTS_IN_BUILDS [Conditional("UNITY_EDITOR")] #endif public static void That( bool condition, string message, object p1, object p2, object p3) { if (!condition) throw CreateException("Assert hit! " + message.Fmt(p1, p2, p3)); } #if UNIDI_STRIP_ASSERTS_IN_BUILDS [Conditional("UNITY_EDITOR")] #endif public static void Warn(bool condition, string message) { if (!condition) Log.Warn("Warning Assert hit! " + message); } #if UNIDI_STRIP_ASSERTS_IN_BUILDS [Conditional("UNITY_EDITOR")] #endif public static void Throws(Action action) { Throws<Exception>(action); } #if UNIDI_STRIP_ASSERTS_IN_BUILDS [Conditional("UNITY_EDITOR")] #endif public static void Throws<TException>(Action action) where TException : Exception { try { action(); } catch (TException) { return; } throw CreateException( "Expected to receive exception of type '{0}' but nothing was thrown", typeof(TException).Name); } public static UniDiException CreateException() { return new UniDiException("Assert hit!"); } public static UniDiException CreateException(string message) { return new UniDiException(message); } public static UniDiException CreateException(string message, params object[] parameters) { return new UniDiException(message.Fmt(parameters)); } public static UniDiException CreateException(Exception innerException, string message, params object[] parameters) { return new UniDiException(message.Fmt(parameters), innerException); } } }
32.717678
120
0.587823
[ "Apache-2.0" ]
UniDi/UniDi
Source/Internal/Assert.cs
12,400
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Accounting.Core.Accounts; using Accounting.Core.TaxCodes; using Accounting.Core.Jobs; using Accounting.Core.Activities; using Accounting.Core.Inventory; using Accounting.Bll; using Accounting.Bll.Purchases.PurchaseLines; namespace SyntechRpt.WinForms.Purchases.PurchaseLines { public partial class FrmTimeBillingPurchaseLine : Form { private BOTimeBillingPurchaseLine mModel = null; public BOTimeBillingPurchaseLine Model { set { mModel = value; } get { return mModel; } } public FrmTimeBillingPurchaseLine() { InitializeComponent(); } private void btnOK_Click(object sender, EventArgs e) { mModel.Activity = (Activity)cboActivity.SelectedItem; mModel.Notes = txtNotes.Text; mModel.TaxCode = (TaxCode)cboTax.SelectedItem; mModel.Job = (Job)cboJob.SelectedItem; mModel.LineDate = dtpLineDate.Value; mModel.HoursUnits = double.Parse(txtHoursUnits.Text); mModel.Rate = double.Parse(txtRate.Text); mModel.Location = (Location)cboLocation.SelectedItem; mModel.EstimatedCost = double.Parse(txtEstimatedCost.Text); OpResult result = mModel.Revise(); if (!result.IsValid) { DialogResult = DialogResult.None; MessageBox.Show(result.Error); } } private void FrmTimeBillingPurchaseLine_Load(object sender, EventArgs e) { cboActivity.DataSource = mModel.List("Activity"); cboTax.DataSource = mModel.List("TaxCode"); cboJob.DataSource = mModel.List("Job"); cboLocation.DataSource = mModel.List("Location"); cboActivity.SelectedItem = mModel.Activity; cboTax.SelectedItem = mModel.TaxCode; if (mModel.LineDate != null) { mModel.LineDate = dtpLineDate.Value; } cboJob.SelectedItem = mModel.Job; cboLocation.SelectedItem = mModel.Location; txtNotes.Text = mModel.Notes; txtRate.Text = string.Format("{0}", mModel.Rate); txtHoursUnits.Text = string.Format("{0}", mModel.HoursUnits); txtEstimatedCost.Text = string.Format("{0}", mModel.EstimatedCost); } private void cboActivity_SelectedIndexChanged(object sender, EventArgs e) { Activity _obj = (Activity)cboActivity.SelectedItem; if (_obj == null) { txtRate.Text = string.Format("{0}", 0); cboTax.SelectedIndex = -1; return; } cboTax.SelectedItem = _obj.TaxCode; txtHoursUnits.Text = string.Format("{0}", 1); txtRate.Text = string.Format("{0}", _obj.ActivityRate); txtNotes.Text = _obj.ActivityDescription; } } }
33.298969
81
0.593808
[ "MIT" ]
cschen1205/myob-accounting-plugin
Inventorist/SyntechRpt/WinForms/Purchases/PurchaseLines/FrmTimeBillingPurchaseLine.cs
3,232
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 System.Reflection; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.UseThrowExpression { /// <summary> /// Looks for patterns of the form: /// <code> /// if (a == null) { /// throw SomeException(); /// } /// /// x = a; /// </code> /// /// and offers to change it to /// /// <code> /// x = a ?? throw SomeException(); /// </code> /// /// Note: this analyzer can be updated to run on VB once VB supports 'throw' /// expressions as well. /// </summary> internal abstract class AbstractUseThrowExpressionDiagnosticAnalyzer : AbstractCodeStyleDiagnosticAnalyzer { protected AbstractUseThrowExpressionDiagnosticAnalyzer() : base(IDEDiagnosticIds.UseThrowExpressionDiagnosticId, new LocalizableResourceString(nameof(FeaturesResources.Use_throw_expression), FeaturesResources.ResourceManager, typeof(FeaturesResources)), new LocalizableResourceString(nameof(FeaturesResources.Null_check_can_be_simplified), FeaturesResources.ResourceManager, typeof(FeaturesResources))) { } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticDocumentAnalysis; public override bool OpenFileOnly(Workspace workspace) => false; protected abstract bool IsSupported(ParseOptions options); protected override void InitializeWorker(AnalysisContext context) { context.RegisterCompilationStartAction(startContext => { var expressionTypeOpt = startContext.Compilation.GetTypeByMetadataName("System.Linq.Expressions.Expression`1"); startContext.RegisterOperationAction(operationContext => AnalyzeOperation(operationContext, expressionTypeOpt), OperationKind.Throw); }); } private void AnalyzeOperation(OperationAnalysisContext context, INamedTypeSymbol expressionTypeOpt) { var syntaxTree = context.Operation.Syntax.SyntaxTree; if (!IsSupported(syntaxTree.Options)) { return; } var cancellationToken = context.CancellationToken; var throwOperation = (IThrowOperation)context.Operation; var throwStatementSyntax = throwOperation.Syntax; var compilation = context.Compilation; var semanticModel = compilation.GetSemanticModel(throwStatementSyntax.SyntaxTree); var ifOperation = GetContainingIfOperation( semanticModel, throwOperation, cancellationToken); // This throw statement isn't parented by an if-statement. Nothing to // do here. if (ifOperation == null) { return; } if (ifOperation.WhenFalse != null) { // Can't offer this if the 'if-statement' has an 'else-clause'. return; } var options = context.Options; var optionSet = options.GetDocumentOptionSetAsync(syntaxTree, cancellationToken).GetAwaiter().GetResult(); if (optionSet == null) { return; } var option = optionSet.GetOption(CodeStyleOptions.PreferThrowExpression, throwStatementSyntax.Language); if (!option.Value) { return; } var semanticFacts = GetSemanticFactsService(); if (semanticFacts.IsInExpressionTree(semanticModel, throwStatementSyntax, expressionTypeOpt, cancellationToken)) { return; } var containingBlock = semanticModel.GetOperation(ifOperation.Syntax.Parent, cancellationToken) as IBlockOperation; if (containingBlock == null) { return; } if (!TryDecomposeIfCondition(ifOperation, out var localOrParameter)) { return; } if (!TryFindAssignmentExpression(containingBlock, ifOperation, localOrParameter, out var expressionStatement, out var assignmentExpression)) { return; } if (!localOrParameter.GetSymbolType().CanAddNullCheck()) { return; } // We found an assignment using this local/parameter. Now, just make sure there // were no intervening accesses between the check and the assignment. if (ValueIsAccessed( semanticModel, ifOperation, containingBlock, localOrParameter, expressionStatement, assignmentExpression)) { return; } // Ok, there were no intervening writes or accesses. This check+assignment can be simplified. var allLocations = ImmutableArray.Create( ifOperation.Syntax.GetLocation(), throwOperation.Exception.Syntax.GetLocation(), assignmentExpression.Value.Syntax.GetLocation()); var descriptor = GetDescriptorWithSeverity(option.Notification.Value); context.ReportDiagnostic( Diagnostic.Create(descriptor, throwStatementSyntax.GetLocation(), additionalLocations: allLocations)); // Fade out the rest of the if that surrounds the 'throw' exception. var tokenBeforeThrow = throwStatementSyntax.GetFirstToken().GetPreviousToken(); var tokenAfterThrow = throwStatementSyntax.GetLastToken().GetNextToken(); context.ReportDiagnostic( Diagnostic.Create(UnnecessaryWithSuggestionDescriptor, Location.Create(syntaxTree, TextSpan.FromBounds( ifOperation.Syntax.SpanStart, tokenBeforeThrow.Span.End)), additionalLocations: allLocations)); if (ifOperation.Syntax.Span.End > tokenAfterThrow.Span.Start) { context.ReportDiagnostic( Diagnostic.Create(UnnecessaryWithSuggestionDescriptor, Location.Create(syntaxTree, TextSpan.FromBounds( tokenAfterThrow.Span.Start, ifOperation.Syntax.Span.End)), additionalLocations: allLocations)); } } private static bool ValueIsAccessed(SemanticModel semanticModel, IConditionalOperation ifOperation, IBlockOperation containingBlock, ISymbol localOrParameter, IExpressionStatementOperation expressionStatement, IAssignmentOperation assignmentExpression) { var statements = containingBlock.Operations; var ifOperationIndex = statements.IndexOf(ifOperation); var expressionStatementIndex = statements.IndexOf(expressionStatement); if (expressionStatementIndex > ifOperationIndex + 1) { // There are intermediary statements between the check and the assignment. // Make sure they don't try to access the local. var dataFlow = semanticModel.AnalyzeDataFlow( statements[ifOperationIndex + 1].Syntax, statements[expressionStatementIndex - 1].Syntax); if (dataFlow.ReadInside.Contains(localOrParameter) || dataFlow.WrittenInside.Contains(localOrParameter)) { return true; } } // Also, have to make sure there is no read/write of the local/parameter on the left // of the assignment. For example: map[val.Id] = val; var exprDataFlow = semanticModel.AnalyzeDataFlow(assignmentExpression.Target.Syntax); return exprDataFlow.ReadInside.Contains(localOrParameter) || exprDataFlow.WrittenInside.Contains(localOrParameter); } protected abstract ISyntaxFactsService GetSyntaxFactsService(); protected abstract ISemanticFactsService GetSemanticFactsService(); private bool TryFindAssignmentExpression( IBlockOperation containingBlock, IConditionalOperation ifOperation, ISymbol localOrParameter, out IExpressionStatementOperation expressionStatement, out IAssignmentOperation assignmentExpression) { var ifOperationIndex = containingBlock.Operations.IndexOf(ifOperation); // walk forward until we find an assignment of this local/parameter into // something else. for (var i = ifOperationIndex + 1; i < containingBlock.Operations.Length; i++) { expressionStatement = containingBlock.Operations[i] as IExpressionStatementOperation; if (expressionStatement == null) { continue; } assignmentExpression = expressionStatement.Operation as IAssignmentOperation; if (assignmentExpression == null) { continue; } if (!TryGetLocalOrParameterSymbol(assignmentExpression.Value, out var assignmentValue)) { continue; } if (!Equals(localOrParameter, assignmentValue)) { continue; } return true; } expressionStatement = null; assignmentExpression = null; return false; } private bool TryDecomposeIfCondition( IConditionalOperation ifStatement, out ISymbol localOrParameter) { localOrParameter = null; var condition = ifStatement.Condition; if (!(condition is IBinaryOperation binaryOperator)) { return false; } if (binaryOperator.OperatorKind != BinaryOperatorKind.Equals) { return false; } if (IsNull(binaryOperator.LeftOperand)) { return TryGetLocalOrParameterSymbol( binaryOperator.RightOperand, out localOrParameter); } if (IsNull(binaryOperator.RightOperand)) { return TryGetLocalOrParameterSymbol( binaryOperator.LeftOperand, out localOrParameter); } return false; } private bool TryGetLocalOrParameterSymbol( IOperation operation, out ISymbol localOrParameter) { if (operation is IConversionOperation conversion && conversion.IsImplicit) { return TryGetLocalOrParameterSymbol(conversion.Operand, out localOrParameter); } else if (operation is ILocalReferenceOperation localReference) { localOrParameter = localReference.Local; return true; } else if (operation is IParameterReferenceOperation parameterReference) { localOrParameter = parameterReference.Parameter; return true; } localOrParameter = null; return false; } private bool IsNull(IOperation operation) { return operation.ConstantValue.HasValue && operation.ConstantValue.Value == null; } private IConditionalOperation GetContainingIfOperation( SemanticModel semanticModel, IThrowOperation throwOperation, CancellationToken cancellationToken) { var throwStatement = throwOperation.Syntax; var containingOperation = semanticModel.GetOperation(throwStatement.Parent, cancellationToken); if (containingOperation is IBlockOperation block) { if (block.Operations.Length != 1) { // If we are in a block, then the block must only contain // the throw statement. return null; } // C# may have an intermediary block between the throw-statement // and the if-statement. Walk up one operation higher in that case. containingOperation = semanticModel.GetOperation(throwStatement.Parent.Parent, cancellationToken); } if (containingOperation is IConditionalOperation conditionalOperation) { return conditionalOperation; } return null; } } }
39.320475
260
0.605766
[ "Apache-2.0" ]
DaiMichael/roslyn
src/Features/Core/Portable/UseThrowExpression/AbstractUseThrowExpressionDiagnosticAnalyzer.cs
13,253
C#
#if UNITY_EDITOR //public class AkWwiseMenu_Linux //{ // private const string MENU_PATH = "Help/Wwise Help/"; // private const string Platform = "Linux"; // [UnityEditor.MenuItem(MENU_PATH + Platform, false, (int)AkWwiseHelpOrder.WwiseHelpOrder)] // public static void OpenDoc() { AkDocHelper.OpenDoc(Platform); } //} #endif // #if UNITY_EDITOR
31.454545
92
0.736994
[ "MIT" ]
Clement-R/ggj_2018
Assets/Wwise/Editor/WwiseMenu/Linux/AkWwiseMenu_Linux.cs
346
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using GrabNReadApp.Data.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace GrabNReadApp.Web.Areas.Identity.Pages.Account { [AllowAnonymous] public class LogoutModel : PageModel { private readonly SignInManager<GrabNReadAppUser> _signInManager; private readonly ILogger<LogoutModel> _logger; public LogoutModel(SignInManager<GrabNReadAppUser> signInManager, ILogger<LogoutModel> logger) { _signInManager = signInManager; _logger = logger; } public void OnGet() { } public async Task<IActionResult> OnPost(string returnUrl = null) { await _signInManager.SignOutAsync(); _logger.LogInformation("User logged out."); if (returnUrl != null) { return LocalRedirect(returnUrl); } else { return Page(); } } } }
27.636364
102
0.638158
[ "MIT" ]
alexandrateneva/CSharp-Web-SoftUni
CSharp MVC Frameworks - ASP.NET Core/GrabNReadApp - Final Project/GrabNReadApp/GrabNReadApp.Web/Areas/Identity/Pages/Account/Logout.cshtml.cs
1,218
C#
// Copyright (c) 2015-2017, Saritasa. All rights reserved. // Licensed under the BSD license. See LICENSE file in the project root for full license information. using System; #if NET40 using System.Runtime.Serialization; #endif namespace Saritasa.Tools.Domain.Exceptions { /// <summary> /// Domain conflict exception. Indicates that the request could not be /// processed because of conflict in the request, such as an edit conflict between multiple simultaneous updates. /// Can be mapped to 409 HTTP status code. /// </summary> #if NET40 [Serializable] #endif public class ConflictException : DomainException { /// <summary> /// .ctor /// </summary> public ConflictException() : base(DomainErrorDescriber.Default.Conflict()) { } /// <summary> /// .ctor /// </summary> public ConflictException(string message) : base(message) { } /// <summary> /// .ctor /// </summary> public ConflictException(string message, Exception innerException) : base(message, innerException) { } #if NET40 /// <summary> /// .ctor for deserialization. /// </summary> /// <param name="info">Stores all the data needed to serialize or deserialize an object.</param> /// <param name="context">Describes the source and destination of a given serialized stream, /// and provides an additional caller-defined context.</param> protected ConflictException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endif } }
30.017857
117
0.622844
[ "BSD-2-Clause" ]
jzabroski/SaritasaTools
src/Saritasa.Tools.Domain/Exceptions/ConflictException.cs
1,683
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.Management.Automation.Internal; namespace System.Management.Automation.ComInterop { /// <summary> /// Strongly-typed and parameterized exception factory. /// </summary> internal static partial class Error { /// <summary> /// InvalidOperationException with message like "Marshal.SetComObjectData failed." /// </summary> internal static Exception SetComObjectDataFailed() { return new InvalidOperationException(ParserStrings.SetComObjectDataFailed); } /// <summary> /// InvalidOperationException with message like "Unexpected VarEnum {0}." /// </summary> internal static Exception UnexpectedVarEnum(object p0) { return new InvalidOperationException(StringUtil.Format(ParserStrings.UnexpectedVarEnum, p0)); } /// <summary> /// System.Reflection.TargetParameterCountException with message like "Error while invoking {0}." /// </summary> internal static Exception DispBadParamCount(object p0, int parameterCount) { return new System.Reflection.TargetParameterCountException(StringUtil.Format(ParserStrings.DispBadParamCount, p0, parameterCount)); } /// <summary> /// MissingMemberException with message like "Error while invoking {0}." /// </summary> internal static Exception DispMemberNotFound(object p0) { return new MissingMemberException(StringUtil.Format(ParserStrings.DispMemberNotFound, p0)); } /// <summary> /// ArgumentException with message like "Error while invoking {0}. Named arguments are not supported." /// </summary> internal static Exception DispNoNamedArgs(object p0) { return new ArgumentException(StringUtil.Format(ParserStrings.DispNoNamedArgs, p0)); } /// <summary> /// OverflowException with message like "Error while invoking {0}." /// </summary> internal static Exception DispOverflow(object p0) { return new OverflowException(StringUtil.Format(ParserStrings.DispOverflow, p0)); } /// <summary> /// ArgumentException with message like "Could not convert argument {0} for call to {1}." /// </summary> internal static Exception DispTypeMismatch(object method, string value, string originalTypeName, string destinationTypeName) { return new ArgumentException(StringUtil.Format(ParserStrings.DispTypeMismatch, method, value, originalTypeName, destinationTypeName)); } /// <summary> /// ArgumentException with message like "Error while invoking {0}. A required parameter was omitted." /// </summary> internal static Exception DispParamNotOptional(object p0) { return new ArgumentException(StringUtil.Format(ParserStrings.DispParamNotOptional, p0)); } /// <summary> /// InvalidOperationException with message like "Cannot retrieve type information." /// </summary> internal static Exception CannotRetrieveTypeInformation() { return new InvalidOperationException(ParserStrings.CannotRetrieveTypeInformation); } /// <summary> /// ArgumentException with message like "IDispatch::GetIDsOfNames behaved unexpectedly for {0}." /// </summary> internal static Exception GetIDsOfNamesInvalid(object p0) { return new ArgumentException(StringUtil.Format(ParserStrings.GetIDsOfNamesInvalid, p0)); } /// <summary> /// InvalidOperationException with message like "Attempting to pass an event handler of an unsupported type." /// </summary> internal static Exception UnsupportedHandlerType() { return new InvalidOperationException(ParserStrings.UnsupportedHandlerType); } /// <summary> /// MissingMemberException with message like "Could not get dispatch ID for {0} (error: {1})." /// </summary> internal static Exception CouldNotGetDispId(object p0, object p1) { return new MissingMemberException(StringUtil.Format(ParserStrings.CouldNotGetDispId, p0, p1)); } /// <summary> /// System.Reflection.AmbiguousMatchException with message like "There are valid conversions from {0} to {1}." /// </summary> internal static Exception AmbiguousConversion(object p0, object p1) { return new System.Reflection.AmbiguousMatchException(StringUtil.Format(ParserStrings.AmbiguousConversion, p0, p1)); } } }
41
146
0.656282
[ "MIT" ]
10088/PowerShell
src/System.Management.Automation/engine/ComInterop/Errors.cs
4,879
C#
using System; namespace Day12 { class Program { public static int day = 12; public static string inputPath = "../../../input/input"; public static string inputPathTest = "../../../input/inputTest"; static void Main(string[] args) { Console.WriteLine("AOC 2021 Day " + day); Console.WriteLine("Solution Part 1:"); Console.WriteLine(Solver.SolvePart1(inputPath)); Console.WriteLine("Solution Part 2:"); Console.WriteLine(Solver.SolvePart2(inputPath)); Console.WriteLine("\nTests:"); var test1 = Solver.SolvePart1(inputPathTest); Console.WriteLine(test1); if (test1 == 10) Console.WriteLine("test 1 successful"); else Console.WriteLine("test 1 failed"); var test2 = Solver.SolvePart2(inputPathTest); Console.WriteLine(test2); if (test2 == 36) Console.WriteLine("test 2 successful"); else Console.WriteLine("test 2 failed"); Console.ReadLine(); } } }
35.466667
109
0.589286
[ "MIT" ]
TillDiebelt/AOC2021
src/Day12/Program.cs
1,066
C#
// Project: Daggerfall Tools For Unity // Copyright: Copyright (C) 2009-2020 Daggerfall Workshop // Web Site: http://www.dfworkshop.net // License: MIT License (http://www.opensource.org/licenses/mit-license.php) // Source Code: https://github.com/Interkarma/daggerfall-unity // Original Author: Gavin Clayton (interkarma@dfworkshop.net) // Contributors: // // Notes: // using DaggerfallConnect; namespace DaggerfallWorkshop.Game.MagicAndEffects.MagicEffects { /// <summary> /// Drain - Willpower /// </summary> public class DrainWillpower : DrainEffect { public static readonly string EffectKey = "Drain-Willpower"; public override void SetProperties() { properties.Key = EffectKey; properties.ClassicKey = MakeClassicKey(7, 2); properties.GroupName = TextManager.Instance.GetText("ClassicEffects", "drain"); properties.SubGroupName = TextManager.Instance.GetText("ClassicEffects", "willpower"); properties.SpellMakerDescription = DaggerfallUnity.Instance.TextProvider.GetRSCTokens(1521); properties.SpellBookDescription = DaggerfallUnity.Instance.TextProvider.GetRSCTokens(1221); properties.SupportMagnitude = true; properties.ShowSpellIcon = false; properties.AllowedTargets = EntityEffectBroker.TargetFlags_Other; properties.AllowedElements = EntityEffectBroker.ElementFlags_All; properties.AllowedCraftingStations = MagicCraftingStations.SpellMaker; properties.MagicSkill = DFCareer.MagicSkills.Destruction; properties.MagnitudeCosts = MakeEffectCosts(8, 100, 116); drainStat = DFCareer.Stats.Willpower; } } }
42.380952
104
0.686517
[ "MIT" ]
BibleUs/daggerfall-unity
Assets/Scripts/Game/MagicAndEffects/Effects/Destruction/DrainWillpower.cs
1,780
C#
using System.Net; using System.Net.Http; using System.Threading.Tasks; using Agoda.Frameworks.Http; using NUnit.Framework; using RichardSzalay.MockHttp; namespace Agoda.Frameworks.LoadBalancing.Tests { public class RandomUrlHttpClientTest { [Test] public async Task TestGetAsync() { var mockHttp = new MockHttpMessageHandler(); mockHttp.When(HttpMethod.Get, "http://test/*") .Respond(msg => { StringAssert.IsMatch("http://test/1|2/api/55", msg.RequestUri.AbsoluteUri); return new StringContent("ok"); }); var httpclient = mockHttp.ToHttpClient(); var client = new RandomUrlHttpClient( httpclient, new[] { "http://test/1", "http://test/2" }, null, 3, null); var res = await client.GetAsync("api/55"); var content = await res.Content.ReadAsStringAsync(); Assert.AreEqual("ok", content); } [Test] public async Task TestPostAsync() { var mockHttp = new MockHttpMessageHandler(); mockHttp.When(HttpMethod.Post, "http://test/*") .Respond(async (msg) => { Assert.AreEqual("55", await msg.Content.ReadAsStringAsync()); StringAssert.IsMatch("http://test/1|2/api/55", msg.RequestUri.AbsoluteUri); var resmsg = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("ok") }; return resmsg; }); var httpclient = mockHttp.ToHttpClient(); var client = new RandomUrlHttpClient( httpclient, new[] { "http://test/1", "http://test/2" }, null, 3, null); var res = await client.PostAsync("api/55", new StringContent("55")); var content = await res.Content.ReadAsStringAsync(); Assert.AreEqual("ok", content); } [Test] public void TestRetry() { var mockHttp = new MockHttpMessageHandler(); var counter = 0; mockHttp.When(HttpMethod.Post, "http://test/*") .Respond(msg => { counter++; Assert.LessOrEqual(counter, 3); return new HttpResponseMessage(HttpStatusCode.RequestTimeout); }); var httpclient = mockHttp.ToHttpClient(); var client = new RandomUrlHttpClient( httpclient, new[] { "http://test/1", "http://test/2" }, null, 3, null); Assert.ThrowsAsync<TransientHttpRequestException>( () => client.PostAsync("api/55", new StringContent("55"))); Assert.AreEqual(3, counter); } } }
33.347368
96
0.482955
[ "Apache-2.0" ]
szaboopeeter/net-loadbalancing
Agoda.Frameworks.Http.Tests/RandomUrlHttpClientTest.cs
3,168
C#
using GenFx.Wpf.Controls; using Moq; using OxyPlot; using OxyPlot.Axes; using OxyPlot.Series; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using TestCommon; using Xunit; namespace GenFx.Wpf.Tests { /// <summary> /// Contains unit tests for the <see cref="MetricsChart"/> class. /// </summary> public class MetricsChartTest { /// <summary> /// Tests that the ctor initializes the state correctly. /// </summary> [StaFact] public void MetricsChart_Ctor() { MetricsChart chart = new MetricsChart(); Assert.Null(chart.Population); Assert.Null(chart.Algorithm); Assert.Null(chart.SelectedMetrics); PlotModel model = chart.PlotModel; Assert.Equal(2, model.Axes.Count); Assert.IsType<LinearAxis>(model.Axes[0]); Assert.IsType<LinearAxis>(model.Axes[1]); } /// <summary> /// Tests that the chart refreshes when the algorithm changes from null. /// </summary> [StaFact] public void MetricsChart_OnAlgorithmChanged_FromNull() { TestPopulation population = new TestPopulation(); TestAlgorithm algorithm = new TestAlgorithm(); Metric metric1 = Mock.Of<Metric>(); List<MetricResult> metric1Results = new List<MetricResult> { new MetricResult(0, 0, 1, metric1), new MetricResult(0, 1, 2, metric1) }; metric1.GetResults(0).AddRange(metric1Results); Metric metric2 = Mock.Of<Metric>(); List<MetricResult> metric2Results = new List<MetricResult> { new MetricResult(0, 0, 3, metric1), new MetricResult(0, 1, 4, metric1) }; metric2.GetResults(0).AddRange(metric2Results); algorithm.Metrics.Add(metric1); algorithm.Metrics.Add(metric2); VerifyChartRefresh(chart => { chart.Population = population; }, chart => { chart.Algorithm = algorithm; }, (metric, series) => { if (metric == metric1) { Assert.Equal(metric1Results, (ICollection)series.ItemsSource); } else if (metric == metric2) { Assert.Equal(metric2Results, (ICollection)series.ItemsSource); } }); } /// <summary> /// Tests that the chart refreshes when the algorithm changes from a previous algorithm. /// </summary> [StaFact] public void MetricsChart_OnAlgorithmChanged_FromOtherAlgorithm() { TestPopulation population = new TestPopulation(); TestAlgorithm algorithm = new TestAlgorithm(); Metric metric1 = Mock.Of<Metric>(); List<MetricResult> metric1Results = new List<MetricResult> { new MetricResult(0, 0, 1, metric1), new MetricResult(0, 1, 2, metric1) }; metric1.GetResults(0).AddRange(metric1Results); Metric metric2 = Mock.Of<Metric>(); List<MetricResult> metric2Results = new List<MetricResult> { new MetricResult(0, 0, 3, metric1), new MetricResult(0, 1, 4, metric1) }; metric2.GetResults(0).AddRange(metric2Results); algorithm.Metrics.Add(metric1); algorithm.Metrics.Add(metric2); VerifyChartRefresh(chart => { chart.Population = population; chart.Algorithm = new TestAlgorithm(); }, chart => { chart.Algorithm = algorithm; }, (metric, series) => { if (metric == metric1) { Assert.Equal(metric1Results, (ICollection)series.ItemsSource); } else if (metric == metric2) { Assert.Equal(metric2Results, (ICollection)series.ItemsSource); } }); } /// <summary> /// Tests that the chart refreshes when the population changes from null. /// </summary> [StaFact] public void MetricsChart_OnPopulationChanged_FromNull() { TestPopulation population = new TestPopulation(); TestAlgorithm algorithm = new TestAlgorithm(); Metric metric1 = Mock.Of<Metric>(); List<MetricResult> metric1Results = new List<MetricResult> { new MetricResult(0, 0, 1, metric1), new MetricResult(0, 1, 2, metric1) }; metric1.GetResults(0).AddRange(metric1Results); Metric metric2 = Mock.Of<Metric>(); List<MetricResult> metric2Results = new List<MetricResult> { new MetricResult(0, 0, 3, metric1), new MetricResult(0, 1, 4, metric1) }; metric2.GetResults(0).AddRange(metric2Results); algorithm.Metrics.Add(metric1); algorithm.Metrics.Add(metric2); VerifyChartRefresh(chart => { chart.Algorithm = algorithm; }, chart => { chart.Population = population; }, (metric, series) => { if (metric == metric1) { Assert.Equal(metric1Results, (ICollection)series.ItemsSource); } else if (metric == metric2) { Assert.Equal(metric2Results, (ICollection)series.ItemsSource); } }); } /// <summary> /// Tests that the chart refreshes when the population changes from a previous population. /// </summary> [StaFact] public void MetricsChart_OnPopulationChanged_FromOtherPopulation() { TestPopulation population = new TestPopulation(); TestAlgorithm algorithm = new TestAlgorithm(); Metric metric1 = Mock.Of<Metric>(); List<MetricResult> metric1Results = new List<MetricResult> { new MetricResult(0, 0, 1, metric1), new MetricResult(0, 1, 2, metric1) }; metric1.GetResults(0).AddRange(metric1Results); Metric metric2 = Mock.Of<Metric>(); List<MetricResult> metric2Results = new List<MetricResult> { new MetricResult(0, 0, 3, metric1), new MetricResult(0, 1, 4, metric1) }; metric2.GetResults(0).AddRange(metric2Results); algorithm.Metrics.Add(metric1); algorithm.Metrics.Add(metric2); VerifyChartRefresh(chart => { chart.Algorithm = new TestAlgorithm(); chart.Population = new TestPopulation(); }, chart => { chart.Algorithm = algorithm; chart.Population = population; }, (metric, series) => { if (metric == metric1) { Assert.Equal(metric1Results, (ICollection)series.ItemsSource); } else if (metric == metric2) { Assert.Equal(metric2Results, (ICollection)series.ItemsSource); } }); } /// <summary> /// Tests that the chart does not add a series for a metric that doesn't produce values convertible to double. /// </summary> [StaFact] public void MetricsChart_MetricWithNonDoubleResult() { TestPopulation population = new TestPopulation(); TestAlgorithm algorithm = new TestAlgorithm(); Metric metric1 = Mock.Of<Metric>(); List<MetricResult> metric1Results = new List<MetricResult> { new MetricResult(0, 0, "foo", metric1), new MetricResult(0, 1, "bar", metric1) }; metric1.GetResults(0).AddRange(metric1Results); Metric metric2 = Mock.Of<Metric>(); List<MetricResult> metric2Results = new List<MetricResult> { new MetricResult(0, 0, 3, metric1), new MetricResult(0, 1, 4, metric1) }; metric2.GetResults(0).AddRange(metric2Results); algorithm.Metrics.Add(metric1); algorithm.Metrics.Add(metric2); MetricsChart chart = new MetricsChart { Algorithm = algorithm, Population = population }; Assert.Single(chart.PlotModel.Series); Assert.Equal(metric2Results, (ICollection)((LineSeries)chart.PlotModel.Series[0]).ItemsSource); } /// <summary> /// Tests that the chart refreshes the series when the fitness is evaluated for the initial generation. /// </summary> [StaFact] public void MetricsChart_RefreshSeriesOnFitnessEvaluated() { TestPopulation population = new TestPopulation(); TestAlgorithm algorithm = new TestAlgorithm(); Metric metric1 = Mock.Of<Metric>(); List<MetricResult> metric1Results = new List<MetricResult> { new MetricResult(0, 0, 3, metric1), new MetricResult(0, 1, 4, metric1) }; metric1.GetResults(0).AddRange(metric1Results); algorithm.Metrics.Add(metric1); MetricsChart chart = new MetricsChart { Algorithm = algorithm, Population = population }; Assert.Single(chart.PlotModel.Series); // Clear the series to ensure it gets refreshed when the fitness is evaluated chart.PlotModel.Series.Clear(); PrivateObject algorithmAccessor = new PrivateObject(algorithm, new PrivateType(typeof(GeneticAlgorithm))); algorithmAccessor.Invoke("OnFitnessEvaluated", new EnvironmentFitnessEvaluatedEventArgs(new GeneticEnvironment(algorithm), 0)); Assert.Single(chart.PlotModel.Series); } /// <summary> /// Tests that the chart refreshes the series when the fitness is evaluated after the initial generation. /// </summary> [StaFact] public void MetricsChart_RefreshPlotOnFitnessEvaluated() { TestPopulation population = new TestPopulation(); TestAlgorithm algorithm = new TestAlgorithm(); Metric metric1 = Mock.Of<Metric>(); List<MetricResult> metric1Results = new List<MetricResult> { new MetricResult(0, 0, 3, metric1), new MetricResult(0, 1, 4, metric1) }; metric1.GetResults(0).AddRange(metric1Results); algorithm.Metrics.Add(metric1); MetricsChart chart = new MetricsChart { Algorithm = algorithm, Population = population }; Assert.Single(chart.PlotModel.Series); // Clear the series to ensure it doesn't gets refreshed when the fitness is evaluated chart.PlotModel.Series.Clear(); PrivateObject algorithmAccessor = new PrivateObject(algorithm, new PrivateType(typeof(GeneticAlgorithm))); algorithmAccessor.Invoke("OnFitnessEvaluated", new EnvironmentFitnessEvaluatedEventArgs(new GeneticEnvironment(algorithm), 1)); Assert.Empty(chart.PlotModel.Series); } /// <summary> /// Tests that the chart refreshes the series when the <see cref="MetricsChart.SelectedMetrics"/> property changes. /// </summary> [StaFact] public void MetricsChart_OnSelectedMetricsChanged() { TestPopulation population = new TestPopulation(); TestAlgorithm algorithm = new TestAlgorithm(); Metric metric1 = Mock.Of<Metric>(); List<MetricResult> metric1Results = new List<MetricResult> { new MetricResult(0, 0, 3, metric1), new MetricResult(0, 1, 4, metric1) }; metric1.GetResults(0).AddRange(metric1Results); algorithm.Metrics.Add(metric1); Metric metric2 = Mock.Of<Metric>(); List<MetricResult> metric2Results = new List<MetricResult> { new MetricResult(0, 0, 3, metric1), new MetricResult(0, 1, 4, metric1) }; metric2.GetResults(0).AddRange(metric2Results); algorithm.Metrics.Add(metric2); MetricsChart chart = new MetricsChart { Algorithm = algorithm, Population = population }; Assert.Equal(2, chart.PlotModel.Series.Count); chart.PlotModel.Series.Clear(); chart.SelectedMetrics = new List<Metric> { algorithm.Metrics[0] }; Assert.Single(chart.PlotModel.Series); } private static void VerifyChartRefresh( Action<MetricsChart> initializeChart, Action<MetricsChart> triggerRefresh, Action<Metric, LineSeries> verifySeries) { MetricsChart chart = new MetricsChart(); initializeChart(chart); // Verify the default state of the chart Assert.Empty(chart.PlotModel.Series); triggerRefresh(chart); // Verify the chart has been refreshed Metric[] metrics = (chart.SelectedMetrics ?? chart.Algorithm.Metrics).ToArray(); Assert.Equal(metrics.Length, chart.PlotModel.Series.Count); for (int i = 0; i < metrics.Length; i++) { verifySeries(metrics[i], (LineSeries)chart.PlotModel.Series[i]); } } private class TestPopulation : Population { } private class TestAlgorithm : GeneticAlgorithm { protected override Task CreateNextGenerationAsync(Population population) { throw new NotImplementedException(); } } } }
34.78673
123
0.546935
[ "MIT" ]
mthalman/GenFx
src/GenFx.Wpf.Tests/MetricsChartTest.cs
14,682
C#
using System; namespace Lab_21_Exceptions { class Program { static long num = 9; static void Main(string[] args) { //var bigNumber = int.MaxValue; //Console.WriteLine(int.MaxValue); //Console.WriteLine(bigNumber + 1); //checked //{ // Console.WriteLine(bigNumber +1); //} //Method1(Program.num); int x = 10; int y = 20; int a = 0; // unhandled try { int z = x / y; double d = x / y; Console.WriteLine($"{x} / {y} = {z} and {d}"); int trouble = y / a; } catch (Exception e) // handled { Console.WriteLine("Divide by zero"); Console.WriteLine(e); Console.WriteLine(e.Data); Console.WriteLine(e.Message); //throw; } finally { } } public static void Method1(long num) { //Console.WriteLine("Crash me"); num *= 2; Method1(num); } } }
23.788462
62
0.390461
[ "MIT" ]
Stephen-Callum/2020-01-c-sharp-labs
Labs/Lab_21_Exceptions/Program.cs
1,239
C#
using ExtendedXmlSerializer.Core.Sources; namespace ExtendedXmlSerializer.ExtensionModel.Xml { interface IInstanceFormatter : IFormatter<object> {} }
25.166667
53
0.84106
[ "MIT" ]
ExtendedXmlSerializer/ExtendedXmlSerializer
src/ExtendedXmlSerializer/ExtensionModel/Xml/IInstanceFormatter.cs
151
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 static Interop.UxTheme; namespace System.Windows.Forms.VisualStyles { public enum MarginProperty { SizingMargins = TMT.SIZINGMARGINS, ContentMargins = TMT.CONTENTMARGINS, CaptionMargins = TMT.CAPTIONMARGINS } }
28.6875
71
0.729847
[ "MIT" ]
AArnott/winforms
src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/MarginProperty.cs
461
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; using System.Linq; public class Creature : MonoBehaviour { public float healthMax = 100; public float health = 100; public bool isAlive = true; public bool isConscious = true; DamageResists _damageResists; /// <summary> /// Affects health and caps it to healthMax automatically for cases of healing. /// Positive values will heal, negative values will deal damage. /// </summary> /// <param name="changeAmount">Parameter value to pass.</param> /// <returns>Returns true if they're left unconscious after the change. /// Returns false if still conscious</returns> /// <returns>Returns false if still conscious</returns> public bool ChangeHealth(float changeAmount) { health += changeAmount; health = Mathf.Min(health, healthMax); if (health <= 0) return true; return false; } public float ApplyDamageResists(float healthChange, DamageInfo dI) { if (_damageResists) { var resists = _damageResists.GetResistencesOfDamageType(dI.damageType); resists = resists.OrderByDescending(w => w.percentage).ToList(); if (resists.Count > 0) { foreach (var dR in resists) { if (dR.percentage) healthChange *= 1 - ((dR.resistAmount) * 0.01f); else healthChange -= dR.resistAmount; } } } // We don't want our damage healing the target, or healing damaging the target. return Mathf.Max(healthChange,0); } DamagePopup damagePopup; public bool ChangeHealth(DamageInfo dI) { var change = dI.damage; // Reduce incoming amount by applicable damage resists change = ApplyDamageResists(change, dI); // If it's a type that deals damage, negate it so it does harm. if (dI.damageType >= 0) change = -change; health += change; health = Mathf.Min(health, healthMax); bool isCritical; if (Random.Range(0, 100) < 30) isCritical = true; else isCritical = false; HandleDamagePopup(transform.position, change, dI.damageType, isCritical); if (health <= 0) return true; return false; } private void HandleDamagePopup(Vector3 position, float change, int damageType, bool isCritical) { // If we're not currently tracking a popup, make a new one. if(!damagePopup) { damagePopup = DamagePopup.Create(transform.position, change, damageType, isCritical); return; } // If tracked damagetype isn't the same as the newest source of damage's type, make and track a new one if(damageType != damagePopup.damageType) { damagePopup = DamagePopup.Create(transform.position, change, damageType, isCritical); return; } else // If same damagetype, add the new damage to the old one on display { damagePopup.AddDamage(change); } } public void Unconscious() { var nMA = GetComponent<NavMeshAgent>(); if (nMA) nMA.enabled = false; var ragdoll = GetComponent<Ragdoll>(); if(ragdoll) ragdoll.EnableRagdoll(); isConscious = false; } // Start is called before the first frame update void Start() { if (!_damageResists) _damageResists = GetComponent<DamageResists>(); } // Update is called once per frame void Update() { if (health < 0) Unconscious(); } }
27.814286
111
0.580637
[ "MIT" ]
codingwatching/Zenthium-Heroes
Assets/Creature.cs
3,894
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Runtime.InteropServices; using System.Security; namespace System.IO { // Only static data; no need to serialize internal static class __Error { internal static Exception GetEndOfFile() { return new EndOfStreamException(SR.IO_EOF_ReadBeyondEOF); } internal static Exception GetFileNotOpen() { return new ObjectDisposedException(null, SR.ObjectDisposed_FileClosed); } internal static Exception GetPipeNotOpen() { return new ObjectDisposedException(null, SR.ObjectDisposed_PipeClosed); } internal static Exception GetStreamIsClosed() { return new ObjectDisposedException(null, SR.ObjectDisposed_StreamIsClosed); } internal static Exception GetReadNotSupported() { return new NotSupportedException(SR.NotSupported_UnreadableStream); } internal static Exception GetSeekNotSupported() { return new NotSupportedException(SR.NotSupported_UnseekableStream); } internal static Exception GetWrongAsyncResult() { return new ArgumentException(SR.Argument_WrongAsyncResult); } internal static Exception GetEndReadCalledTwice() { // Should ideally be InvalidOperationExc but we can't maintain parity with Stream and FileStream without some work return new ArgumentException(SR.InvalidOperation_EndReadCalledMultiple); } internal static Exception GetEndWriteCalledTwice() { // Should ideally be InvalidOperationExc but we can't maintain parity with Stream and FileStream without some work return new ArgumentException(SR.InvalidOperation_EndWriteCalledMultiple); } internal static Exception GetEndWaitForConnectionCalledTwice() { // Should ideally be InvalidOperationExc but we can't maintain parity with Stream and FileStream without some work return new ArgumentException(SR.InvalidOperation_EndWaitForConnectionCalledMultiple); } internal static Exception GetWriteNotSupported() { return new NotSupportedException(SR.NotSupported_UnwritableStream); } internal static Exception GetOperationAborted() { return new IOException(SR.IO_OperationAborted); } } }
34.25
126
0.678832
[ "MIT" ]
ProgramFOX/corefx
src/System.IO.Pipes/src/System/IO/__Error.cs
2,603
C#
using System; using System.Collections.Generic; namespace DictionariesDemos { class DictionariesDemo { public static void Main() { var phoneBook = new Dictionary<string, string>(); phoneBook["Ivan"] = "+35923421412"; phoneBook["Pesho"] = "+3591234152"; phoneBook["Stavri"] = "+441561234"; phoneBook["Temelko"] = "+561234862"; var keys = phoneBook.Keys; //foreach (var key in keys) //{ // console.writeline(key); //} //var values = phonebook.values; //foreach (var value in values) //{ // console.writeline(value); //} //foreach (var kvp in phoneBook) //{ // var key = kvp.Key; // var value = kvp.Value; // Console.WriteLine($"{key} -> {value}"); //} //phoneBook.Add("Asparuh", "+1"); //phoneBook.Remove("Temelko"); //phoneBook.Clear(); //var existKey = phoneBook.ContainsKey("Temelko"); //var existValue = phoneBook.ContainsValue("+3598441244"); //Console.WriteLine(existKey); //Console.WriteLine(existValue); //var name = Console.ReadLine(); //var nameNumber = Console.ReadLine(); //if (!phoneBook.ContainsKey(name)) //{ // phoneBook.Add(name, nameNumber); //} //else //{ // Console.WriteLine("You need to provide unique name and number"); //} //var secondPhoneBook = new Dictionary<string, List<string>>(); //secondPhoneBook["Gosho"] = new List<string> //{ // "+2141234","+16612" //}; //var gosheNumbers = secondPhoneBook["Gosho"]; //foreach (var phone in gosheNumbers) //{ // Console.WriteLine(phone); //} //foreach (var key in phoneBook.Keys) //{ // Console.WriteLine(key); // Console.WriteLine(phoneBook[key]); // Console.WriteLine("---"); //} //int number; //bool parsed = int.TryParse(text, out number); //Console.WriteLine(number); //Console.WriteLine(parsed); var phone = new Dictionary<string, string>(); phone["Ivan"] = "+1234557"; string number; var succes = phone.TryGetValue("Ivan", out number); Console.WriteLine(succes); Console.WriteLine(number); } } }
29.641304
82
0.471947
[ "MIT" ]
viktornikolov038/Programming-Fundamentals-C-Sharp-2018
09.Dictionaries/DictionariesDemos/DictionariesDemos/DictionariesDemo.cs
2,729
C#
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Passingwind.Blog.Services; using Passingwind.Blog.Web.Factory; using Passingwind.Blog.Web.Models; using System.Linq; using System.Threading.Tasks; namespace Passingwind.Blog.Web.ApiControllers { public class IdentityController : ApiControllerBase { private readonly IHttpContextAccessor _httpContextAccessor; private readonly BlogUserManager _userManager; private readonly BlogRoleManager _roleManager; private readonly IUserFactory _userFactory; public IdentityController(IHttpContextAccessor httpContextAccessor, BlogUserManager userManager, BlogRoleManager roleManager, IUserFactory userFactory) { _httpContextAccessor = httpContextAccessor; _userManager = userManager; _roleManager = roleManager; _userFactory = userFactory; } [HttpGet] public async Task<CurrentUserProfileModel> GetCurrentUserProfleAsync() { var cp = _httpContextAccessor.HttpContext.User; var user = await _userManager.FindByNameAsync(cp.Identity.Name); var roles = await _userManager.GetRolesAsync(user); var permissions = await _roleManager.GetRolesPermissionsAsync(roles.ToArray()); var model = new CurrentUserProfileModel() { DisplayName = user.DisplayName, PhoneNumber = user.PhoneNumber, Bio = user.Bio, UserDescription = user.UserDescription, Email = user.Email, Roles = roles, Permissions = permissions, AvatarUrl = AvatarHelper.GetSrc(user.Email), }; #if DEBUG model.IdentityName = cp.Identity.Name; model.AuthenticationType = cp.Identity.AuthenticationType; model.Claims = cp.Claims.Select(t => new IdentityClaim(t.Type, t.Value)).ToArray(); #endif return model; } } }
28.459016
153
0.773041
[ "MIT" ]
jxnkwlp/Passingwind.Blog
Passingwind.Blog.Web.Core/ApiControllers/IdentityController.cs
1,736
C#
using UnityEngine; using UnityEngine.SceneManagement; public class ButtonToDodgeCoin : MonoBehaviour { public void ChangeToDodgeCoin() { SceneManager.LoadScene("DodgeCoin", LoadSceneMode.Single); } }
24.111111
66
0.75576
[ "BSD-3-Clause" ]
JenniTheDev/Microverse
Assets/Scripts/ButtonToDodgeCoin.cs
217
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Azure.Network { /// <summary> /// Manages a network security group that contains a list of network security rules. Network security groups enable inbound or outbound traffic to be enabled or denied. /// /// &gt; **NOTE on Network Security Groups and Network Security Rules:** This provider currently /// provides both a standalone Network Security Rule resource, and allows for Network Security Rules to be defined in-line within the Network Security Group resource. /// At this time you cannot use a Network Security Group with in-line Network Security Rules in conjunction with any Network Security Rule resources. Doing so will cause a conflict of rule settings and will overwrite rules. /// /// ## Example Usage /// /// ```csharp /// using Pulumi; /// using Azure = Pulumi.Azure; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var exampleResourceGroup = new Azure.Core.ResourceGroup("exampleResourceGroup", new Azure.Core.ResourceGroupArgs /// { /// Location = "West US", /// }); /// var exampleNetworkSecurityGroup = new Azure.Network.NetworkSecurityGroup("exampleNetworkSecurityGroup", new Azure.Network.NetworkSecurityGroupArgs /// { /// Location = exampleResourceGroup.Location, /// ResourceGroupName = exampleResourceGroup.Name, /// SecurityRules = /// { /// new Azure.Network.Inputs.NetworkSecurityGroupSecurityRuleArgs /// { /// Name = "test123", /// Priority = 100, /// Direction = "Inbound", /// Access = "Allow", /// Protocol = "Tcp", /// SourcePortRange = "*", /// DestinationPortRange = "*", /// SourceAddressPrefix = "*", /// DestinationAddressPrefix = "*", /// }, /// }, /// Tags = /// { /// { "environment", "Production" }, /// }, /// }); /// } /// /// } /// ``` /// /// ## Import /// /// Network Security Groups can be imported using the `resource id`, e.g. /// /// ```sh /// $ pulumi import azure:network/networkSecurityGroup:NetworkSecurityGroup group1 /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/mygroup1/providers/Microsoft.Network/networkSecurityGroups/mySecurityGroup /// ``` /// </summary> public partial class NetworkSecurityGroup : Pulumi.CustomResource { /// <summary> /// Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created. /// </summary> [Output("location")] public Output<string> Location { get; private set; } = null!; /// <summary> /// The name of the security rule. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// The name of the resource group in which to create the network security group. Changing this forces a new resource to be created. /// </summary> [Output("resourceGroupName")] public Output<string> ResourceGroupName { get; private set; } = null!; /// <summary> /// A list of objects representing security rules, as defined below. /// </summary> [Output("securityRules")] public Output<ImmutableArray<Outputs.NetworkSecurityGroupSecurityRule>> SecurityRules { get; private set; } = null!; /// <summary> /// A mapping of tags to assign to the resource. /// </summary> [Output("tags")] public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!; /// <summary> /// Create a NetworkSecurityGroup resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public NetworkSecurityGroup(string name, NetworkSecurityGroupArgs args, CustomResourceOptions? options = null) : base("azure:network/networkSecurityGroup:NetworkSecurityGroup", name, args ?? new NetworkSecurityGroupArgs(), MakeResourceOptions(options, "")) { } private NetworkSecurityGroup(string name, Input<string> id, NetworkSecurityGroupState? state = null, CustomResourceOptions? options = null) : base("azure:network/networkSecurityGroup:NetworkSecurityGroup", name, state, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing NetworkSecurityGroup resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="state">Any extra arguments used during the lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static NetworkSecurityGroup Get(string name, Input<string> id, NetworkSecurityGroupState? state = null, CustomResourceOptions? options = null) { return new NetworkSecurityGroup(name, id, state, options); } } public sealed class NetworkSecurityGroupArgs : Pulumi.ResourceArgs { /// <summary> /// Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created. /// </summary> [Input("location")] public Input<string>? Location { get; set; } /// <summary> /// The name of the security rule. /// </summary> [Input("name")] public Input<string>? Name { get; set; } /// <summary> /// The name of the resource group in which to create the network security group. Changing this forces a new resource to be created. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; [Input("securityRules")] private InputList<Inputs.NetworkSecurityGroupSecurityRuleArgs>? _securityRules; /// <summary> /// A list of objects representing security rules, as defined below. /// </summary> public InputList<Inputs.NetworkSecurityGroupSecurityRuleArgs> SecurityRules { get => _securityRules ?? (_securityRules = new InputList<Inputs.NetworkSecurityGroupSecurityRuleArgs>()); set => _securityRules = value; } [Input("tags")] private InputMap<string>? _tags; /// <summary> /// A mapping of tags to assign to the resource. /// </summary> public InputMap<string> Tags { get => _tags ?? (_tags = new InputMap<string>()); set => _tags = value; } public NetworkSecurityGroupArgs() { } } public sealed class NetworkSecurityGroupState : Pulumi.ResourceArgs { /// <summary> /// Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created. /// </summary> [Input("location")] public Input<string>? Location { get; set; } /// <summary> /// The name of the security rule. /// </summary> [Input("name")] public Input<string>? Name { get; set; } /// <summary> /// The name of the resource group in which to create the network security group. Changing this forces a new resource to be created. /// </summary> [Input("resourceGroupName")] public Input<string>? ResourceGroupName { get; set; } [Input("securityRules")] private InputList<Inputs.NetworkSecurityGroupSecurityRuleGetArgs>? _securityRules; /// <summary> /// A list of objects representing security rules, as defined below. /// </summary> public InputList<Inputs.NetworkSecurityGroupSecurityRuleGetArgs> SecurityRules { get => _securityRules ?? (_securityRules = new InputList<Inputs.NetworkSecurityGroupSecurityRuleGetArgs>()); set => _securityRules = value; } [Input("tags")] private InputMap<string>? _tags; /// <summary> /// A mapping of tags to assign to the resource. /// </summary> public InputMap<string> Tags { get => _tags ?? (_tags = new InputMap<string>()); set => _tags = value; } public NetworkSecurityGroupState() { } } }
41.557377
229
0.59428
[ "ECL-2.0", "Apache-2.0" ]
suresh198526/pulumi-azure
sdk/dotnet/Network/NetworkSecurityGroup.cs
10,140
C#
using Cosmos.Business.Extensions.Holiday.Core; using Cosmos.I18N.Countries; namespace Cosmos.Business.Extensions.Holiday.Definitions.Africa.CapeVerde.Public { /// <summary> /// Heroes' Day<br /> /// pt: Dia dos Heróis Nacionais /// </summary> public class HeroesDay : BaseFixedHolidayFunc { /// <inheritdoc /> public override Country Country { get; } = Country.CapeVerde; /// <inheritdoc /> public override Country BelongsToCountry { get; } = Country.CapeVerde; /// <inheritdoc /> public override string Name { get; } = "Dia dos Heróis Nacionais"; /// <inheritdoc /> public override HolidayType HolidayType { get; set; } = HolidayType.Public; /// <inheritdoc /> public override int Month { get; set; } = 1; /// <inheritdoc /> public override int Day { get; set; } = 20; /// <inheritdoc /> public override string I18NIdentityCode { get; } = "i18n_holiday_cv_heroes"; } }
30.787879
84
0.612205
[ "Apache-2.0" ]
cosmos-open/Holiday
src/Cosmos.Business.Extensions.Holiday/Cosmos/Business/Extensions/Holiday/Definitions/Africa/CapeVerde/Public/HeroesDay.cs
1,018
C#
using Acme.Common; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Acme.Biz { /// <summary> /// Manages the approved vendors from whom Acme purchases our inventory. /// </summary> public class Vendor { public int VendorId { get; set; } public string CompanyName { get; set; } public string Email { get; set; } /// <summary> /// Sends a product order to the vendor. /// </summary> /// <param name="product">Product to order.</param> /// <param name="quantity">Quantity of the product to order.</param> /// <param name="deliverBy">Requested delivery date.</param> /// <param name="instructions">Delivery instructions.</param> /// <returns></returns> public OperationResult<bool> PlaceOrder(Product product, int quantity, DateTimeOffset? deliverBy = null, string instructions = "standard delivery") { if (product == null) throw new ArgumentNullException(nameof(product)); if (quantity <= 0) throw new ArgumentOutOfRangeException(nameof(quantity)); if (deliverBy <= DateTimeOffset.Now) throw new ArgumentOutOfRangeException(nameof(deliverBy)); var success = false; var orderTextBuilder = new StringBuilder("Order from Acme, Inc" + System.Environment.NewLine + "Product: " + product.ProductName + System.Environment.NewLine + "Quantity: " + quantity); if (deliverBy.HasValue) { orderTextBuilder.Append( System.Environment.NewLine + "Deliver By: " + deliverBy.Value.ToString("d")); } if (!String.IsNullOrWhiteSpace(instructions)) { orderTextBuilder.Append( System.Environment.NewLine + "Instructions: " + instructions); } var orderText = orderTextBuilder.ToString(); var emailService = new EmailService(); var confirmation = emailService.SendMessage("New Order", orderText, this.Email); if (confirmation.StartsWith("Message sent:")) { success = true; } var operationResult = new OperationResult<bool>(success, orderText); return operationResult; } public override string ToString() { return $"Vendor: {this.CompanyName} ({this.VendorId})"; } public override bool Equals(object obj) { if(obj == null || this.GetType() != obj.GetType()) return false; Vendor compareVendor = obj as Vendor; if(compareVendor != null && this.VendorId == compareVendor.VendorId && this.CompanyName == compareVendor.CompanyName && this.Email == compareVendor.Email) return true; return base.Equals(obj); } public override int GetHashCode() => base.GetHashCode(); /// <summary> /// Sends an email to welcome a new vendor. /// </summary> /// <returns></returns> public string SendWelcomeEmail(string message) { var emailService = new EmailService(); var subject = ("Hello " + this.CompanyName).Trim(); var confirmation = emailService.SendMessage(subject, message, this.Email); return confirmation; } /// <summary> /// Sends an email to a set of vendors /// </summary> /// <param name="vendors">Collection of vendors</param> /// <param name="message">Message to send</param> /// <returns></returns> public static List<string> SendEmail(ICollection<Vendor> vendors, string message) { var confirmations = new List<string>(); var emailService = new EmailService(); Console.WriteLine(vendors.Count); foreach(var vendor in vendors) { var subject = "Important message for: " + vendor.CompanyName; var confirmation = emailService.SendMessage(subject, message, vendor.Email); confirmations.Add(confirmation); } return confirmations; } } }
37.645669
92
0.526459
[ "MIT" ]
mttwht/CSharpBP-Collections
AcmeApp/Acme.Biz/Vendor.cs
4,783
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; namespace Example_UWP { /// <summary> /// Provides application-specific behavior to supplement the default Application class. /// </summary> sealed partial class App : Application { /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { this.InitializeComponent(); this.Suspending += OnSuspending; } /// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs e) { Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (e.PrelaunchActivated == false) { if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter rootFrame.Navigate(typeof(MainPage), e.Arguments); } // Ensure the current window is active Window.Current.Activate(); } } /// <summary> /// Invoked when Navigation to a certain page fails /// </summary> /// <param name="sender">The Frame which failed navigation</param> /// <param name="e">Details about the navigation failure</param> void OnNavigationFailed(object sender, NavigationFailedEventArgs e) { throw new Exception("Failed to load Page " + e.SourcePageType.FullName); } /// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); //TODO: Save application state and stop any background activity deferral.Complete(); } } }
38.841584
99
0.614326
[ "BSD-3-Clause" ]
Zunair/OpenWeatherC
Example UWP/App.xaml.cs
3,925
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsLro { using System.Threading.Tasks; using Microsoft.Rest.Azure; using Models; /// <summary> /// Extension methods for LROsCustomHeaderOperations. /// </summary> public static partial class LROsCustomHeaderOperationsExtensions { /// <summary> /// x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 is required /// message header for all requests. Long running put request, service /// returns a 200 to the initial request, with an entity that contains /// ProvisioningState=’Creating’. Poll the endpoint indicated in the /// Azure-AsyncOperation header for operation status /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='product'> /// Product to put /// </param> public static Product PutAsyncRetrySucceeded(this ILROsCustomHeaderOperations operations, Product product = default(Product)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((ILROsCustomHeaderOperations)s).PutAsyncRetrySucceededAsync(product), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 is required /// message header for all requests. Long running put request, service /// returns a 200 to the initial request, with an entity that contains /// ProvisioningState=’Creating’. Poll the endpoint indicated in the /// Azure-AsyncOperation header for operation status /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='product'> /// Product to put /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Product> PutAsyncRetrySucceededAsync(this ILROsCustomHeaderOperations operations, Product product = default(Product), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.PutAsyncRetrySucceededWithHttpMessagesAsync(product, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 is required /// message header for all requests. Long running put request, service /// returns a 200 to the initial request, with an entity that contains /// ProvisioningState=’Creating’. Poll the endpoint indicated in the /// Azure-AsyncOperation header for operation status /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='product'> /// Product to put /// </param> public static Product BeginPutAsyncRetrySucceeded(this ILROsCustomHeaderOperations operations, Product product = default(Product)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((ILROsCustomHeaderOperations)s).BeginPutAsyncRetrySucceededAsync(product), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 is required /// message header for all requests. Long running put request, service /// returns a 200 to the initial request, with an entity that contains /// ProvisioningState=’Creating’. Poll the endpoint indicated in the /// Azure-AsyncOperation header for operation status /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='product'> /// Product to put /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Product> BeginPutAsyncRetrySucceededAsync(this ILROsCustomHeaderOperations operations, Product product = default(Product), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.BeginPutAsyncRetrySucceededWithHttpMessagesAsync(product, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 is required /// message header for all requests. Long running put request, service /// returns a 201 to the initial request, with an entity that contains /// ProvisioningState=’Creating’. Polls return this value until the last /// poll returns a ‘200’ with ProvisioningState=’Succeeded’ /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='product'> /// Product to put /// </param> public static Product Put201CreatingSucceeded200(this ILROsCustomHeaderOperations operations, Product product = default(Product)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((ILROsCustomHeaderOperations)s).Put201CreatingSucceeded200Async(product), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 is required /// message header for all requests. Long running put request, service /// returns a 201 to the initial request, with an entity that contains /// ProvisioningState=’Creating’. Polls return this value until the last /// poll returns a ‘200’ with ProvisioningState=’Succeeded’ /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='product'> /// Product to put /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Product> Put201CreatingSucceeded200Async(this ILROsCustomHeaderOperations operations, Product product = default(Product), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.Put201CreatingSucceeded200WithHttpMessagesAsync(product, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 is required /// message header for all requests. Long running put request, service /// returns a 201 to the initial request, with an entity that contains /// ProvisioningState=’Creating’. Polls return this value until the last /// poll returns a ‘200’ with ProvisioningState=’Succeeded’ /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='product'> /// Product to put /// </param> public static Product BeginPut201CreatingSucceeded200(this ILROsCustomHeaderOperations operations, Product product = default(Product)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((ILROsCustomHeaderOperations)s).BeginPut201CreatingSucceeded200Async(product), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 is required /// message header for all requests. Long running put request, service /// returns a 201 to the initial request, with an entity that contains /// ProvisioningState=’Creating’. Polls return this value until the last /// poll returns a ‘200’ with ProvisioningState=’Succeeded’ /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='product'> /// Product to put /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Product> BeginPut201CreatingSucceeded200Async(this ILROsCustomHeaderOperations operations, Product product = default(Product), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.BeginPut201CreatingSucceeded200WithHttpMessagesAsync(product, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 is required /// message header for all requests. Long running post request, service /// returns a 202 to the initial request, with 'Location' and 'Retry-After' /// headers, Polls return a 200 with a response body after success /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='product'> /// Product to put /// </param> public static LROsCustomHeaderPost202Retry200Headers Post202Retry200(this ILROsCustomHeaderOperations operations, Product product = default(Product)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((ILROsCustomHeaderOperations)s).Post202Retry200Async(product), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 is required /// message header for all requests. Long running post request, service /// returns a 202 to the initial request, with 'Location' and 'Retry-After' /// headers, Polls return a 200 with a response body after success /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='product'> /// Product to put /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<LROsCustomHeaderPost202Retry200Headers> Post202Retry200Async(this ILROsCustomHeaderOperations operations, Product product = default(Product), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.Post202Retry200WithHttpMessagesAsync(product, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 is required /// message header for all requests. Long running post request, service /// returns a 202 to the initial request, with 'Location' and 'Retry-After' /// headers, Polls return a 200 with a response body after success /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='product'> /// Product to put /// </param> public static LROsCustomHeaderPost202Retry200Headers BeginPost202Retry200(this ILROsCustomHeaderOperations operations, Product product = default(Product)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((ILROsCustomHeaderOperations)s).BeginPost202Retry200Async(product), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 is required /// message header for all requests. Long running post request, service /// returns a 202 to the initial request, with 'Location' and 'Retry-After' /// headers, Polls return a 200 with a response body after success /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='product'> /// Product to put /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<LROsCustomHeaderPost202Retry200Headers> BeginPost202Retry200Async(this ILROsCustomHeaderOperations operations, Product product = default(Product), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.BeginPost202Retry200WithHttpMessagesAsync(product, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 is required /// message header for all requests. Long running post request, service /// returns a 202 to the initial request, with an entity that contains /// ProvisioningState=’Creating’. Poll the endpoint indicated in the /// Azure-AsyncOperation header for operation status /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='product'> /// Product to put /// </param> public static LROsCustomHeaderPostAsyncRetrySucceededHeaders PostAsyncRetrySucceeded(this ILROsCustomHeaderOperations operations, Product product = default(Product)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((ILROsCustomHeaderOperations)s).PostAsyncRetrySucceededAsync(product), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 is required /// message header for all requests. Long running post request, service /// returns a 202 to the initial request, with an entity that contains /// ProvisioningState=’Creating’. Poll the endpoint indicated in the /// Azure-AsyncOperation header for operation status /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='product'> /// Product to put /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<LROsCustomHeaderPostAsyncRetrySucceededHeaders> PostAsyncRetrySucceededAsync(this ILROsCustomHeaderOperations operations, Product product = default(Product), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.PostAsyncRetrySucceededWithHttpMessagesAsync(product, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 is required /// message header for all requests. Long running post request, service /// returns a 202 to the initial request, with an entity that contains /// ProvisioningState=’Creating’. Poll the endpoint indicated in the /// Azure-AsyncOperation header for operation status /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='product'> /// Product to put /// </param> public static LROsCustomHeaderPostAsyncRetrySucceededHeaders BeginPostAsyncRetrySucceeded(this ILROsCustomHeaderOperations operations, Product product = default(Product)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((ILROsCustomHeaderOperations)s).BeginPostAsyncRetrySucceededAsync(product), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 is required /// message header for all requests. Long running post request, service /// returns a 202 to the initial request, with an entity that contains /// ProvisioningState=’Creating’. Poll the endpoint indicated in the /// Azure-AsyncOperation header for operation status /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='product'> /// Product to put /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<LROsCustomHeaderPostAsyncRetrySucceededHeaders> BeginPostAsyncRetrySucceededAsync(this ILROsCustomHeaderOperations operations, Product product = default(Product), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.BeginPostAsyncRetrySucceededWithHttpMessagesAsync(product, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } } }
58.915254
335
0.624568
[ "MIT" ]
fhoering/autorest
src/generator/AutoRest.CSharp.Azure.Tests/Expected/AcceptanceTests/Lro/LROsCustomHeaderOperationsExtensions.cs
20,936
C#
using ATech.Ring.Configuration.Interfaces; using Nett; namespace ATech.Ring.Configuration; public class ConfigurationLoader : IConfigurationLoader { public T Load<T>(string path) => Toml.ReadFile<T>(path, TomlConfig.Settings); }
23.6
81
0.779661
[ "Apache-2.0" ]
AccountTechnologies/rin
src/ATech.Ring.Configuration/ConfigurationLoader.cs
238
C#
using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Formatters; namespace JsonCrafter.Processing.Serialization { public interface IResourceSerializer { /// <summary> /// The name of the mediatype format. /// </summary> string FormatName { get; } /// <summary> /// The headervalue for the current mediatype. /// </summary> string MediaTypeHeaderValue { get; } /// <summary> /// Initializes the serialization chain using the recieved object. /// </summary> /// <param name="context">The context of the formatter request</param> /// <param name="selectedEncoding">The requested encoding</param> /// <returns></returns> Task<string> SerializeAsync(OutputFormatterWriteContext context, Encoding selectedEncoding); } }
31.321429
100
0.6374
[ "Apache-2.0" ]
baseless/JsonCrafter
src/JsonCrafter.Processing/Serialization/IResourceSerializer.cs
879
C#
using System; using System.Collections.Generic; #nullable disable namespace P0DbContext { public partial class StoreInventory { public int StoreInventoryId { get; set; } public int StoreId { get; set; } public int ProductId { get; set; } public int Quantity { get; set; } public virtual Product Product { get; set; } public virtual Store Store { get; set; } } }
22.421053
52
0.631455
[ "MIT" ]
ssilva2021/SteveSilvaP0
P0DbContext/StoreInventory.cs
428
C#
/******************************************************************************* * Copyright 2012-2019 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. * ***************************************************************************** * * AWS Tools for Windows (TM) PowerShell (TM) * */ using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using Amazon.PowerShell.Common; using Amazon.Runtime; using Amazon.AlexaForBusiness; using Amazon.AlexaForBusiness.Model; namespace Amazon.PowerShell.Cmdlets.ALXB { /// <summary> /// Registers an Alexa-enabled device built by an Original Equipment Manufacturer (OEM) /// using Alexa Voice Service (AVS). /// </summary> [Cmdlet("Register", "ALXBAVSDevice", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium)] [OutputType("System.String")] [AWSCmdlet("Calls the Alexa For Business RegisterAVSDevice API operation.", Operation = new[] {"RegisterAVSDevice"}, SelectReturnType = typeof(Amazon.AlexaForBusiness.Model.RegisterAVSDeviceResponse))] [AWSCmdletOutput("System.String or Amazon.AlexaForBusiness.Model.RegisterAVSDeviceResponse", "This cmdlet returns a System.String object.", "The service call response (type Amazon.AlexaForBusiness.Model.RegisterAVSDeviceResponse) can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack." )] public partial class RegisterALXBAVSDeviceCmdlet : AmazonAlexaForBusinessClientCmdlet, IExecutor { #region Parameter AmazonId /// <summary> /// <para> /// <para>The device type ID for your AVS device generated by Amazon when the OEM creates a /// new product on Amazon's Developer Console.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] #else [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String AmazonId { get; set; } #endregion #region Parameter ClientId /// <summary> /// <para> /// <para>The client ID of the OEM used for code-based linking authorization on an AVS device.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] #else [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String ClientId { get; set; } #endregion #region Parameter DeviceSerialNumber /// <summary> /// <para> /// <para>The key generated by the OEM that uniquely identifies a specified instance of your /// AVS device.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)] #else [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String DeviceSerialNumber { get; set; } #endregion #region Parameter ProductId /// <summary> /// <para> /// <para>The product ID used to identify your AVS device during authorization.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] #else [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String ProductId { get; set; } #endregion #region Parameter UserCode /// <summary> /// <para> /// <para>The code that is obtained after your AVS device has made a POST request to LWA as /// a part of the Device Authorization Request component of the OAuth code-based linking /// specification.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] #else [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String UserCode { get; set; } #endregion #region Parameter Select /// <summary> /// Use the -Select parameter to control the cmdlet output. The default value is 'DeviceArn'. /// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.AlexaForBusiness.Model.RegisterAVSDeviceResponse). /// Specifying the name of a property of type Amazon.AlexaForBusiness.Model.RegisterAVSDeviceResponse will result in that property being returned. /// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public string Select { get; set; } = "DeviceArn"; #endregion #region Parameter PassThru /// <summary> /// Changes the cmdlet behavior to return the value passed to the DeviceSerialNumber parameter. /// The -PassThru parameter is deprecated, use -Select '^DeviceSerialNumber' instead. This parameter will be removed in a future version. /// </summary> [System.Obsolete("The -PassThru parameter is deprecated, use -Select '^DeviceSerialNumber' instead. This parameter will be removed in a future version.")] [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter PassThru { get; set; } #endregion #region Parameter Force /// <summary> /// This parameter overrides confirmation prompts to force /// the cmdlet to continue its operation. This parameter should always /// be used with caution. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter Force { get; set; } #endregion protected override void ProcessRecord() { base.ProcessRecord(); var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.DeviceSerialNumber), MyInvocation.BoundParameters); if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "Register-ALXBAVSDevice (RegisterAVSDevice)")) { return; } var context = new CmdletContext(); // allow for manipulation of parameters prior to loading into context PreExecutionContextLoad(context); #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute if (ParameterWasBound(nameof(this.Select))) { context.Select = CreateSelectDelegate<Amazon.AlexaForBusiness.Model.RegisterAVSDeviceResponse, RegisterALXBAVSDeviceCmdlet>(Select) ?? throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select)); if (this.PassThru.IsPresent) { throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select)); } } else if (this.PassThru.IsPresent) { context.Select = (response, cmdlet) => this.DeviceSerialNumber; } #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute context.AmazonId = this.AmazonId; #if MODULAR if (this.AmazonId == null && ParameterWasBound(nameof(this.AmazonId))) { WriteWarning("You are passing $null as a value for parameter AmazonId which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif context.ClientId = this.ClientId; #if MODULAR if (this.ClientId == null && ParameterWasBound(nameof(this.ClientId))) { WriteWarning("You are passing $null as a value for parameter ClientId which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif context.DeviceSerialNumber = this.DeviceSerialNumber; #if MODULAR if (this.DeviceSerialNumber == null && ParameterWasBound(nameof(this.DeviceSerialNumber))) { WriteWarning("You are passing $null as a value for parameter DeviceSerialNumber which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif context.ProductId = this.ProductId; #if MODULAR if (this.ProductId == null && ParameterWasBound(nameof(this.ProductId))) { WriteWarning("You are passing $null as a value for parameter ProductId which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif context.UserCode = this.UserCode; #if MODULAR if (this.UserCode == null && ParameterWasBound(nameof(this.UserCode))) { WriteWarning("You are passing $null as a value for parameter UserCode which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif // allow further manipulation of loaded context prior to processing PostExecutionContextLoad(context); var output = Execute(context) as CmdletOutput; ProcessOutput(output); } #region IExecutor Members public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; // create request var request = new Amazon.AlexaForBusiness.Model.RegisterAVSDeviceRequest(); if (cmdletContext.AmazonId != null) { request.AmazonId = cmdletContext.AmazonId; } if (cmdletContext.ClientId != null) { request.ClientId = cmdletContext.ClientId; } if (cmdletContext.DeviceSerialNumber != null) { request.DeviceSerialNumber = cmdletContext.DeviceSerialNumber; } if (cmdletContext.ProductId != null) { request.ProductId = cmdletContext.ProductId; } if (cmdletContext.UserCode != null) { request.UserCode = cmdletContext.UserCode; } CmdletOutput output; // issue call var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; pipelineOutput = cmdletContext.Select(response, this); output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } return output; } public ExecutorContext CreateContext() { return new CmdletContext(); } #endregion #region AWS Service Operation Call private Amazon.AlexaForBusiness.Model.RegisterAVSDeviceResponse CallAWSServiceOperation(IAmazonAlexaForBusiness client, Amazon.AlexaForBusiness.Model.RegisterAVSDeviceRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Alexa For Business", "RegisterAVSDevice"); try { #if DESKTOP return client.RegisterAVSDevice(request); #elif CORECLR return client.RegisterAVSDeviceAsync(request).GetAwaiter().GetResult(); #else #error "Unknown build edition" #endif } catch (AmazonServiceException exc) { var webException = exc.InnerException as System.Net.WebException; if (webException != null) { throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException); } throw; } } #endregion internal partial class CmdletContext : ExecutorContext { public System.String AmazonId { get; set; } public System.String ClientId { get; set; } public System.String DeviceSerialNumber { get; set; } public System.String ProductId { get; set; } public System.String UserCode { get; set; } public System.Func<Amazon.AlexaForBusiness.Model.RegisterAVSDeviceResponse, RegisterALXBAVSDeviceCmdlet, object> Select { get; set; } = (response, cmdlet) => response.DeviceArn; } } }
46.881306
289
0.621179
[ "Apache-2.0" ]
5u5hma/aws-tools-for-powershell
modules/AWSPowerShell/Cmdlets/AlexaForBusiness/Basic/Register-ALXBAVSDevice-Cmdlet.cs
15,799
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace GroupService.Repo.Migrations { public partial class FE835FixMarkdown : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.UpdateData( schema: "Group", table: "SupportActivityInstructions", keyColumn: "SupportActivityInstructionsID", keyValue: (short)44, column: "Instructions", value: "{\"SupportActivityInstructions\":44,\"ActivityDetails\":null,\"Intro\":\"We are looking for you to pick up a prescription on a client’s behalf. (Prescriptions in Wales are free)\",\"Steps\":[{\"Heading\":\"Let the client know you’re able to help\",\"Detail\":\"Contact the client to let them know who you are and to confirm the help is still needed. You should also check if the client has told the pharmacy that you will be picking up the prescription on their behalf - see the [NHS website](https://www.nhs.uk/common-health-questions/caring-carers-and-long-term-conditions/can-i-pick-up-a-prescription-for-someone-else/) for more details.\"},{\"Heading\":\"Collect the prescription\",\"Detail\":\"Collect the prescription on the client’s behalf.\"},{\"Heading\":\"Mark the request as complete\",\"Detail\":\"Once you have completed the task, mark it as complete from your “My Requests” page.\"},{\"Heading\":\"Share any concerns or updates\",\"Detail\":\"Please make sure to tell us if you have any concerns or updates by using the contact details provided on the request or leaving feedback when you mark the request as complete.\"}],\"Close\":\"If for any reason you can’t complete the request, let us know by updating the accepted request and clicking “Can’t Do” - this will allow us to find a new volunteer to help. If you need to claim expenses for this activity, you must do so within three months by submitting our [expense claim form](/forms/ageconnect/cardiff/volunteer-expense-form.docx).\"}"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.UpdateData( schema: "Group", table: "SupportActivityInstructions", keyColumn: "SupportActivityInstructionsID", keyValue: (short)44, column: "Instructions", value: "{\"SupportActivityInstructions\":44,\"ActivityDetails\":null,\"Intro\":\"We are looking for you to pick up a prescription on a client’s behalf. (Prescriptions in Wales are free)\",\"Steps\":[{\"Heading\":\"Let the client know you’re able to help\",\"Detail\":\"Contact the client to let them know who you are and to confirm the help is still needed. You should also check if the client has told the pharmacy that you will be picking up the prescription on their behalf - see the [NHS website] (https://www.nhs.uk/common-health-questions/caring-carers-and-long-term-conditions/can-i-pick-up-a-prescription-for-someone-else/) for more details.\"},{\"Heading\":\"Collect the prescription\",\"Detail\":\"Collect the prescription on the client’s behalf.\"},{\"Heading\":\"Mark the request as complete\",\"Detail\":\"Once you have completed the task, mark it as complete from your “My Requests” page.\"},{\"Heading\":\"Share any concerns or updates\",\"Detail\":\"Please make sure to tell us if you have any concerns or updates by using the contact details provided on the request or leaving feedback when you mark the request as complete.\"}],\"Close\":\"If for any reason you can’t complete the request, let us know by updating the accepted request and clicking “Can’t Do” - this will allow us to find a new volunteer to help. If you need to claim expenses for this activity, you must do so within three months by submitting our [expense claim form](/forms/ageconnect/cardiff/volunteer-expense-form.docx).\"}"); } } }
131.166667
1,531
0.704701
[ "MIT" ]
HelpMyStreet/group-service
GroupService/GroupService.Repo/Migrations/20210401095614_FE-835-Fix-Markdown.cs
3,973
C#
 //using Microsoft.Extensions.Logging; //using Serilog; //using Serilog.Events; namespace BS.Domain { public class Dispatcher : IDispatcher { private IUnitOfWork _unitOfWork; private ILogger _logger; public Dispatcher(IUnitOfWork work, ILogger logger) { _unitOfWork = work; _logger = logger; } public T Process<T>(T message) where T : Types.Process { message.Execute(_unitOfWork); var log = $"Executed {@message} of type {message.GetType().Name}"; _logger.Debug(log, message); return message; } } }
20.5
79
0.57622
[ "MIT" ]
tmaski45/Book-Switcharoo
BS.Domain/Dispatcher.cs
658
C#
using Swisschain.Sirius.Sdk.Primitives; namespace Brokerage.Common.ReadModels.Blockchains { public class Protocol { public string Code { get; set; } public Capabilities Capabilities { get; set; } } }
20.909091
54
0.678261
[ "Apache-2.0" ]
KonstantinRyazantsev/Sirius.Brokerage
src/Brokerage.Common/ReadModels/Blockchains/Protocol.cs
232
C#
using CalorieTracker.Models.FoodEntries; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace CalorieTracker.Data.Mappings { class FoodEntryMap : IEntityTypeConfiguration<FoodEntry> { private const int FoodNameLength = 200; public void Configure(EntityTypeBuilder<FoodEntry> builder) { builder.ToTable("food_entry", "ct"); builder.HasKey(x => x.Id); builder.Property(x => x.Id).HasColumnName("id").IsRequired(); builder.Property(x => x.FoodName).HasColumnName("food_name").HasMaxLength(FoodNameLength); builder.Property(x => x.Calorie).HasColumnName("calorie"); builder.Property(x => x.Date).HasColumnName("date"); } } }
38.9
102
0.679949
[ "MIT" ]
tugrulelmas/CalorieTracker
src/Backend/CalorieTracker/Data/Mappings/FoodEntryMap.cs
780
C#