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
#if ODIN_INSPECTOR using System.Linq; using Sirenix.OdinInspector.Editor; namespace FPCSharpUnity.unity.Editor.unity_serialization { public static class OdinUtils { public static InspectorProperty getChildSmart(this InspectorProperty property, string name) => property.Children[name] // When placed in any PropertyGroupAttribute, value gets placed as child element in parent #groupName // https://odininspector.com/documentation/sirenix.odininspector.propertygroupattribute ?? property.Children.First(_ => _.Info.PropertyType == PropertyType.Group).Children.First(); } } #endif
43.642857
107
0.775777
[ "MIT" ]
FPCSharpUnity/FPCSharpUnity
parts/0000-library/Assets/Vendor/FPCSharpUnity/Editor/unity_serialization/OdinUtils.cs
611
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class WaveSpawnTanks : MonoBehaviour { public int WaveSize; public GameObject EnemyPrefab; public float EnemyInterval; public Transform spawnPoint; public float startTime; public Transform[] WayPoints; int enemyCount = 0; void Start() { InvokeRepeating("SpawnEnemy", startTime, EnemyInterval); } void Update() { if (enemyCount == WaveSize) { CancelInvoke("SpawnEnemy"); } } void SpawnEnemy() { enemyCount++; GameObject enemy = GameObject.Instantiate(EnemyPrefab, spawnPoint.position, Quaternion.identity) as GameObject; enemy.GetComponent<TankEnemy>().waypoints = WayPoints; } }
23.914286
120
0.62963
[ "MIT" ]
balashanmugam/cmpt-742-project
Assets/TowerDefence_Vsquad/Scripts/Scripts_towers_enemies/WaveSpawnTanks.cs
839
C#
 using System; using Microsoft.AspNetCore.Authentication; using NetCore2.MVC.BasicAuthentication.Authentication; namespace Microsoft.AspNetCore.Builder { public static class BasicAuthenticationAppBuilderExtensions { public static AuthenticationBuilder AddBasic(this AuthenticationBuilder builder) => builder.AddBasic(BasicAuthenticationDefaults.AuthenticationScheme); public static AuthenticationBuilder AddBasic(this AuthenticationBuilder builder, string authenticationScheme) => builder.AddBasic(authenticationScheme, configureOptions: null); public static AuthenticationBuilder AddBasic(this AuthenticationBuilder builder, Action<BasicAuthenticationOptions> configureOptions) => builder.AddBasic(BasicAuthenticationDefaults.AuthenticationScheme, configureOptions); public static AuthenticationBuilder AddBasic( this AuthenticationBuilder builder, string authenticationScheme, Action<BasicAuthenticationOptions> configureOptions) { return builder.AddScheme<BasicAuthenticationOptions, BasicAuthenticationHandler>(authenticationScheme, configureOptions); } } }
39.16129
141
0.769357
[ "MIT" ]
Vladimir-Novick/NetCore2.MVC.BasicAuthentication
NetCore2.MVC.BasicAuthentication/Authentication/BasicAuthenticationExtensions.cs
1,216
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace GiveawayFreeSteamBot.Models { public class Channel : Config { } }
15.583333
37
0.743316
[ "MIT" ]
kuriharaa/GiveawayDiscordNotifier
src/Models/Channel.cs
189
C#
using System; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; namespace AppShapes.Core.Service { public class ConfigureWebHostConfigurationCommand { public void Execute(IWebHostBuilder builder, Action<WebHostBuilderContext, IConfigurationBuilder> options) { builder.ConfigureAppConfiguration(options); } } }
27.642857
114
0.744186
[ "Apache-2.0" ]
appshapes-org/dotnet-core
AppShapes.Core.Service/ConfigureWebHostConfigurationCommand.cs
389
C#
using System; using System.Collections.Generic; using Xamarin.Forms; using AppleMusic; namespace AppleMusicSample.Pages { public partial class PlaybackPage : ContentPage { Song song; public Song CurrentSong { get => song; set { song = value; OnPropertyChanged (); OnPropertyChanged (nameof (PlayBackButtonEnabled)); } } bool isPlaying; public bool IsPlaying { get => isPlaying; set { isPlaying = value; OnPropertyChanged (); OnPropertyChanged (nameof (PlaybackButtonText)); } } public string PlaybackButtonText => IsPlaying ? "Pause" : "Play"; public bool PlayBackButtonEnabled => CurrentSong != null; public PlaybackPage () { InitializeComponent (); this.BindingContext = this; } } }
18.214286
67
0.684967
[ "Apache-2.0" ]
Clancey/AppleMusicApi
Sample/AppleMusicSample/Pages/PlaybackPage.xaml.cs
767
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("07.BasicMath")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("07.BasicMath")] [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("537f74fa-db08-4340-b5bf-c7c2536364ef")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.621622
84
0.746408
[ "MIT" ]
l3kov9/CSharpOOPBasics
StaticMembers/07.BasicMath/Properties/AssemblyInfo.cs
1,395
C#
// <auto-generated /> using System; using BoxingStore.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace BoxingStore.Data.Migrations { [DbContext(typeof(BoxingStoreDbContext))] [Migration("20210730132758_UserFullNameColumn")] partial class UserFullNameColumn { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("ProductVersion", "5.0.7") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("BoxingStore.Data.Models.Category", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("Categories"); }); modelBuilder.Entity("BoxingStore.Data.Models.Product", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Brand") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<int>("CategoryId") .HasColumnType("int"); b.Property<string>("ConvertedName") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("Description") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("ImageUrl") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<double>("Price") .HasColumnType("float"); b.HasKey("Id"); b.HasIndex("CategoryId"); b.ToTable("Products"); }); modelBuilder.Entity("BoxingStore.Data.Models.ProductSizeQuantity", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("ProductId") .HasColumnType("int"); b.Property<int>("Quantity") .HasColumnType("int"); b.Property<string>("Size") .IsRequired() .HasColumnType("nvarchar(3)"); b.HasKey("Id"); b.HasIndex("ProductId"); b.ToTable("ProductSizeQuantities"); }); modelBuilder.Entity("BoxingStore.Data.Models.User", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<int>("AccessFailedCount") .HasColumnType("int"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<string>("Email") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<bool>("EmailConfirmed") .HasColumnType("bit"); b.Property<string>("FullName") .HasMaxLength(30) .HasColumnType("nvarchar(30)"); b.Property<bool>("LockoutEnabled") .HasColumnType("bit"); b.Property<DateTimeOffset?>("LockoutEnd") .HasColumnType("datetimeoffset"); b.Property<string>("NormalizedEmail") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("NormalizedUserName") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("PasswordHash") .HasColumnType("nvarchar(max)"); b.Property<string>("PhoneNumber") .HasColumnType("nvarchar(max)"); b.Property<bool>("PhoneNumberConfirmed") .HasColumnType("bit"); b.Property<string>("SecurityStamp") .HasColumnType("nvarchar(max)"); b.Property<bool>("TwoFactorEnabled") .HasColumnType("bit"); b.Property<string>("UserName") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasDatabaseName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasDatabaseName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("NormalizedName") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasDatabaseName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasColumnType("nvarchar(max)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<string>("RoleId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasColumnType("nvarchar(max)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("ProviderKey") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("ProviderDisplayName") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.Property<string>("RoleId") .HasColumnType("nvarchar(450)"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.Property<string>("LoginProvider") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("Name") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("Value") .HasColumnType("nvarchar(max)"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("BoxingStore.Data.Models.Product", b => { b.HasOne("BoxingStore.Data.Models.Category", "Category") .WithMany("Products") .HasForeignKey("CategoryId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Category"); }); modelBuilder.Entity("BoxingStore.Data.Models.ProductSizeQuantity", b => { b.HasOne("BoxingStore.Data.Models.Product", "Product") .WithMany("ProductSizeQuantities") .HasForeignKey("ProductId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Product"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("BoxingStore.Data.Models.User", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("BoxingStore.Data.Models.User", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("BoxingStore.Data.Models.User", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("BoxingStore.Data.Models.User", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("BoxingStore.Data.Models.Category", b => { b.Navigation("Products"); }); modelBuilder.Entity("BoxingStore.Data.Models.Product", b => { b.Navigation("ProductSizeQuantities"); }); #pragma warning restore 612, 618 } } }
37.251269
125
0.458472
[ "MIT" ]
Svetlin17/BoxingStore
BoxingStore/Data/Migrations/20210730132758_UserFullNameColumn.Designer.cs
14,679
C#
using UnityEngine; public class ShopManager : MonoBehaviour { protected ShopItem currentSelectedItem; public delegate void ShopItemEvent(ShopItem item); private static event ShopItemEvent SelectButton; public static event ShopItemEvent Purchase; void Start() { Shop.Close += RemoveSelectedButton; SelectButton += Select; } private void Select(ShopItem item) { RemoveSelectedButton(); currentSelectedItem = item; } protected void RemoveSelectedButton() { currentSelectedItem?.RemoveSelect(); currentSelectedItem = null; } public static void RemoveOtherSelectedButton(ShopItem item) { SelectButton?.Invoke(item); } public void PurchaseItem() { if (currentSelectedItem == null) { Debug.Log("Item not selected"); return; } if (GameAssets.Player.Items.Contains(currentSelectedItem.ItemID)) { Debug.Log("Такой предмет уже куплен"); return; } Purchase?.Invoke(currentSelectedItem); GameAssets.Player.WriteOffMoney(currentSelectedItem.Price); RemoveSelectedButton(); } }
23.113208
73
0.631837
[ "Apache-2.0" ]
maximbtw/HookWarsGame
Hook Wars/Assets/Scripts/ShopScripts/ShopManager.cs
1,248
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.Network { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// LoadBalancerLoadBalancingRulesOperations operations. /// </summary> internal partial class LoadBalancerLoadBalancingRulesOperations : IServiceOperations<NetworkManagementClient>, ILoadBalancerLoadBalancingRulesOperations { /// <summary> /// Initializes a new instance of the LoadBalancerLoadBalancingRulesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal LoadBalancerLoadBalancingRulesOperations(NetworkManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the NetworkManagementClient /// </summary> public NetworkManagementClient Client { get; private set; } /// <summary> /// Gets all the load balancing rules in a load balancer. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<LoadBalancingRule>>> ListWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (loadBalancerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "loadBalancerName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2019-02-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("loadBalancerName", loadBalancerName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/loadBalancingRules").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{loadBalancerName}", System.Uri.EscapeDataString(loadBalancerName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<LoadBalancingRule>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<LoadBalancingRule>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets the specified load balancer load balancing rule. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='loadBalancingRuleName'> /// The name of the load balancing rule. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<LoadBalancingRule>> GetWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, string loadBalancingRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (loadBalancerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "loadBalancerName"); } if (loadBalancingRuleName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "loadBalancingRuleName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2019-02-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("loadBalancerName", loadBalancerName); tracingParameters.Add("loadBalancingRuleName", loadBalancingRuleName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/loadBalancingRules/{loadBalancingRuleName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{loadBalancerName}", System.Uri.EscapeDataString(loadBalancerName)); _url = _url.Replace("{loadBalancingRuleName}", System.Uri.EscapeDataString(loadBalancingRuleName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<LoadBalancingRule>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<LoadBalancingRule>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all the load balancing rules in a load balancer. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<LoadBalancingRule>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<LoadBalancingRule>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<LoadBalancingRule>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
45.5888
295
0.566174
[ "MIT" ]
0xced/azure-sdk-for-net
src/SDKs/Network/Management.Network/Generated/LoadBalancerLoadBalancingRulesOperations.cs
28,493
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using Alex.Blocks.State; using Alex.Common.Utils.Vectors; using Alex.Worlds.Abstraction; using Alex.Worlds.Chunks; namespace Alex.Worlds; public class CollisionBlockAccess : IBlockAccess, IDisposable { private readonly IBlockAccess _source; private ConcurrentDictionary<BlockCoordinates, BlockState> _cached = new ConcurrentDictionary<BlockCoordinates, BlockState>(); public CollisionBlockAccess(IBlockAccess source) { _source = source; } /// <inheritdoc /> public ChunkColumn GetChunk(BlockCoordinates coordinates, bool cacheOnly = false) { throw new System.NotImplementedException(); } /// <inheritdoc /> public ChunkColumn GetChunk(ChunkCoordinates coordinates, bool cacheOnly = false) { throw new System.NotImplementedException(); } /// <inheritdoc /> public void SetSkyLight(BlockCoordinates coordinates, byte skyLight) { throw new System.NotImplementedException(); } /// <inheritdoc /> public byte GetSkyLight(BlockCoordinates coordinates) { throw new System.NotImplementedException(); } /// <inheritdoc /> public byte GetBlockLight(BlockCoordinates coordinates) { throw new System.NotImplementedException(); } /// <inheritdoc /> public void SetBlockLight(BlockCoordinates coordinates, byte blockLight) { throw new System.NotImplementedException(); } /// <inheritdoc /> public bool TryGetBlockLight(BlockCoordinates coordinates, out byte blockLight) { throw new System.NotImplementedException(); } /// <inheritdoc /> public void GetLight(BlockCoordinates coordinates, out byte blockLight, out byte skyLight) { throw new System.NotImplementedException(); } /// <inheritdoc /> public int GetHeight(BlockCoordinates coordinates) { throw new System.NotImplementedException(); } /// <inheritdoc /> public IEnumerable<ChunkSection.BlockEntry> GetBlockStates(int positionX, int positionY, int positionZ) { throw new System.NotImplementedException(); } /// <inheritdoc /> public BlockState GetBlockState(BlockCoordinates position) { return _cached.GetOrAdd(position, v => _source.GetBlockState(v)); } /// <inheritdoc /> public void SetBlockState(int x, int y, int z, BlockState block, int storage, BlockUpdatePriority priority = BlockUpdatePriority.High) { throw new System.NotImplementedException(); } /// <inheritdoc /> public Biome GetBiome(BlockCoordinates coordinates) { throw new System.NotImplementedException(); } /// <inheritdoc /> public void Dispose() { } }
23.577982
127
0.756031
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
codingwatching/Alex
src/Alex/Worlds/CollissionBlockAccess.cs
2,570
C#
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Windows.Controls; using System.Windows.Media; using ICSharpCode.AvalonEdit.CodeCompletion; using ICSharpCode.Core; using ICSharpCode.NRefactory; using ICSharpCode.NRefactory.TypeSystem; using ICSharpCode.NRefactory.TypeSystem.Implementation; using ICSharpCode.SharpDevelop; using ICSharpCode.SharpDevelop.Parser; using ICSharpCode.SharpDevelop.Project; namespace ICSharpCode.AvalonEdit.AddIn { /// <summary> /// Panel with two combo boxes. Used to quickly navigate to entities in the current file. /// </summary> public partial class QuickClassBrowser : UserControl { /// <summary> /// ViewModel used for combobox items. /// </summary> class EntityItem : IComparable<EntityItem>, System.ComponentModel.INotifyPropertyChanged { IUnresolvedEntity entity; ImageSource image; string text; public IUnresolvedEntity Entity { get { return entity; } } public EntityItem(IUnresolvedTypeDefinition typeDef, ICompilation compilation) { this.IsInSamePart = true; this.entity = typeDef; var resolvedDefinition = typeDef.Resolve(new SimpleTypeResolveContext(compilation.MainAssembly)).GetDefinition(); if (resolvedDefinition != null) { var ambience = compilation.GetAmbience(); ambience.ConversionFlags = ConversionFlags.ShowTypeParameterList | ConversionFlags.ShowDeclaringType; this.text = ambience.ConvertSymbol(resolvedDefinition); } else { this.text = typeDef.Name; } this.image = CompletionImage.GetImage(typeDef); } public EntityItem(IMember member, IAmbience ambience) { this.IsInSamePart = true; this.entity = member.UnresolvedMember; ambience.ConversionFlags = ConversionFlags.ShowTypeParameterList | ConversionFlags.ShowParameterList | ConversionFlags.ShowParameterNames; text = ambience.ConvertSymbol(member); image = CompletionImage.GetImage(member); } /// <summary> /// Text to display in combo box. /// </summary> public string Text { get { return text; } } /// <summary> /// Image to use in combox box /// </summary> public ImageSource Image { get { return image; } } /// <summary> /// Gets/Sets whether the item is in the current file. /// </summary> /// <returns> /// <c>true</c>: item is in current file; /// <c>false</c>: item is in another part of the partial class /// </returns> public bool IsInSamePart { get; set; } public int CompareTo(EntityItem other) { int r = this.Entity.SymbolKind.CompareTo(other.Entity.SymbolKind); if (r != 0) return r; r = string.Compare(text, other.text, StringComparison.OrdinalIgnoreCase); if (r != 0) return r; return string.Compare(text, other.text, StringComparison.Ordinal); } /// <summary> /// ToString override is necessary to support keyboard navigation in WPF /// </summary> public override string ToString() { return text; } // I'm not sure if it actually was a leak or caused by something else, but I saw QCB.EntityItem being alive for longer // than it should when looking at the heap with WinDbg. // Maybe this was caused by http://support.microsoft.com/kb/938416/en-us, so I'm adding INotifyPropertyChanged to be sure. event System.ComponentModel.PropertyChangedEventHandler System.ComponentModel.INotifyPropertyChanged.PropertyChanged { add { } remove { } } } public QuickClassBrowser() { InitializeComponent(); } /// <summary> /// Updates the list of available classes. /// This causes the classes combo box to lose its current selection, /// so the members combo box will be cleared. /// </summary> public void Update(IUnresolvedFile compilationUnit) { runUpdateWhenDropDownClosed = true; runUpdateWhenDropDownClosedCU = compilationUnit; if (!IsDropDownOpen) ComboBox_DropDownClosed(null, null); } // The lists of items currently visible in the combo boxes. // These should never be null. List<EntityItem> classItems = new List<EntityItem>(); List<EntityItem> memberItems = new List<EntityItem>(); void DoUpdate(IUnresolvedFile unresolvedFile) { classItems = new List<EntityItem>(); if (unresolvedFile != null) { ICompilation compilation = SD.ParserService.GetCompilationForFile(FileName.Create(unresolvedFile.FileName)); AddClasses(unresolvedFile.TopLevelTypeDefinitions, compilation); } classItems.Sort(); classComboBox.ItemsSource = classItems; } bool IsDropDownOpen { get { return classComboBox.IsDropDownOpen || membersComboBox.IsDropDownOpen; } } // Delayed execution - avoid changing combo boxes while the user is browsing the dropdown list. bool runUpdateWhenDropDownClosed; IUnresolvedFile runUpdateWhenDropDownClosedCU; bool runSelectItemWhenDropDownClosed; TextLocation runSelectItemWhenDropDownClosedLocation; void ComboBox_DropDownClosed(object sender, EventArgs e) { if (runUpdateWhenDropDownClosed) { runUpdateWhenDropDownClosed = false; DoUpdate(runUpdateWhenDropDownClosedCU); runUpdateWhenDropDownClosedCU = null; } if (runSelectItemWhenDropDownClosed) { runSelectItemWhenDropDownClosed = false; DoSelectItem(runSelectItemWhenDropDownClosedLocation); } } void AddClasses(IEnumerable<IUnresolvedTypeDefinition> classes, ICompilation compilation) { foreach (var c in classes) { if (c.IsSynthetic) continue; classItems.Add(new EntityItem(c, compilation)); AddClasses(c.NestedTypes, compilation); } } /// <summary> /// Selects the class and member closest to the specified location. /// </summary> public void SelectItemAtCaretPosition(TextLocation location) { runSelectItemWhenDropDownClosed = true; runSelectItemWhenDropDownClosedLocation = location; if (!IsDropDownOpen) ComboBox_DropDownClosed(null, null); } void DoSelectItem(TextLocation location) { EntityItem matchInside = null; EntityItem nearestMatch = null; int nearestMatchDistance = int.MaxValue; foreach (EntityItem item in classItems) { if (item.IsInSamePart) { IUnresolvedTypeDefinition c = (IUnresolvedTypeDefinition)item.Entity; if (c.Region.IsInside(location.Line, location.Column)) { matchInside = item; // when there are multiple matches inside (nested classes), use the last one } else { // Not a perfect match? // Try to first the nearest match. We want the classes combo box to always // have a class selected if possible. int matchDistance = Math.Min(Math.Abs(location.Line - c.Region.BeginLine), Math.Abs(location.Line - c.Region.EndLine)); if (matchDistance < nearestMatchDistance) { nearestMatchDistance = matchDistance; nearestMatch = item; } } } } jumpOnSelectionChange = false; try { classComboBox.SelectedItem = matchInside ?? nearestMatch; // the SelectedItem setter will update the list of member items } finally { jumpOnSelectionChange = true; } matchInside = null; foreach (EntityItem item in memberItems) { if (item.IsInSamePart) { IUnresolvedMember member = (IUnresolvedMember)item.Entity; if (member.Region.IsInside(location.Line, location.Column) || member.BodyRegion.IsInside(location.Line, location.Column)) { matchInside = item; } } } jumpOnSelectionChange = false; try { membersComboBox.SelectedItem = matchInside; } finally { jumpOnSelectionChange = true; } } bool jumpOnSelectionChange = true; void classComboBoxSelectionChanged(object sender, SelectionChangedEventArgs e) { // The selected class was changed. // Update the list of member items to be the list of members of the current class. EntityItem item = classComboBox.SelectedItem as EntityItem; IUnresolvedTypeDefinition selectedClass = item != null ? item.Entity as IUnresolvedTypeDefinition : null; memberItems = new List<EntityItem>(); if (selectedClass != null) { ICompilation compilation = SD.ParserService.GetCompilationForFile(FileName.Create(selectedClass.UnresolvedFile.FileName)); var context = new SimpleTypeResolveContext(compilation.MainAssembly); ITypeDefinition compoundClass = selectedClass.Resolve(context).GetDefinition(); if (compoundClass != null) { var ambience = compilation.GetAmbience(); foreach (var member in compoundClass.Members) { if (member.IsSynthetic) continue; bool isInSamePart = string.Equals(member.Region.FileName, selectedClass.Region.FileName, StringComparison.OrdinalIgnoreCase); memberItems.Add(new EntityItem(member, ambience) { IsInSamePart = isInSamePart }); } memberItems.Sort(); if (jumpOnSelectionChange) { SD.AnalyticsMonitor.TrackFeature(GetType(), "JumpToClass"); JumpTo(item, selectedClass.Region); } } } membersComboBox.ItemsSource = memberItems; } void membersComboBoxSelectionChanged(object sender, SelectionChangedEventArgs e) { EntityItem item = membersComboBox.SelectedItem as EntityItem; if (item != null) { IUnresolvedMember member = item.Entity as IUnresolvedMember; if (member != null && jumpOnSelectionChange) { SD.AnalyticsMonitor.TrackFeature(GetType(), "JumpToMember"); JumpTo(item, member.Region); } } } void JumpTo(EntityItem item, DomRegion region) { if (region.IsEmpty) return; Action<int, int> jumpAction = this.JumpAction; if (item.IsInSamePart && jumpAction != null) { jumpAction(region.BeginLine, region.BeginColumn); } else { FileService.JumpToFilePosition(region.FileName, region.BeginLine, region.BeginColumn); } } /// <summary> /// Action used for jumping to a position inside the current file. /// </summary> public Action<int, int> JumpAction { get; set; } } }
35.231013
142
0.718764
[ "MIT" ]
galich/SharpDevelop
src/AddIns/DisplayBindings/AvalonEdit.AddIn/Src/QuickClassBrowser.cs
11,135
C#
//----------------------------------------------------------------------------- // Copyright (c) 2017-2021 informedcitizenry <informedcitizenry@gmail.com> // // Licensed under the MIT license. See LICENSE for full license information. // //----------------------------------------------------------------------------- using Newtonsoft.Json.Linq; using System; namespace Core6502DotNet.Json { /// <summary> /// Represents an error encountered during the building of a /// schema object from parsed JSON. /// </summary> public sealed class SchemaBuilderException : Exception { /// <summary> /// Creates a new instance of a <see cref="SchemaBuilderException"/>. /// </summary> /// <param name="message">The error message.</param> /// <param name="token">The <see cref="JToken"/> at the point the error occurred.</param> public SchemaBuilderException(string message, JToken token) : base($"Error in schema: {message}\nAt: {token.ToJsonPointer()}") => JsonPointer = token.ToJsonPointer(); /// <summary> /// Creates a new instance of a <see cref="SchemaBuilderException"/>. /// </summary> /// <param name="message">The error message.</param> /// <param name="jsonPointer">The JSON pointer path at the point the error occurrred.</param> public SchemaBuilderException(string message, string jsonPointer) : base(message) => JsonPointer = jsonPointer; /// <summary> /// Gets the JSON pointer of the path the error occurred. /// </summary> public string JsonPointer { get; } } }
39.428571
118
0.574275
[ "MIT" ]
informedcitizenry/6502.Net
Core6502DotNet/src/Utility/Json/SchemaBuilderException.cs
1,658
C#
using UnityEngine; namespace theGame { class TheGame : MonoBehaviour { public static bool Inited; #region Singleton private static TheGame _instance; public static TheGame Instance { get { if (_instance == null) { _instance = new GameObject("theGame").AddComponent<TheGame>(); DontDestroyOnLoad(_instance.gameObject); } return _instance; } } #endregion #region Methods public new static T GetComponent<T>() where T : TheGameComponent { return Instance.gameObject.GetComponent<T>(); } public static T AddComponent<T>() where T : TheGameComponent { var go = Instance.gameObject.AddComponent<T>(); go.Init(); return go; } public static T ReloadComponent<T>() where T : TheGameComponent { var go = Instance.gameObject.GetComponent<T>(); if (go != null) { Destroy(go); go = Instance.gameObject.AddComponent<T>(); go.Init(); return go; } return null; } public static void RemoveComponent<T>() where T : TheGameComponent { if(Instance.gameObject.GetComponent<T>()) DestroyImmediate(Instance.gameObject.GetComponent<T>()); } #endregion private void OnDestroy() { Exit(); } // Use this for initialization void Start() { } // Update is called once per frame void Update() { } public void Init() { Inited = true; var lang = new Lang(); var daySwitcher = new Gui.DaySwitcher(); lang.Load(); AddComponent<GameData>(); AddComponent<Admob>(); //AddComponent<GamePlayer>(); AddComponent<BackgroundData>(); //AddComponent<SoundManager>(); AddComponent<GameDataModel>(); } public void Exit() { } } }
23.479592
82
0.476749
[ "MIT" ]
koderon/Full-Sources-Game
Scripts/theGame/TheGame.cs
2,303
C#
using MediatR; using Microsoft.Extensions.Logging; using System; using System.Threading; using System.Threading.Tasks; namespace OrderingApplication.Behaviours { public class UnhandledExceptionBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> where TRequest : IRequest<TResponse> { private readonly ILogger<TRequest> _logger; public UnhandledExceptionBehaviour(ILogger<TRequest> logger) { _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next) { try { return await next(); } catch (Exception ex) { var requestName = typeof(TRequest).Name; _logger.LogError(ex, "Application Request: Unhandled Exception for Request {Name} {@Request}", requestName, request); throw; } } } }
31.588235
143
0.631285
[ "MIT" ]
srinathvaradan10/aspnetMicroServices
src/Services/Ordering/OrderingApplication/Behaviours/UnhandledExceptionBehaviour.cs
1,076
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Collections.Generic; using System.Globalization; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; using Azure.ResourceManager; using Azure.ResourceManager.Compute.Models; using Azure.ResourceManager.Core; namespace Azure.ResourceManager.Compute { /// <summary> A Class representing a GalleryApplication along with the instance operations that can be performed on it. </summary> public partial class GalleryApplication : ArmResource { /// <summary> Generate the resource identifier of a <see cref="GalleryApplication"/> instance. </summary> public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string galleryName, string galleryApplicationName) { var resourceId = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/applications/{galleryApplicationName}"; return new ResourceIdentifier(resourceId); } private readonly ClientDiagnostics _clientDiagnostics; private readonly GalleryApplicationsRestOperations _galleryApplicationsRestClient; private readonly GalleryApplicationData _data; /// <summary> Initializes a new instance of the <see cref="GalleryApplication"/> class for mocking. </summary> protected GalleryApplication() { } /// <summary> Initializes a new instance of the <see cref = "GalleryApplication"/> class. </summary> /// <param name="options"> The client parameters to use in these operations. </param> /// <param name="data"> The resource that is the target of operations. </param> internal GalleryApplication(ArmResource options, GalleryApplicationData data) : base(options, data.Id) { HasData = true; _data = data; _clientDiagnostics = new ClientDiagnostics(ClientOptions); _galleryApplicationsRestClient = new GalleryApplicationsRestOperations(_clientDiagnostics, Pipeline, ClientOptions, BaseUri); #if DEBUG ValidateResourceId(Id); #endif } /// <summary> Initializes a new instance of the <see cref="GalleryApplication"/> class. </summary> /// <param name="options"> The client parameters to use in these operations. </param> /// <param name="id"> The identifier of the resource that is the target of operations. </param> internal GalleryApplication(ArmResource options, ResourceIdentifier id) : base(options, id) { _clientDiagnostics = new ClientDiagnostics(ClientOptions); _galleryApplicationsRestClient = new GalleryApplicationsRestOperations(_clientDiagnostics, Pipeline, ClientOptions, BaseUri); #if DEBUG ValidateResourceId(Id); #endif } /// <summary> Initializes a new instance of the <see cref="GalleryApplication"/> class. </summary> /// <param name="clientOptions"> The client options to build client context. </param> /// <param name="credential"> The credential to build client context. </param> /// <param name="uri"> The uri to build client context. </param> /// <param name="pipeline"> The pipeline to build client context. </param> /// <param name="id"> The identifier of the resource that is the target of operations. </param> internal GalleryApplication(ArmClientOptions clientOptions, TokenCredential credential, Uri uri, HttpPipeline pipeline, ResourceIdentifier id) : base(clientOptions, credential, uri, pipeline, id) { _clientDiagnostics = new ClientDiagnostics(ClientOptions); _galleryApplicationsRestClient = new GalleryApplicationsRestOperations(_clientDiagnostics, Pipeline, ClientOptions, BaseUri); #if DEBUG ValidateResourceId(Id); #endif } /// <summary> Gets the resource type for the operations. </summary> public static readonly ResourceType ResourceType = "Microsoft.Compute/galleries/applications"; /// <summary> Gets whether or not the current instance has data. </summary> public virtual bool HasData { get; } /// <summary> Gets the data representing this Feature. </summary> /// <exception cref="InvalidOperationException"> Throws if there is no data loaded in the current instance. </exception> public virtual GalleryApplicationData Data { get { if (!HasData) throw new InvalidOperationException("The current instance does not have data, you must call Get first."); return _data; } } internal static void ValidateResourceId(ResourceIdentifier id) { if (id.ResourceType != ResourceType) throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id)); } /// <summary> Retrieves information about a gallery Application Definition. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public async virtual Task<Response<GalleryApplication>> GetAsync(CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("GalleryApplication.Get"); scope.Start(); try { var response = await _galleryApplicationsRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false); if (response.Value == null) throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(response.GetRawResponse()).ConfigureAwait(false); return Response.FromValue(new GalleryApplication(this, response.Value), response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Retrieves information about a gallery Application Definition. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual Response<GalleryApplication> Get(CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("GalleryApplication.Get"); scope.Start(); try { var response = _galleryApplicationsRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken); if (response.Value == null) throw _clientDiagnostics.CreateRequestFailedException(response.GetRawResponse()); return Response.FromValue(new GalleryApplication(this, response.Value), response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Lists all available geo-locations. </summary> /// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param> /// <returns> A collection of locations that may take multiple service requests to iterate over. </returns> public async virtual Task<IEnumerable<AzureLocation>> GetAvailableLocationsAsync(CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("GalleryApplication.GetAvailableLocations"); scope.Start(); try { return await ListAvailableLocationsAsync(ResourceType, cancellationToken).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Lists all available geo-locations. </summary> /// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param> /// <returns> A collection of locations that may take multiple service requests to iterate over. </returns> public virtual IEnumerable<AzureLocation> GetAvailableLocations(CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("GalleryApplication.GetAvailableLocations"); scope.Start(); try { return ListAvailableLocations(ResourceType, cancellationToken); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Delete a gallery Application. </summary> /// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public async virtual Task<GalleryApplicationDeleteOperation> DeleteAsync(bool waitForCompletion, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("GalleryApplication.Delete"); scope.Start(); try { var response = await _galleryApplicationsRestClient.DeleteAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false); var operation = new GalleryApplicationDeleteOperation(_clientDiagnostics, Pipeline, _galleryApplicationsRestClient.CreateDeleteRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name).Request, response); if (waitForCompletion) await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false); return operation; } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Delete a gallery Application. </summary> /// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual GalleryApplicationDeleteOperation Delete(bool waitForCompletion, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("GalleryApplication.Delete"); scope.Start(); try { var response = _galleryApplicationsRestClient.Delete(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken); var operation = new GalleryApplicationDeleteOperation(_clientDiagnostics, Pipeline, _galleryApplicationsRestClient.CreateDeleteRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name).Request, response); if (waitForCompletion) operation.WaitForCompletion(cancellationToken); return operation; } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Add a tag to the current resource. </summary> /// <param name="key"> The key for the tag. </param> /// <param name="value"> The value for the tag. </param> /// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param> /// <returns> The updated resource with the tag added. </returns> public async virtual Task<Response<GalleryApplication>> AddTagAsync(string key, string value, CancellationToken cancellationToken = default) { if (string.IsNullOrWhiteSpace(key)) { throw new ArgumentNullException(nameof(key), $"{nameof(key)} provided cannot be null or a whitespace."); } using var scope = _clientDiagnostics.CreateScope("GalleryApplication.AddTag"); scope.Start(); try { var originalTags = await TagResource.GetAsync(cancellationToken).ConfigureAwait(false); originalTags.Value.Data.Properties.TagsValue[key] = value; await TagResource.CreateOrUpdateAsync(originalTags.Value.Data, cancellationToken: cancellationToken).ConfigureAwait(false); var originalResponse = await _galleryApplicationsRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false); return Response.FromValue(new GalleryApplication(this, originalResponse.Value), originalResponse.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Add a tag to the current resource. </summary> /// <param name="key"> The key for the tag. </param> /// <param name="value"> The value for the tag. </param> /// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param> /// <returns> The updated resource with the tag added. </returns> public virtual Response<GalleryApplication> AddTag(string key, string value, CancellationToken cancellationToken = default) { if (string.IsNullOrWhiteSpace(key)) { throw new ArgumentNullException(nameof(key), $"{nameof(key)} provided cannot be null or a whitespace."); } using var scope = _clientDiagnostics.CreateScope("GalleryApplication.AddTag"); scope.Start(); try { var originalTags = TagResource.Get(cancellationToken); originalTags.Value.Data.Properties.TagsValue[key] = value; TagResource.CreateOrUpdate(originalTags.Value.Data, cancellationToken: cancellationToken); var originalResponse = _galleryApplicationsRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken); return Response.FromValue(new GalleryApplication(this, originalResponse.Value), originalResponse.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Replace the tags on the resource with the given set. </summary> /// <param name="tags"> The set of tags to use as replacement. </param> /// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param> /// <returns> The updated resource with the tags replaced. </returns> public async virtual Task<Response<GalleryApplication>> SetTagsAsync(IDictionary<string, string> tags, CancellationToken cancellationToken = default) { if (tags == null) { throw new ArgumentNullException(nameof(tags), $"{nameof(tags)} provided cannot be null."); } using var scope = _clientDiagnostics.CreateScope("GalleryApplication.SetTags"); scope.Start(); try { await TagResource.DeleteAsync(cancellationToken: cancellationToken).ConfigureAwait(false); var originalTags = await TagResource.GetAsync(cancellationToken).ConfigureAwait(false); originalTags.Value.Data.Properties.TagsValue.ReplaceWith(tags); await TagResource.CreateOrUpdateAsync(originalTags.Value.Data, cancellationToken: cancellationToken).ConfigureAwait(false); var originalResponse = await _galleryApplicationsRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false); return Response.FromValue(new GalleryApplication(this, originalResponse.Value), originalResponse.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Replace the tags on the resource with the given set. </summary> /// <param name="tags"> The set of tags to use as replacement. </param> /// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param> /// <returns> The updated resource with the tags replaced. </returns> public virtual Response<GalleryApplication> SetTags(IDictionary<string, string> tags, CancellationToken cancellationToken = default) { if (tags == null) { throw new ArgumentNullException(nameof(tags), $"{nameof(tags)} provided cannot be null."); } using var scope = _clientDiagnostics.CreateScope("GalleryApplication.SetTags"); scope.Start(); try { TagResource.Delete(cancellationToken: cancellationToken); var originalTags = TagResource.Get(cancellationToken); originalTags.Value.Data.Properties.TagsValue.ReplaceWith(tags); TagResource.CreateOrUpdate(originalTags.Value.Data, cancellationToken: cancellationToken); var originalResponse = _galleryApplicationsRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken); return Response.FromValue(new GalleryApplication(this, originalResponse.Value), originalResponse.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Removes a tag by key from the resource. </summary> /// <param name="key"> The key of the tag to remove. </param> /// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param> /// <returns> The updated resource with the tag removed. </returns> public async virtual Task<Response<GalleryApplication>> RemoveTagAsync(string key, CancellationToken cancellationToken = default) { if (string.IsNullOrWhiteSpace(key)) { throw new ArgumentNullException(nameof(key), $"{nameof(key)} provided cannot be null or a whitespace."); } using var scope = _clientDiagnostics.CreateScope("GalleryApplication.RemoveTag"); scope.Start(); try { var originalTags = await TagResource.GetAsync(cancellationToken).ConfigureAwait(false); originalTags.Value.Data.Properties.TagsValue.Remove(key); await TagResource.CreateOrUpdateAsync(originalTags.Value.Data, cancellationToken: cancellationToken).ConfigureAwait(false); var originalResponse = await _galleryApplicationsRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false); return Response.FromValue(new GalleryApplication(this, originalResponse.Value), originalResponse.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Removes a tag by key from the resource. </summary> /// <param name="key"> The key of the tag to remove. </param> /// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param> /// <returns> The updated resource with the tag removed. </returns> public virtual Response<GalleryApplication> RemoveTag(string key, CancellationToken cancellationToken = default) { if (string.IsNullOrWhiteSpace(key)) { throw new ArgumentNullException(nameof(key), $"{nameof(key)} provided cannot be null or a whitespace."); } using var scope = _clientDiagnostics.CreateScope("GalleryApplication.RemoveTag"); scope.Start(); try { var originalTags = TagResource.Get(cancellationToken); originalTags.Value.Data.Properties.TagsValue.Remove(key); TagResource.CreateOrUpdate(originalTags.Value.Data, cancellationToken: cancellationToken); var originalResponse = _galleryApplicationsRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken); return Response.FromValue(new GalleryApplication(this, originalResponse.Value), originalResponse.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Update a gallery Application Definition. </summary> /// <param name="galleryApplication"> Parameters supplied to the update gallery Application operation. </param> /// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="galleryApplication"/> is null. </exception> public async virtual Task<GalleryApplicationUpdateOperation> UpdateAsync(bool waitForCompletion, GalleryApplicationUpdate galleryApplication, CancellationToken cancellationToken = default) { if (galleryApplication == null) { throw new ArgumentNullException(nameof(galleryApplication)); } using var scope = _clientDiagnostics.CreateScope("GalleryApplication.Update"); scope.Start(); try { var response = await _galleryApplicationsRestClient.UpdateAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, galleryApplication, cancellationToken).ConfigureAwait(false); var operation = new GalleryApplicationUpdateOperation(this, _clientDiagnostics, Pipeline, _galleryApplicationsRestClient.CreateUpdateRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, galleryApplication).Request, response); if (waitForCompletion) await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); return operation; } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Update a gallery Application Definition. </summary> /// <param name="galleryApplication"> Parameters supplied to the update gallery Application operation. </param> /// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="galleryApplication"/> is null. </exception> public virtual GalleryApplicationUpdateOperation Update(bool waitForCompletion, GalleryApplicationUpdate galleryApplication, CancellationToken cancellationToken = default) { if (galleryApplication == null) { throw new ArgumentNullException(nameof(galleryApplication)); } using var scope = _clientDiagnostics.CreateScope("GalleryApplication.Update"); scope.Start(); try { var response = _galleryApplicationsRestClient.Update(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, galleryApplication, cancellationToken); var operation = new GalleryApplicationUpdateOperation(this, _clientDiagnostics, Pipeline, _galleryApplicationsRestClient.CreateUpdateRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, galleryApplication).Request, response); if (waitForCompletion) operation.WaitForCompletion(cancellationToken); return operation; } catch (Exception e) { scope.Failed(e); throw; } } #region GalleryApplicationVersion /// <summary> Gets a collection of GalleryApplicationVersions in the GalleryApplication. </summary> /// <returns> An object representing collection of GalleryApplicationVersions and their operations over a GalleryApplication. </returns> public virtual GalleryApplicationVersionCollection GetGalleryApplicationVersions() { return new GalleryApplicationVersionCollection(this); } #endregion } }
55.006438
262
0.650763
[ "MIT" ]
AhmedLeithy/azure-sdk-for-net
sdk/compute/Azure.ResourceManager.Compute/src/Generated/GalleryApplication.cs
25,633
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="NamingRegistrationConvention.cs" company="Catel development team"> // Copyright (c) 2008 - 2014 Catel development team. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Catel.IoC { using System; using System.Collections.Generic; using System.Linq; using Collections; using Logging; using Reflection; /// <summary> /// The naming convention based on <see cref="RegistrationConventionBase"/>. /// </summary> public class NamingRegistrationConvention : RegistrationConventionBase { #region Fields /// <summary> /// The log. /// </summary> private static readonly ILog Log = LogManager.GetCurrentClassLogger(); #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="NamingRegistrationConvention" /> class. /// </summary> /// <param name="serviceLocator">The service locator.</param> /// <param name="registrationType">Type of the registration.</param> public NamingRegistrationConvention(IServiceLocator serviceLocator, RegistrationType registrationType = RegistrationType.Singleton) : base(serviceLocator, registrationType) { } #endregion #region Methods /// <summary> /// Processes the specified types to register. /// </summary> /// <param name="typesToRegister">The types to register.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="typesToRegister" /> is <c>null</c>.</exception> public override void Process(IEnumerable<Type> typesToRegister) { Argument.IsNotNull("typesToRegister", typesToRegister); var typesToHandle = typesToRegister as Type[] ?? typesToRegister.ToArray(); var interfaceTypes = typesToHandle.Select(type => { if (type.IsInterfaceEx() && type.Name.StartsWith("I")) { var implementationType = typesToHandle.FirstOrDefault(row => TagHelper.AreTagsEqual(row.Name, type.Name.Replace("I", string.Empty).Trim()) && row.IsClassEx() && type.IsAssignableFromEx(row)); if (implementationType != null) { return new {InterfaceType = type, ImplementationType = implementationType}; } } return null; }).Where(type => type != null); interfaceTypes.ForEach(type => { Log.Debug("Applying '{0}' on '{1}'", GetType().Name, type.InterfaceType); Container.RegisterType(type.InterfaceType, type.ImplementationType, registrationType: RegistrationType); }); } #endregion } }
40.5
211
0.557505
[ "MIT" ]
IvanKupriyanov/Catel
src/Catel.Core/Catel.Core.Shared/IoC/Conventions/NamingRegistrationConvention.cs
3,080
C#
namespace SistemaHotel { partial class frmCliente { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.tcCliente = new System.Windows.Forms.TabControl(); this.tpgClientes = new System.Windows.Forms.TabPage(); this.dgvClientes = new System.Windows.Forms.DataGridView(); this.panel4 = new System.Windows.Forms.Panel(); this.btnExcluir = new System.Windows.Forms.Button(); this.btnEditar = new System.Windows.Forms.Button(); this.btnNovo = new System.Windows.Forms.Button(); this.tpgCriarCliente = new System.Windows.Forms.TabPage(); this.txtRG = new System.Windows.Forms.MaskedTextBox(); this.txtCPF = new System.Windows.Forms.MaskedTextBox(); this.label5 = new System.Windows.Forms.Label(); this.txtDtNasc = new System.Windows.Forms.MaskedTextBox(); this.label4 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.txtUltimoNome = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.txtPrimeiroNome = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.panel2 = new System.Windows.Forms.Panel(); this.btnCancelar = new System.Windows.Forms.Button(); this.btnSalvar = new System.Windows.Forms.Button(); this.panel1 = new System.Windows.Forms.Panel(); this.btnSair = new System.Windows.Forms.Button(); this.tcCliente.SuspendLayout(); this.tpgClientes.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dgvClientes)).BeginInit(); this.panel4.SuspendLayout(); this.tpgCriarCliente.SuspendLayout(); this.panel2.SuspendLayout(); this.panel1.SuspendLayout(); this.SuspendLayout(); // // tcCliente // this.tcCliente.Controls.Add(this.tpgClientes); this.tcCliente.Controls.Add(this.tpgCriarCliente); this.tcCliente.Dock = System.Windows.Forms.DockStyle.Top; this.tcCliente.Location = new System.Drawing.Point(0, 0); this.tcCliente.Name = "tcCliente"; this.tcCliente.SelectedIndex = 0; this.tcCliente.Size = new System.Drawing.Size(800, 400); this.tcCliente.TabIndex = 0; // // tpgClientes // this.tpgClientes.Controls.Add(this.dgvClientes); this.tpgClientes.Controls.Add(this.panel4); this.tpgClientes.Location = new System.Drawing.Point(4, 22); this.tpgClientes.Name = "tpgClientes"; this.tpgClientes.Padding = new System.Windows.Forms.Padding(3); this.tpgClientes.Size = new System.Drawing.Size(792, 374); this.tpgClientes.TabIndex = 0; this.tpgClientes.Text = "Clientes"; this.tpgClientes.UseVisualStyleBackColor = true; // // dgvClientes // this.dgvClientes.AllowUserToAddRows = false; this.dgvClientes.AllowUserToDeleteRows = false; this.dgvClientes.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dgvClientes.Dock = System.Windows.Forms.DockStyle.Fill; this.dgvClientes.Location = new System.Drawing.Point(3, 3); this.dgvClientes.MultiSelect = false; this.dgvClientes.Name = "dgvClientes"; this.dgvClientes.ReadOnly = true; this.dgvClientes.Size = new System.Drawing.Size(786, 339); this.dgvClientes.TabIndex = 3; this.dgvClientes.CellMouseDoubleClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.dgvClientes_CellMouseDoubleClick); // // panel4 // this.panel4.Controls.Add(this.btnExcluir); this.panel4.Controls.Add(this.btnEditar); this.panel4.Controls.Add(this.btnNovo); this.panel4.Dock = System.Windows.Forms.DockStyle.Bottom; this.panel4.Location = new System.Drawing.Point(3, 342); this.panel4.Name = "panel4"; this.panel4.Size = new System.Drawing.Size(786, 29); this.panel4.TabIndex = 2; // // btnExcluir // this.btnExcluir.Location = new System.Drawing.Point(167, 3); this.btnExcluir.Name = "btnExcluir"; this.btnExcluir.Size = new System.Drawing.Size(75, 23); this.btnExcluir.TabIndex = 2; this.btnExcluir.Text = "Excluir"; this.btnExcluir.UseVisualStyleBackColor = true; this.btnExcluir.Click += new System.EventHandler(this.btnExcluir_Click); // // btnEditar // this.btnEditar.Location = new System.Drawing.Point(86, 3); this.btnEditar.Name = "btnEditar"; this.btnEditar.Size = new System.Drawing.Size(75, 23); this.btnEditar.TabIndex = 1; this.btnEditar.Text = "Editar..."; this.btnEditar.UseVisualStyleBackColor = true; this.btnEditar.Click += new System.EventHandler(this.btnEditar_Click); // // btnNovo // this.btnNovo.Location = new System.Drawing.Point(5, 3); this.btnNovo.Name = "btnNovo"; this.btnNovo.Size = new System.Drawing.Size(75, 23); this.btnNovo.TabIndex = 0; this.btnNovo.Text = "Novo..."; this.btnNovo.UseVisualStyleBackColor = true; this.btnNovo.Click += new System.EventHandler(this.btnNovo_Click); // // tpgCriarCliente // this.tpgCriarCliente.Controls.Add(this.txtRG); this.tpgCriarCliente.Controls.Add(this.txtCPF); this.tpgCriarCliente.Controls.Add(this.label5); this.tpgCriarCliente.Controls.Add(this.txtDtNasc); this.tpgCriarCliente.Controls.Add(this.label4); this.tpgCriarCliente.Controls.Add(this.label3); this.tpgCriarCliente.Controls.Add(this.txtUltimoNome); this.tpgCriarCliente.Controls.Add(this.label2); this.tpgCriarCliente.Controls.Add(this.txtPrimeiroNome); this.tpgCriarCliente.Controls.Add(this.label1); this.tpgCriarCliente.Controls.Add(this.panel2); this.tpgCriarCliente.Location = new System.Drawing.Point(4, 22); this.tpgCriarCliente.Name = "tpgCriarCliente"; this.tpgCriarCliente.Padding = new System.Windows.Forms.Padding(3); this.tpgCriarCliente.Size = new System.Drawing.Size(792, 374); this.tpgCriarCliente.TabIndex = 1; this.tpgCriarCliente.Text = "Novo"; this.tpgCriarCliente.UseVisualStyleBackColor = true; // // txtRG // this.txtRG.Location = new System.Drawing.Point(121, 58); this.txtRG.Mask = "00.000.000-0"; this.txtRG.Name = "txtRG"; this.txtRG.Size = new System.Drawing.Size(174, 20); this.txtRG.TabIndex = 3; // // txtCPF // this.txtCPF.Location = new System.Drawing.Point(121, 84); this.txtCPF.Mask = "000.000.000-00"; this.txtCPF.Name = "txtCPF"; this.txtCPF.Size = new System.Drawing.Size(174, 20); this.txtCPF.TabIndex = 4; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(8, 113); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(107, 13); this.label5.TabIndex = 12; this.label5.Text = "Data de Nascimento:"; // // txtDtNasc // this.txtDtNasc.Location = new System.Drawing.Point(121, 110); this.txtDtNasc.Mask = "00/00/0000"; this.txtDtNasc.Name = "txtDtNasc"; this.txtDtNasc.Size = new System.Drawing.Size(174, 20); this.txtDtNasc.TabIndex = 5; this.txtDtNasc.ValidatingType = typeof(System.DateTime); // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(8, 87); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(30, 13); this.label4.TabIndex = 10; this.label4.Text = "CPF:"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(8, 61); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(26, 13); this.label3.TabIndex = 7; this.label3.Text = "RG:"; // // txtUltimoNome // this.txtUltimoNome.Location = new System.Drawing.Point(121, 32); this.txtUltimoNome.Name = "txtUltimoNome"; this.txtUltimoNome.Size = new System.Drawing.Size(174, 20); this.txtUltimoNome.TabIndex = 2; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(8, 35); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(70, 13); this.label2.TabIndex = 5; this.label2.Text = "Último Nome:"; // // txtPrimeiroNome // this.txtPrimeiroNome.Location = new System.Drawing.Point(121, 6); this.txtPrimeiroNome.Name = "txtPrimeiroNome"; this.txtPrimeiroNome.Size = new System.Drawing.Size(174, 20); this.txtPrimeiroNome.TabIndex = 1; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(8, 9); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(78, 13); this.label1.TabIndex = 3; this.label1.Text = "Primeiro Nome:"; // // panel2 // this.panel2.Controls.Add(this.btnCancelar); this.panel2.Controls.Add(this.btnSalvar); this.panel2.Dock = System.Windows.Forms.DockStyle.Bottom; this.panel2.Location = new System.Drawing.Point(3, 255); this.panel2.Name = "panel2"; this.panel2.Size = new System.Drawing.Size(786, 116); this.panel2.TabIndex = 2; // // btnCancelar // this.btnCancelar.Location = new System.Drawing.Point(86, 3); this.btnCancelar.Name = "btnCancelar"; this.btnCancelar.Size = new System.Drawing.Size(75, 23); this.btnCancelar.TabIndex = 70; this.btnCancelar.Text = "Cancelar"; this.btnCancelar.UseVisualStyleBackColor = true; this.btnCancelar.Click += new System.EventHandler(this.btnCancelar_Click); // // btnSalvar // this.btnSalvar.Location = new System.Drawing.Point(5, 3); this.btnSalvar.Name = "btnSalvar"; this.btnSalvar.Size = new System.Drawing.Size(75, 23); this.btnSalvar.TabIndex = 60; this.btnSalvar.Text = "Salvar"; this.btnSalvar.UseVisualStyleBackColor = true; this.btnSalvar.Click += new System.EventHandler(this.btnSalvar_Click); // // panel1 // this.panel1.Controls.Add(this.btnSair); this.panel1.Dock = System.Windows.Forms.DockStyle.Bottom; this.panel1.Location = new System.Drawing.Point(0, 406); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(800, 44); this.panel1.TabIndex = 1; // // btnSair // this.btnSair.Location = new System.Drawing.Point(713, 9); this.btnSair.Name = "btnSair"; this.btnSair.Size = new System.Drawing.Size(75, 23); this.btnSair.TabIndex = 50; this.btnSair.Text = "Sair"; this.btnSair.UseVisualStyleBackColor = true; this.btnSair.Click += new System.EventHandler(this.btnSair_Click); // // frmCliente // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(800, 450); this.Controls.Add(this.panel1); this.Controls.Add(this.tcCliente); this.MaximizeBox = false; this.Name = "frmCliente"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Gerenciar Clientes"; this.tcCliente.ResumeLayout(false); this.tpgClientes.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.dgvClientes)).EndInit(); this.panel4.ResumeLayout(false); this.tpgCriarCliente.ResumeLayout(false); this.tpgCriarCliente.PerformLayout(); this.panel2.ResumeLayout(false); this.panel1.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.TabControl tcCliente; private System.Windows.Forms.TabPage tpgClientes; private System.Windows.Forms.TabPage tpgCriarCliente; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.DataGridView dgvClientes; private System.Windows.Forms.Panel panel4; private System.Windows.Forms.Button btnExcluir; private System.Windows.Forms.Button btnEditar; private System.Windows.Forms.Button btnNovo; private System.Windows.Forms.Button btnSair; private System.Windows.Forms.Panel panel2; private System.Windows.Forms.Button btnSalvar; private System.Windows.Forms.Label label5; private System.Windows.Forms.MaskedTextBox txtDtNasc; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox txtUltimoNome; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox txtPrimeiroNome; private System.Windows.Forms.Label label1; private System.Windows.Forms.MaskedTextBox txtRG; private System.Windows.Forms.MaskedTextBox txtCPF; private System.Windows.Forms.Button btnCancelar; } }
46.194767
151
0.583286
[ "Unlicense" ]
mannuscritto/SistemaHotel
frmCliente.Designer.cs
15,894
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // Manual changes will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ #if HWINTRINSICS using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; namespace Blake2Fast.Implementation { #if BLAKE2_PUBLIC public #else internal #endif unsafe partial struct Blake2bHashState { // SIMD algorithm described in https://eprint.iacr.org/2012/275.pdf #if !HWINTRINSICS_EXP [MethodImpl(MethodImplOptions.AggressiveOptimization)] #endif private static void mixSse41(ulong* sh, ulong* m) { ref byte rrm = ref MemoryMarshal.GetReference(rormask); #if HWINTRINSICS_EXP var r24 = Unsafe.As<byte, Vector128<sbyte>>(ref rrm); var r16 = Unsafe.As<byte, Vector128<sbyte>>(ref Unsafe.Add(ref rrm, 16)); #else var r24 = Unsafe.As<byte, Vector128<byte>>(ref rrm); var r16 = Unsafe.As<byte, Vector128<byte>>(ref Unsafe.Add(ref rrm, Vector128<byte>.Count)); #endif var row1l = Sse2.LoadVector128(sh); var row1h = Sse2.LoadVector128(sh + 2); var row2l = Sse2.LoadVector128(sh + 4); var row2h = Sse2.LoadVector128(sh + 6); ref byte riv = ref MemoryMarshal.GetReference(ivle); var row3l = Unsafe.As<byte, Vector128<ulong>>(ref riv); var row3h = Unsafe.As<byte, Vector128<ulong>>(ref Unsafe.Add(ref riv, 16)); var row4l = Unsafe.As<byte, Vector128<ulong>>(ref Unsafe.Add(ref riv, 32)); var row4h = Unsafe.As<byte, Vector128<ulong>>(ref Unsafe.Add(ref riv, 48)); row4l = Sse2.Xor(row4l, Sse2.LoadVector128(sh + 8)); // t[] row4h = Sse2.Xor(row4h, Sse2.LoadVector128(sh + 10)); // f[] //ROUND 1 var m0 = Sse2.LoadVector128(m); var m1 = Sse2.LoadVector128(m + 2); var m2 = Sse2.LoadVector128(m + 4); var m3 = Sse2.LoadVector128(m + 6); var b0 = Sse2.UnpackLow(m0, m1); var b1 = Sse2.UnpackLow(m2, m3); //G1 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4l), 0b_10_11_00_01)); row4h = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4h), 0b_10_11_00_01)); #else row4l = Sse2.Shuffle(row4l.AsUInt32(), 0b_10_11_00_01).AsUInt64(); row4h = Sse2.Shuffle(row4h.AsUInt32(), 0b_10_11_00_01).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); #if HWINTRINSICS_EXP row2l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2l), r24)); row2h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2h), r24)); #else row2l = Ssse3.Shuffle(row2l.AsByte(), r24).AsUInt64(); row2h = Ssse3.Shuffle(row2h.AsByte(), r24).AsUInt64(); #endif b0 = Sse2.UnpackHigh(m0, m1); b1 = Sse2.UnpackHigh(m2, m3); //G2 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4l), r16)); row4h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4h), r16)); #else row4l = Ssse3.Shuffle(row4l.AsByte(), r16).AsUInt64(); row4h = Ssse3.Shuffle(row4h.AsByte(), r16).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); row2l = Sse2.Xor(Sse2.ShiftRightLogical(row2l, 63), Sse2.Add(row2l, row2l)); row2h = Sse2.Xor(Sse2.ShiftRightLogical(row2h, 63), Sse2.Add(row2h, row2h)); //DIAGONALIZE #if HWINTRINSICS_EXP var t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2h), Sse.StaticCast<ulong, sbyte>(row2l), 8); var t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2l), Sse.StaticCast<ulong, sbyte>(row2h), 8); row2l = Sse.StaticCast<sbyte, ulong>(t0); row2h = Sse.StaticCast<sbyte, ulong>(t1); #else var t0 = Ssse3.AlignRight(row2h, row2l, 8); var t1 = Ssse3.AlignRight(row2l, row2h, 8); row2l = t0; row2h = t1; #endif b0 = row3l; row3l = row3h; row3h = b0; #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4h), Sse.StaticCast<ulong, sbyte>(row4l), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4l), Sse.StaticCast<ulong, sbyte>(row4h), 8); row4l = Sse.StaticCast<sbyte, ulong>(t1); row4h = Sse.StaticCast<sbyte, ulong>(t0); #else t0 = Ssse3.AlignRight(row4h, row4l, 8); t1 = Ssse3.AlignRight(row4l, row4h, 8); row4l = t1; row4h = t0; #endif var m4 = Sse2.LoadVector128(m + 8); var m5 = Sse2.LoadVector128(m + 10); var m6 = Sse2.LoadVector128(m + 12); var m7 = Sse2.LoadVector128(m + 14); b0 = Sse2.UnpackLow(m4, m5); b1 = Sse2.UnpackLow(m6, m7); //G1 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4l), 0b_10_11_00_01)); row4h = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4h), 0b_10_11_00_01)); #else row4l = Sse2.Shuffle(row4l.AsUInt32(), 0b_10_11_00_01).AsUInt64(); row4h = Sse2.Shuffle(row4h.AsUInt32(), 0b_10_11_00_01).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); #if HWINTRINSICS_EXP row2l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2l), r24)); row2h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2h), r24)); #else row2l = Ssse3.Shuffle(row2l.AsByte(), r24).AsUInt64(); row2h = Ssse3.Shuffle(row2h.AsByte(), r24).AsUInt64(); #endif b0 = Sse2.UnpackHigh(m4, m5); b1 = Sse2.UnpackHigh(m6, m7); //G2 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4l), r16)); row4h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4h), r16)); #else row4l = Ssse3.Shuffle(row4l.AsByte(), r16).AsUInt64(); row4h = Ssse3.Shuffle(row4h.AsByte(), r16).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); row2l = Sse2.Xor(Sse2.ShiftRightLogical(row2l, 63), Sse2.Add(row2l, row2l)); row2h = Sse2.Xor(Sse2.ShiftRightLogical(row2h, 63), Sse2.Add(row2h, row2h)); //UNDIAGONALIZE #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2l), Sse.StaticCast<ulong, sbyte>(row2h), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2h), Sse.StaticCast<ulong, sbyte>(row2l), 8); row2l = Sse.StaticCast<sbyte, ulong>(t0); row2h = Sse.StaticCast<sbyte, ulong>(t1); #else t0 = Ssse3.AlignRight(row2l, row2h, 8); t1 = Ssse3.AlignRight(row2h, row2l, 8); row2l = t0; row2h = t1; #endif b0 = row3l; row3l = row3h; row3h = b0; #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4l), Sse.StaticCast<ulong, sbyte>(row4h), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4h), Sse.StaticCast<ulong, sbyte>(row4l), 8); row4l = Sse.StaticCast<sbyte, ulong>(t1); row4h = Sse.StaticCast<sbyte, ulong>(t0); #else t0 = Ssse3.AlignRight(row4l, row4h, 8); t1 = Ssse3.AlignRight(row4h, row4l, 8); row4l = t1; row4h = t0; #endif //ROUND 2 b0 = Sse2.UnpackLow(m7, m2); b1 = Sse2.UnpackHigh(m4, m6); //G1 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4l), 0b_10_11_00_01)); row4h = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4h), 0b_10_11_00_01)); #else row4l = Sse2.Shuffle(row4l.AsUInt32(), 0b_10_11_00_01).AsUInt64(); row4h = Sse2.Shuffle(row4h.AsUInt32(), 0b_10_11_00_01).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); #if HWINTRINSICS_EXP row2l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2l), r24)); row2h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2h), r24)); #else row2l = Ssse3.Shuffle(row2l.AsByte(), r24).AsUInt64(); row2h = Ssse3.Shuffle(row2h.AsByte(), r24).AsUInt64(); #endif b0 = Sse2.UnpackLow(m5, m4); #if HWINTRINSICS_EXP b1 = Sse.StaticCast<sbyte, ulong>(Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(m3), Sse.StaticCast<ulong, sbyte>(m7), 8)); #else b1 = Ssse3.AlignRight(m3, m7, 8); #endif //G2 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4l), r16)); row4h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4h), r16)); #else row4l = Ssse3.Shuffle(row4l.AsByte(), r16).AsUInt64(); row4h = Ssse3.Shuffle(row4h.AsByte(), r16).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); row2l = Sse2.Xor(Sse2.ShiftRightLogical(row2l, 63), Sse2.Add(row2l, row2l)); row2h = Sse2.Xor(Sse2.ShiftRightLogical(row2h, 63), Sse2.Add(row2h, row2h)); //DIAGONALIZE #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2h), Sse.StaticCast<ulong, sbyte>(row2l), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2l), Sse.StaticCast<ulong, sbyte>(row2h), 8); row2l = Sse.StaticCast<sbyte, ulong>(t0); row2h = Sse.StaticCast<sbyte, ulong>(t1); #else t0 = Ssse3.AlignRight(row2h, row2l, 8); t1 = Ssse3.AlignRight(row2l, row2h, 8); row2l = t0; row2h = t1; #endif b0 = row3l; row3l = row3h; row3h = b0; #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4h), Sse.StaticCast<ulong, sbyte>(row4l), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4l), Sse.StaticCast<ulong, sbyte>(row4h), 8); row4l = Sse.StaticCast<sbyte, ulong>(t1); row4h = Sse.StaticCast<sbyte, ulong>(t0); #else t0 = Ssse3.AlignRight(row4h, row4l, 8); t1 = Ssse3.AlignRight(row4l, row4h, 8); row4l = t1; row4h = t0; #endif #if HWINTRINSICS_EXP b0 = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(m0), 0b_01_00_11_10)); #else b0 = Sse2.Shuffle(m0.AsUInt32(), 0b_01_00_11_10).AsUInt64(); #endif b1 = Sse2.UnpackHigh(m5, m2); //G1 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4l), 0b_10_11_00_01)); row4h = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4h), 0b_10_11_00_01)); #else row4l = Sse2.Shuffle(row4l.AsUInt32(), 0b_10_11_00_01).AsUInt64(); row4h = Sse2.Shuffle(row4h.AsUInt32(), 0b_10_11_00_01).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); #if HWINTRINSICS_EXP row2l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2l), r24)); row2h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2h), r24)); #else row2l = Ssse3.Shuffle(row2l.AsByte(), r24).AsUInt64(); row2h = Ssse3.Shuffle(row2h.AsByte(), r24).AsUInt64(); #endif b0 = Sse2.UnpackLow(m6, m1); b1 = Sse2.UnpackHigh(m3, m1); //G2 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4l), r16)); row4h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4h), r16)); #else row4l = Ssse3.Shuffle(row4l.AsByte(), r16).AsUInt64(); row4h = Ssse3.Shuffle(row4h.AsByte(), r16).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); row2l = Sse2.Xor(Sse2.ShiftRightLogical(row2l, 63), Sse2.Add(row2l, row2l)); row2h = Sse2.Xor(Sse2.ShiftRightLogical(row2h, 63), Sse2.Add(row2h, row2h)); //UNDIAGONALIZE #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2l), Sse.StaticCast<ulong, sbyte>(row2h), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2h), Sse.StaticCast<ulong, sbyte>(row2l), 8); row2l = Sse.StaticCast<sbyte, ulong>(t0); row2h = Sse.StaticCast<sbyte, ulong>(t1); #else t0 = Ssse3.AlignRight(row2l, row2h, 8); t1 = Ssse3.AlignRight(row2h, row2l, 8); row2l = t0; row2h = t1; #endif b0 = row3l; row3l = row3h; row3h = b0; #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4l), Sse.StaticCast<ulong, sbyte>(row4h), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4h), Sse.StaticCast<ulong, sbyte>(row4l), 8); row4l = Sse.StaticCast<sbyte, ulong>(t1); row4h = Sse.StaticCast<sbyte, ulong>(t0); #else t0 = Ssse3.AlignRight(row4l, row4h, 8); t1 = Ssse3.AlignRight(row4h, row4l, 8); row4l = t1; row4h = t0; #endif //ROUND 3 #if HWINTRINSICS_EXP b0 = Sse.StaticCast<sbyte, ulong>(Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(m6), Sse.StaticCast<ulong, sbyte>(m5), 8)); #else b0 = Ssse3.AlignRight(m6, m5, 8); #endif b1 = Sse2.UnpackHigh(m2, m7); //G1 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4l), 0b_10_11_00_01)); row4h = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4h), 0b_10_11_00_01)); #else row4l = Sse2.Shuffle(row4l.AsUInt32(), 0b_10_11_00_01).AsUInt64(); row4h = Sse2.Shuffle(row4h.AsUInt32(), 0b_10_11_00_01).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); #if HWINTRINSICS_EXP row2l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2l), r24)); row2h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2h), r24)); #else row2l = Ssse3.Shuffle(row2l.AsByte(), r24).AsUInt64(); row2h = Ssse3.Shuffle(row2h.AsByte(), r24).AsUInt64(); #endif b0 = Sse2.UnpackLow(m4, m0); #if HWINTRINSICS_EXP b1 = Sse.StaticCast<ushort, ulong>(Sse41.Blend(Sse.StaticCast<ulong, ushort>(m1), Sse.StaticCast<ulong, ushort>(m6), 0b_1111_0000)); #else b1 = Sse41.Blend(m1.AsUInt16(), m6.AsUInt16(), 0b_1111_0000).AsUInt64(); #endif //G2 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4l), r16)); row4h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4h), r16)); #else row4l = Ssse3.Shuffle(row4l.AsByte(), r16).AsUInt64(); row4h = Ssse3.Shuffle(row4h.AsByte(), r16).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); row2l = Sse2.Xor(Sse2.ShiftRightLogical(row2l, 63), Sse2.Add(row2l, row2l)); row2h = Sse2.Xor(Sse2.ShiftRightLogical(row2h, 63), Sse2.Add(row2h, row2h)); //DIAGONALIZE #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2h), Sse.StaticCast<ulong, sbyte>(row2l), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2l), Sse.StaticCast<ulong, sbyte>(row2h), 8); row2l = Sse.StaticCast<sbyte, ulong>(t0); row2h = Sse.StaticCast<sbyte, ulong>(t1); #else t0 = Ssse3.AlignRight(row2h, row2l, 8); t1 = Ssse3.AlignRight(row2l, row2h, 8); row2l = t0; row2h = t1; #endif b0 = row3l; row3l = row3h; row3h = b0; #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4h), Sse.StaticCast<ulong, sbyte>(row4l), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4l), Sse.StaticCast<ulong, sbyte>(row4h), 8); row4l = Sse.StaticCast<sbyte, ulong>(t1); row4h = Sse.StaticCast<sbyte, ulong>(t0); #else t0 = Ssse3.AlignRight(row4h, row4l, 8); t1 = Ssse3.AlignRight(row4l, row4h, 8); row4l = t1; row4h = t0; #endif #if HWINTRINSICS_EXP b0 = Sse.StaticCast<ushort, ulong>(Sse41.Blend(Sse.StaticCast<ulong, ushort>(m5), Sse.StaticCast<ulong, ushort>(m1), 0b_1111_0000)); #else b0 = Sse41.Blend(m5.AsUInt16(), m1.AsUInt16(), 0b_1111_0000).AsUInt64(); #endif b1 = Sse2.UnpackHigh(m3, m4); //G1 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4l), 0b_10_11_00_01)); row4h = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4h), 0b_10_11_00_01)); #else row4l = Sse2.Shuffle(row4l.AsUInt32(), 0b_10_11_00_01).AsUInt64(); row4h = Sse2.Shuffle(row4h.AsUInt32(), 0b_10_11_00_01).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); #if HWINTRINSICS_EXP row2l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2l), r24)); row2h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2h), r24)); #else row2l = Ssse3.Shuffle(row2l.AsByte(), r24).AsUInt64(); row2h = Ssse3.Shuffle(row2h.AsByte(), r24).AsUInt64(); #endif b0 = Sse2.UnpackLow(m7, m3); #if HWINTRINSICS_EXP b1 = Sse.StaticCast<sbyte, ulong>(Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(m2), Sse.StaticCast<ulong, sbyte>(m0), 8)); #else b1 = Ssse3.AlignRight(m2, m0, 8); #endif //G2 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4l), r16)); row4h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4h), r16)); #else row4l = Ssse3.Shuffle(row4l.AsByte(), r16).AsUInt64(); row4h = Ssse3.Shuffle(row4h.AsByte(), r16).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); row2l = Sse2.Xor(Sse2.ShiftRightLogical(row2l, 63), Sse2.Add(row2l, row2l)); row2h = Sse2.Xor(Sse2.ShiftRightLogical(row2h, 63), Sse2.Add(row2h, row2h)); //UNDIAGONALIZE #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2l), Sse.StaticCast<ulong, sbyte>(row2h), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2h), Sse.StaticCast<ulong, sbyte>(row2l), 8); row2l = Sse.StaticCast<sbyte, ulong>(t0); row2h = Sse.StaticCast<sbyte, ulong>(t1); #else t0 = Ssse3.AlignRight(row2l, row2h, 8); t1 = Ssse3.AlignRight(row2h, row2l, 8); row2l = t0; row2h = t1; #endif b0 = row3l; row3l = row3h; row3h = b0; #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4l), Sse.StaticCast<ulong, sbyte>(row4h), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4h), Sse.StaticCast<ulong, sbyte>(row4l), 8); row4l = Sse.StaticCast<sbyte, ulong>(t1); row4h = Sse.StaticCast<sbyte, ulong>(t0); #else t0 = Ssse3.AlignRight(row4l, row4h, 8); t1 = Ssse3.AlignRight(row4h, row4l, 8); row4l = t1; row4h = t0; #endif //ROUND 4 b0 = Sse2.UnpackHigh(m3, m1); b1 = Sse2.UnpackHigh(m6, m5); //G1 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4l), 0b_10_11_00_01)); row4h = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4h), 0b_10_11_00_01)); #else row4l = Sse2.Shuffle(row4l.AsUInt32(), 0b_10_11_00_01).AsUInt64(); row4h = Sse2.Shuffle(row4h.AsUInt32(), 0b_10_11_00_01).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); #if HWINTRINSICS_EXP row2l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2l), r24)); row2h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2h), r24)); #else row2l = Ssse3.Shuffle(row2l.AsByte(), r24).AsUInt64(); row2h = Ssse3.Shuffle(row2h.AsByte(), r24).AsUInt64(); #endif b0 = Sse2.UnpackHigh(m4, m0); b1 = Sse2.UnpackLow(m6, m7); //G2 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4l), r16)); row4h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4h), r16)); #else row4l = Ssse3.Shuffle(row4l.AsByte(), r16).AsUInt64(); row4h = Ssse3.Shuffle(row4h.AsByte(), r16).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); row2l = Sse2.Xor(Sse2.ShiftRightLogical(row2l, 63), Sse2.Add(row2l, row2l)); row2h = Sse2.Xor(Sse2.ShiftRightLogical(row2h, 63), Sse2.Add(row2h, row2h)); //DIAGONALIZE #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2h), Sse.StaticCast<ulong, sbyte>(row2l), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2l), Sse.StaticCast<ulong, sbyte>(row2h), 8); row2l = Sse.StaticCast<sbyte, ulong>(t0); row2h = Sse.StaticCast<sbyte, ulong>(t1); #else t0 = Ssse3.AlignRight(row2h, row2l, 8); t1 = Ssse3.AlignRight(row2l, row2h, 8); row2l = t0; row2h = t1; #endif b0 = row3l; row3l = row3h; row3h = b0; #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4h), Sse.StaticCast<ulong, sbyte>(row4l), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4l), Sse.StaticCast<ulong, sbyte>(row4h), 8); row4l = Sse.StaticCast<sbyte, ulong>(t1); row4h = Sse.StaticCast<sbyte, ulong>(t0); #else t0 = Ssse3.AlignRight(row4h, row4l, 8); t1 = Ssse3.AlignRight(row4l, row4h, 8); row4l = t1; row4h = t0; #endif #if HWINTRINSICS_EXP b0 = Sse.StaticCast<ushort, ulong>(Sse41.Blend(Sse.StaticCast<ulong, ushort>(m1), Sse.StaticCast<ulong, ushort>(m2), 0b_1111_0000)); b1 = Sse.StaticCast<ushort, ulong>(Sse41.Blend(Sse.StaticCast<ulong, ushort>(m2), Sse.StaticCast<ulong, ushort>(m7), 0b_1111_0000)); #else b0 = Sse41.Blend(m1.AsUInt16(), m2.AsUInt16(), 0b_1111_0000).AsUInt64(); b1 = Sse41.Blend(m2.AsUInt16(), m7.AsUInt16(), 0b_1111_0000).AsUInt64(); #endif //G1 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4l), 0b_10_11_00_01)); row4h = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4h), 0b_10_11_00_01)); #else row4l = Sse2.Shuffle(row4l.AsUInt32(), 0b_10_11_00_01).AsUInt64(); row4h = Sse2.Shuffle(row4h.AsUInt32(), 0b_10_11_00_01).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); #if HWINTRINSICS_EXP row2l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2l), r24)); row2h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2h), r24)); #else row2l = Ssse3.Shuffle(row2l.AsByte(), r24).AsUInt64(); row2h = Ssse3.Shuffle(row2h.AsByte(), r24).AsUInt64(); #endif b0 = Sse2.UnpackLow(m3, m5); b1 = Sse2.UnpackLow(m0, m4); //G2 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4l), r16)); row4h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4h), r16)); #else row4l = Ssse3.Shuffle(row4l.AsByte(), r16).AsUInt64(); row4h = Ssse3.Shuffle(row4h.AsByte(), r16).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); row2l = Sse2.Xor(Sse2.ShiftRightLogical(row2l, 63), Sse2.Add(row2l, row2l)); row2h = Sse2.Xor(Sse2.ShiftRightLogical(row2h, 63), Sse2.Add(row2h, row2h)); //UNDIAGONALIZE #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2l), Sse.StaticCast<ulong, sbyte>(row2h), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2h), Sse.StaticCast<ulong, sbyte>(row2l), 8); row2l = Sse.StaticCast<sbyte, ulong>(t0); row2h = Sse.StaticCast<sbyte, ulong>(t1); #else t0 = Ssse3.AlignRight(row2l, row2h, 8); t1 = Ssse3.AlignRight(row2h, row2l, 8); row2l = t0; row2h = t1; #endif b0 = row3l; row3l = row3h; row3h = b0; #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4l), Sse.StaticCast<ulong, sbyte>(row4h), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4h), Sse.StaticCast<ulong, sbyte>(row4l), 8); row4l = Sse.StaticCast<sbyte, ulong>(t1); row4h = Sse.StaticCast<sbyte, ulong>(t0); #else t0 = Ssse3.AlignRight(row4l, row4h, 8); t1 = Ssse3.AlignRight(row4h, row4l, 8); row4l = t1; row4h = t0; #endif //ROUND 5 b0 = Sse2.UnpackHigh(m4, m2); b1 = Sse2.UnpackLow(m1, m5); //G1 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4l), 0b_10_11_00_01)); row4h = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4h), 0b_10_11_00_01)); #else row4l = Sse2.Shuffle(row4l.AsUInt32(), 0b_10_11_00_01).AsUInt64(); row4h = Sse2.Shuffle(row4h.AsUInt32(), 0b_10_11_00_01).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); #if HWINTRINSICS_EXP row2l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2l), r24)); row2h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2h), r24)); #else row2l = Ssse3.Shuffle(row2l.AsByte(), r24).AsUInt64(); row2h = Ssse3.Shuffle(row2h.AsByte(), r24).AsUInt64(); #endif #if HWINTRINSICS_EXP b0 = Sse.StaticCast<ushort, ulong>(Sse41.Blend(Sse.StaticCast<ulong, ushort>(m0), Sse.StaticCast<ulong, ushort>(m3), 0b_1111_0000)); b1 = Sse.StaticCast<ushort, ulong>(Sse41.Blend(Sse.StaticCast<ulong, ushort>(m2), Sse.StaticCast<ulong, ushort>(m7), 0b_1111_0000)); #else b0 = Sse41.Blend(m0.AsUInt16(), m3.AsUInt16(), 0b_1111_0000).AsUInt64(); b1 = Sse41.Blend(m2.AsUInt16(), m7.AsUInt16(), 0b_1111_0000).AsUInt64(); #endif //G2 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4l), r16)); row4h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4h), r16)); #else row4l = Ssse3.Shuffle(row4l.AsByte(), r16).AsUInt64(); row4h = Ssse3.Shuffle(row4h.AsByte(), r16).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); row2l = Sse2.Xor(Sse2.ShiftRightLogical(row2l, 63), Sse2.Add(row2l, row2l)); row2h = Sse2.Xor(Sse2.ShiftRightLogical(row2h, 63), Sse2.Add(row2h, row2h)); //DIAGONALIZE #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2h), Sse.StaticCast<ulong, sbyte>(row2l), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2l), Sse.StaticCast<ulong, sbyte>(row2h), 8); row2l = Sse.StaticCast<sbyte, ulong>(t0); row2h = Sse.StaticCast<sbyte, ulong>(t1); #else t0 = Ssse3.AlignRight(row2h, row2l, 8); t1 = Ssse3.AlignRight(row2l, row2h, 8); row2l = t0; row2h = t1; #endif b0 = row3l; row3l = row3h; row3h = b0; #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4h), Sse.StaticCast<ulong, sbyte>(row4l), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4l), Sse.StaticCast<ulong, sbyte>(row4h), 8); row4l = Sse.StaticCast<sbyte, ulong>(t1); row4h = Sse.StaticCast<sbyte, ulong>(t0); #else t0 = Ssse3.AlignRight(row4h, row4l, 8); t1 = Ssse3.AlignRight(row4l, row4h, 8); row4l = t1; row4h = t0; #endif #if HWINTRINSICS_EXP b0 = Sse.StaticCast<ushort, ulong>(Sse41.Blend(Sse.StaticCast<ulong, ushort>(m7), Sse.StaticCast<ulong, ushort>(m5), 0b_1111_0000)); b1 = Sse.StaticCast<ushort, ulong>(Sse41.Blend(Sse.StaticCast<ulong, ushort>(m3), Sse.StaticCast<ulong, ushort>(m1), 0b_1111_0000)); #else b0 = Sse41.Blend(m7.AsUInt16(), m5.AsUInt16(), 0b_1111_0000).AsUInt64(); b1 = Sse41.Blend(m3.AsUInt16(), m1.AsUInt16(), 0b_1111_0000).AsUInt64(); #endif //G1 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4l), 0b_10_11_00_01)); row4h = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4h), 0b_10_11_00_01)); #else row4l = Sse2.Shuffle(row4l.AsUInt32(), 0b_10_11_00_01).AsUInt64(); row4h = Sse2.Shuffle(row4h.AsUInt32(), 0b_10_11_00_01).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); #if HWINTRINSICS_EXP row2l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2l), r24)); row2h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2h), r24)); #else row2l = Ssse3.Shuffle(row2l.AsByte(), r24).AsUInt64(); row2h = Ssse3.Shuffle(row2h.AsByte(), r24).AsUInt64(); #endif #if HWINTRINSICS_EXP b0 = Sse.StaticCast<sbyte, ulong>(Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(m6), Sse.StaticCast<ulong, sbyte>(m0), 8)); b1 = Sse.StaticCast<ushort, ulong>(Sse41.Blend(Sse.StaticCast<ulong, ushort>(m4), Sse.StaticCast<ulong, ushort>(m6), 0b_1111_0000)); #else b0 = Ssse3.AlignRight(m6, m0, 8); b1 = Sse41.Blend(m4.AsUInt16(), m6.AsUInt16(), 0b_1111_0000).AsUInt64(); #endif //G2 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4l), r16)); row4h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4h), r16)); #else row4l = Ssse3.Shuffle(row4l.AsByte(), r16).AsUInt64(); row4h = Ssse3.Shuffle(row4h.AsByte(), r16).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); row2l = Sse2.Xor(Sse2.ShiftRightLogical(row2l, 63), Sse2.Add(row2l, row2l)); row2h = Sse2.Xor(Sse2.ShiftRightLogical(row2h, 63), Sse2.Add(row2h, row2h)); //UNDIAGONALIZE #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2l), Sse.StaticCast<ulong, sbyte>(row2h), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2h), Sse.StaticCast<ulong, sbyte>(row2l), 8); row2l = Sse.StaticCast<sbyte, ulong>(t0); row2h = Sse.StaticCast<sbyte, ulong>(t1); #else t0 = Ssse3.AlignRight(row2l, row2h, 8); t1 = Ssse3.AlignRight(row2h, row2l, 8); row2l = t0; row2h = t1; #endif b0 = row3l; row3l = row3h; row3h = b0; #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4l), Sse.StaticCast<ulong, sbyte>(row4h), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4h), Sse.StaticCast<ulong, sbyte>(row4l), 8); row4l = Sse.StaticCast<sbyte, ulong>(t1); row4h = Sse.StaticCast<sbyte, ulong>(t0); #else t0 = Ssse3.AlignRight(row4l, row4h, 8); t1 = Ssse3.AlignRight(row4h, row4l, 8); row4l = t1; row4h = t0; #endif //ROUND 6 b0 = Sse2.UnpackLow(m1, m3); b1 = Sse2.UnpackLow(m0, m4); //G1 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4l), 0b_10_11_00_01)); row4h = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4h), 0b_10_11_00_01)); #else row4l = Sse2.Shuffle(row4l.AsUInt32(), 0b_10_11_00_01).AsUInt64(); row4h = Sse2.Shuffle(row4h.AsUInt32(), 0b_10_11_00_01).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); #if HWINTRINSICS_EXP row2l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2l), r24)); row2h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2h), r24)); #else row2l = Ssse3.Shuffle(row2l.AsByte(), r24).AsUInt64(); row2h = Ssse3.Shuffle(row2h.AsByte(), r24).AsUInt64(); #endif b0 = Sse2.UnpackLow(m6, m5); b1 = Sse2.UnpackHigh(m5, m1); //G2 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4l), r16)); row4h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4h), r16)); #else row4l = Ssse3.Shuffle(row4l.AsByte(), r16).AsUInt64(); row4h = Ssse3.Shuffle(row4h.AsByte(), r16).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); row2l = Sse2.Xor(Sse2.ShiftRightLogical(row2l, 63), Sse2.Add(row2l, row2l)); row2h = Sse2.Xor(Sse2.ShiftRightLogical(row2h, 63), Sse2.Add(row2h, row2h)); //DIAGONALIZE #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2h), Sse.StaticCast<ulong, sbyte>(row2l), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2l), Sse.StaticCast<ulong, sbyte>(row2h), 8); row2l = Sse.StaticCast<sbyte, ulong>(t0); row2h = Sse.StaticCast<sbyte, ulong>(t1); #else t0 = Ssse3.AlignRight(row2h, row2l, 8); t1 = Ssse3.AlignRight(row2l, row2h, 8); row2l = t0; row2h = t1; #endif b0 = row3l; row3l = row3h; row3h = b0; #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4h), Sse.StaticCast<ulong, sbyte>(row4l), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4l), Sse.StaticCast<ulong, sbyte>(row4h), 8); row4l = Sse.StaticCast<sbyte, ulong>(t1); row4h = Sse.StaticCast<sbyte, ulong>(t0); #else t0 = Ssse3.AlignRight(row4h, row4l, 8); t1 = Ssse3.AlignRight(row4l, row4h, 8); row4l = t1; row4h = t0; #endif #if HWINTRINSICS_EXP b0 = Sse.StaticCast<ushort, ulong>(Sse41.Blend(Sse.StaticCast<ulong, ushort>(m2), Sse.StaticCast<ulong, ushort>(m3), 0b_1111_0000)); #else b0 = Sse41.Blend(m2.AsUInt16(), m3.AsUInt16(), 0b_1111_0000).AsUInt64(); #endif b1 = Sse2.UnpackHigh(m7, m0); //G1 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4l), 0b_10_11_00_01)); row4h = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4h), 0b_10_11_00_01)); #else row4l = Sse2.Shuffle(row4l.AsUInt32(), 0b_10_11_00_01).AsUInt64(); row4h = Sse2.Shuffle(row4h.AsUInt32(), 0b_10_11_00_01).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); #if HWINTRINSICS_EXP row2l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2l), r24)); row2h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2h), r24)); #else row2l = Ssse3.Shuffle(row2l.AsByte(), r24).AsUInt64(); row2h = Ssse3.Shuffle(row2h.AsByte(), r24).AsUInt64(); #endif b0 = Sse2.UnpackHigh(m6, m2); #if HWINTRINSICS_EXP b1 = Sse.StaticCast<ushort, ulong>(Sse41.Blend(Sse.StaticCast<ulong, ushort>(m7), Sse.StaticCast<ulong, ushort>(m4), 0b_1111_0000)); #else b1 = Sse41.Blend(m7.AsUInt16(), m4.AsUInt16(), 0b_1111_0000).AsUInt64(); #endif //G2 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4l), r16)); row4h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4h), r16)); #else row4l = Ssse3.Shuffle(row4l.AsByte(), r16).AsUInt64(); row4h = Ssse3.Shuffle(row4h.AsByte(), r16).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); row2l = Sse2.Xor(Sse2.ShiftRightLogical(row2l, 63), Sse2.Add(row2l, row2l)); row2h = Sse2.Xor(Sse2.ShiftRightLogical(row2h, 63), Sse2.Add(row2h, row2h)); //UNDIAGONALIZE #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2l), Sse.StaticCast<ulong, sbyte>(row2h), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2h), Sse.StaticCast<ulong, sbyte>(row2l), 8); row2l = Sse.StaticCast<sbyte, ulong>(t0); row2h = Sse.StaticCast<sbyte, ulong>(t1); #else t0 = Ssse3.AlignRight(row2l, row2h, 8); t1 = Ssse3.AlignRight(row2h, row2l, 8); row2l = t0; row2h = t1; #endif b0 = row3l; row3l = row3h; row3h = b0; #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4l), Sse.StaticCast<ulong, sbyte>(row4h), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4h), Sse.StaticCast<ulong, sbyte>(row4l), 8); row4l = Sse.StaticCast<sbyte, ulong>(t1); row4h = Sse.StaticCast<sbyte, ulong>(t0); #else t0 = Ssse3.AlignRight(row4l, row4h, 8); t1 = Ssse3.AlignRight(row4h, row4l, 8); row4l = t1; row4h = t0; #endif //ROUND 7 #if HWINTRINSICS_EXP b0 = Sse.StaticCast<ushort, ulong>(Sse41.Blend(Sse.StaticCast<ulong, ushort>(m6), Sse.StaticCast<ulong, ushort>(m0), 0b_1111_0000)); #else b0 = Sse41.Blend(m6.AsUInt16(), m0.AsUInt16(), 0b_1111_0000).AsUInt64(); #endif b1 = Sse2.UnpackLow(m7, m2); //G1 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4l), 0b_10_11_00_01)); row4h = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4h), 0b_10_11_00_01)); #else row4l = Sse2.Shuffle(row4l.AsUInt32(), 0b_10_11_00_01).AsUInt64(); row4h = Sse2.Shuffle(row4h.AsUInt32(), 0b_10_11_00_01).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); #if HWINTRINSICS_EXP row2l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2l), r24)); row2h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2h), r24)); #else row2l = Ssse3.Shuffle(row2l.AsByte(), r24).AsUInt64(); row2h = Ssse3.Shuffle(row2h.AsByte(), r24).AsUInt64(); #endif b0 = Sse2.UnpackHigh(m2, m7); #if HWINTRINSICS_EXP b1 = Sse.StaticCast<sbyte, ulong>(Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(m5), Sse.StaticCast<ulong, sbyte>(m6), 8)); #else b1 = Ssse3.AlignRight(m5, m6, 8); #endif //G2 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4l), r16)); row4h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4h), r16)); #else row4l = Ssse3.Shuffle(row4l.AsByte(), r16).AsUInt64(); row4h = Ssse3.Shuffle(row4h.AsByte(), r16).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); row2l = Sse2.Xor(Sse2.ShiftRightLogical(row2l, 63), Sse2.Add(row2l, row2l)); row2h = Sse2.Xor(Sse2.ShiftRightLogical(row2h, 63), Sse2.Add(row2h, row2h)); //DIAGONALIZE #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2h), Sse.StaticCast<ulong, sbyte>(row2l), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2l), Sse.StaticCast<ulong, sbyte>(row2h), 8); row2l = Sse.StaticCast<sbyte, ulong>(t0); row2h = Sse.StaticCast<sbyte, ulong>(t1); #else t0 = Ssse3.AlignRight(row2h, row2l, 8); t1 = Ssse3.AlignRight(row2l, row2h, 8); row2l = t0; row2h = t1; #endif b0 = row3l; row3l = row3h; row3h = b0; #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4h), Sse.StaticCast<ulong, sbyte>(row4l), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4l), Sse.StaticCast<ulong, sbyte>(row4h), 8); row4l = Sse.StaticCast<sbyte, ulong>(t1); row4h = Sse.StaticCast<sbyte, ulong>(t0); #else t0 = Ssse3.AlignRight(row4h, row4l, 8); t1 = Ssse3.AlignRight(row4l, row4h, 8); row4l = t1; row4h = t0; #endif b0 = Sse2.UnpackLow(m0, m3); #if HWINTRINSICS_EXP b1 = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(m4), 0b_01_00_11_10)); #else b1 = Sse2.Shuffle(m4.AsUInt32(), 0b_01_00_11_10).AsUInt64(); #endif //G1 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4l), 0b_10_11_00_01)); row4h = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4h), 0b_10_11_00_01)); #else row4l = Sse2.Shuffle(row4l.AsUInt32(), 0b_10_11_00_01).AsUInt64(); row4h = Sse2.Shuffle(row4h.AsUInt32(), 0b_10_11_00_01).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); #if HWINTRINSICS_EXP row2l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2l), r24)); row2h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2h), r24)); #else row2l = Ssse3.Shuffle(row2l.AsByte(), r24).AsUInt64(); row2h = Ssse3.Shuffle(row2h.AsByte(), r24).AsUInt64(); #endif b0 = Sse2.UnpackHigh(m3, m1); #if HWINTRINSICS_EXP b1 = Sse.StaticCast<ushort, ulong>(Sse41.Blend(Sse.StaticCast<ulong, ushort>(m1), Sse.StaticCast<ulong, ushort>(m5), 0b_1111_0000)); #else b1 = Sse41.Blend(m1.AsUInt16(), m5.AsUInt16(), 0b_1111_0000).AsUInt64(); #endif //G2 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4l), r16)); row4h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4h), r16)); #else row4l = Ssse3.Shuffle(row4l.AsByte(), r16).AsUInt64(); row4h = Ssse3.Shuffle(row4h.AsByte(), r16).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); row2l = Sse2.Xor(Sse2.ShiftRightLogical(row2l, 63), Sse2.Add(row2l, row2l)); row2h = Sse2.Xor(Sse2.ShiftRightLogical(row2h, 63), Sse2.Add(row2h, row2h)); //UNDIAGONALIZE #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2l), Sse.StaticCast<ulong, sbyte>(row2h), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2h), Sse.StaticCast<ulong, sbyte>(row2l), 8); row2l = Sse.StaticCast<sbyte, ulong>(t0); row2h = Sse.StaticCast<sbyte, ulong>(t1); #else t0 = Ssse3.AlignRight(row2l, row2h, 8); t1 = Ssse3.AlignRight(row2h, row2l, 8); row2l = t0; row2h = t1; #endif b0 = row3l; row3l = row3h; row3h = b0; #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4l), Sse.StaticCast<ulong, sbyte>(row4h), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4h), Sse.StaticCast<ulong, sbyte>(row4l), 8); row4l = Sse.StaticCast<sbyte, ulong>(t1); row4h = Sse.StaticCast<sbyte, ulong>(t0); #else t0 = Ssse3.AlignRight(row4l, row4h, 8); t1 = Ssse3.AlignRight(row4h, row4l, 8); row4l = t1; row4h = t0; #endif //ROUND 8 b0 = Sse2.UnpackHigh(m6, m3); #if HWINTRINSICS_EXP b1 = Sse.StaticCast<ushort, ulong>(Sse41.Blend(Sse.StaticCast<ulong, ushort>(m6), Sse.StaticCast<ulong, ushort>(m1), 0b_1111_0000)); #else b1 = Sse41.Blend(m6.AsUInt16(), m1.AsUInt16(), 0b_1111_0000).AsUInt64(); #endif //G1 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4l), 0b_10_11_00_01)); row4h = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4h), 0b_10_11_00_01)); #else row4l = Sse2.Shuffle(row4l.AsUInt32(), 0b_10_11_00_01).AsUInt64(); row4h = Sse2.Shuffle(row4h.AsUInt32(), 0b_10_11_00_01).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); #if HWINTRINSICS_EXP row2l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2l), r24)); row2h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2h), r24)); #else row2l = Ssse3.Shuffle(row2l.AsByte(), r24).AsUInt64(); row2h = Ssse3.Shuffle(row2h.AsByte(), r24).AsUInt64(); #endif #if HWINTRINSICS_EXP b0 = Sse.StaticCast<sbyte, ulong>(Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(m7), Sse.StaticCast<ulong, sbyte>(m5), 8)); #else b0 = Ssse3.AlignRight(m7, m5, 8); #endif b1 = Sse2.UnpackHigh(m0, m4); //G2 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4l), r16)); row4h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4h), r16)); #else row4l = Ssse3.Shuffle(row4l.AsByte(), r16).AsUInt64(); row4h = Ssse3.Shuffle(row4h.AsByte(), r16).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); row2l = Sse2.Xor(Sse2.ShiftRightLogical(row2l, 63), Sse2.Add(row2l, row2l)); row2h = Sse2.Xor(Sse2.ShiftRightLogical(row2h, 63), Sse2.Add(row2h, row2h)); //DIAGONALIZE #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2h), Sse.StaticCast<ulong, sbyte>(row2l), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2l), Sse.StaticCast<ulong, sbyte>(row2h), 8); row2l = Sse.StaticCast<sbyte, ulong>(t0); row2h = Sse.StaticCast<sbyte, ulong>(t1); #else t0 = Ssse3.AlignRight(row2h, row2l, 8); t1 = Ssse3.AlignRight(row2l, row2h, 8); row2l = t0; row2h = t1; #endif b0 = row3l; row3l = row3h; row3h = b0; #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4h), Sse.StaticCast<ulong, sbyte>(row4l), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4l), Sse.StaticCast<ulong, sbyte>(row4h), 8); row4l = Sse.StaticCast<sbyte, ulong>(t1); row4h = Sse.StaticCast<sbyte, ulong>(t0); #else t0 = Ssse3.AlignRight(row4h, row4l, 8); t1 = Ssse3.AlignRight(row4l, row4h, 8); row4l = t1; row4h = t0; #endif b0 = Sse2.UnpackHigh(m2, m7); b1 = Sse2.UnpackLow(m4, m1); //G1 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4l), 0b_10_11_00_01)); row4h = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4h), 0b_10_11_00_01)); #else row4l = Sse2.Shuffle(row4l.AsUInt32(), 0b_10_11_00_01).AsUInt64(); row4h = Sse2.Shuffle(row4h.AsUInt32(), 0b_10_11_00_01).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); #if HWINTRINSICS_EXP row2l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2l), r24)); row2h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2h), r24)); #else row2l = Ssse3.Shuffle(row2l.AsByte(), r24).AsUInt64(); row2h = Ssse3.Shuffle(row2h.AsByte(), r24).AsUInt64(); #endif b0 = Sse2.UnpackLow(m0, m2); b1 = Sse2.UnpackLow(m3, m5); //G2 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4l), r16)); row4h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4h), r16)); #else row4l = Ssse3.Shuffle(row4l.AsByte(), r16).AsUInt64(); row4h = Ssse3.Shuffle(row4h.AsByte(), r16).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); row2l = Sse2.Xor(Sse2.ShiftRightLogical(row2l, 63), Sse2.Add(row2l, row2l)); row2h = Sse2.Xor(Sse2.ShiftRightLogical(row2h, 63), Sse2.Add(row2h, row2h)); //UNDIAGONALIZE #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2l), Sse.StaticCast<ulong, sbyte>(row2h), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2h), Sse.StaticCast<ulong, sbyte>(row2l), 8); row2l = Sse.StaticCast<sbyte, ulong>(t0); row2h = Sse.StaticCast<sbyte, ulong>(t1); #else t0 = Ssse3.AlignRight(row2l, row2h, 8); t1 = Ssse3.AlignRight(row2h, row2l, 8); row2l = t0; row2h = t1; #endif b0 = row3l; row3l = row3h; row3h = b0; #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4l), Sse.StaticCast<ulong, sbyte>(row4h), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4h), Sse.StaticCast<ulong, sbyte>(row4l), 8); row4l = Sse.StaticCast<sbyte, ulong>(t1); row4h = Sse.StaticCast<sbyte, ulong>(t0); #else t0 = Ssse3.AlignRight(row4l, row4h, 8); t1 = Ssse3.AlignRight(row4h, row4l, 8); row4l = t1; row4h = t0; #endif //ROUND 9 b0 = Sse2.UnpackLow(m3, m7); #if HWINTRINSICS_EXP b1 = Sse.StaticCast<sbyte, ulong>(Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(m0), Sse.StaticCast<ulong, sbyte>(m5), 8)); #else b1 = Ssse3.AlignRight(m0, m5, 8); #endif //G1 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4l), 0b_10_11_00_01)); row4h = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4h), 0b_10_11_00_01)); #else row4l = Sse2.Shuffle(row4l.AsUInt32(), 0b_10_11_00_01).AsUInt64(); row4h = Sse2.Shuffle(row4h.AsUInt32(), 0b_10_11_00_01).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); #if HWINTRINSICS_EXP row2l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2l), r24)); row2h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2h), r24)); #else row2l = Ssse3.Shuffle(row2l.AsByte(), r24).AsUInt64(); row2h = Ssse3.Shuffle(row2h.AsByte(), r24).AsUInt64(); #endif b0 = Sse2.UnpackHigh(m7, m4); #if HWINTRINSICS_EXP b1 = Sse.StaticCast<sbyte, ulong>(Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(m4), Sse.StaticCast<ulong, sbyte>(m1), 8)); #else b1 = Ssse3.AlignRight(m4, m1, 8); #endif //G2 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4l), r16)); row4h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4h), r16)); #else row4l = Ssse3.Shuffle(row4l.AsByte(), r16).AsUInt64(); row4h = Ssse3.Shuffle(row4h.AsByte(), r16).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); row2l = Sse2.Xor(Sse2.ShiftRightLogical(row2l, 63), Sse2.Add(row2l, row2l)); row2h = Sse2.Xor(Sse2.ShiftRightLogical(row2h, 63), Sse2.Add(row2h, row2h)); //DIAGONALIZE #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2h), Sse.StaticCast<ulong, sbyte>(row2l), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2l), Sse.StaticCast<ulong, sbyte>(row2h), 8); row2l = Sse.StaticCast<sbyte, ulong>(t0); row2h = Sse.StaticCast<sbyte, ulong>(t1); #else t0 = Ssse3.AlignRight(row2h, row2l, 8); t1 = Ssse3.AlignRight(row2l, row2h, 8); row2l = t0; row2h = t1; #endif b0 = row3l; row3l = row3h; row3h = b0; #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4h), Sse.StaticCast<ulong, sbyte>(row4l), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4l), Sse.StaticCast<ulong, sbyte>(row4h), 8); row4l = Sse.StaticCast<sbyte, ulong>(t1); row4h = Sse.StaticCast<sbyte, ulong>(t0); #else t0 = Ssse3.AlignRight(row4h, row4l, 8); t1 = Ssse3.AlignRight(row4l, row4h, 8); row4l = t1; row4h = t0; #endif b0 = m6; #if HWINTRINSICS_EXP b1 = Sse.StaticCast<sbyte, ulong>(Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(m5), Sse.StaticCast<ulong, sbyte>(m0), 8)); #else b1 = Ssse3.AlignRight(m5, m0, 8); #endif //G1 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4l), 0b_10_11_00_01)); row4h = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4h), 0b_10_11_00_01)); #else row4l = Sse2.Shuffle(row4l.AsUInt32(), 0b_10_11_00_01).AsUInt64(); row4h = Sse2.Shuffle(row4h.AsUInt32(), 0b_10_11_00_01).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); #if HWINTRINSICS_EXP row2l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2l), r24)); row2h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2h), r24)); #else row2l = Ssse3.Shuffle(row2l.AsByte(), r24).AsUInt64(); row2h = Ssse3.Shuffle(row2h.AsByte(), r24).AsUInt64(); #endif #if HWINTRINSICS_EXP b0 = Sse.StaticCast<ushort, ulong>(Sse41.Blend(Sse.StaticCast<ulong, ushort>(m1), Sse.StaticCast<ulong, ushort>(m3), 0b_1111_0000)); #else b0 = Sse41.Blend(m1.AsUInt16(), m3.AsUInt16(), 0b_1111_0000).AsUInt64(); #endif b1 = m2; //G2 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4l), r16)); row4h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4h), r16)); #else row4l = Ssse3.Shuffle(row4l.AsByte(), r16).AsUInt64(); row4h = Ssse3.Shuffle(row4h.AsByte(), r16).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); row2l = Sse2.Xor(Sse2.ShiftRightLogical(row2l, 63), Sse2.Add(row2l, row2l)); row2h = Sse2.Xor(Sse2.ShiftRightLogical(row2h, 63), Sse2.Add(row2h, row2h)); //UNDIAGONALIZE #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2l), Sse.StaticCast<ulong, sbyte>(row2h), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2h), Sse.StaticCast<ulong, sbyte>(row2l), 8); row2l = Sse.StaticCast<sbyte, ulong>(t0); row2h = Sse.StaticCast<sbyte, ulong>(t1); #else t0 = Ssse3.AlignRight(row2l, row2h, 8); t1 = Ssse3.AlignRight(row2h, row2l, 8); row2l = t0; row2h = t1; #endif b0 = row3l; row3l = row3h; row3h = b0; #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4l), Sse.StaticCast<ulong, sbyte>(row4h), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4h), Sse.StaticCast<ulong, sbyte>(row4l), 8); row4l = Sse.StaticCast<sbyte, ulong>(t1); row4h = Sse.StaticCast<sbyte, ulong>(t0); #else t0 = Ssse3.AlignRight(row4l, row4h, 8); t1 = Ssse3.AlignRight(row4h, row4l, 8); row4l = t1; row4h = t0; #endif //ROUND 10 b0 = Sse2.UnpackLow(m5, m4); b1 = Sse2.UnpackHigh(m3, m0); //G1 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4l), 0b_10_11_00_01)); row4h = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4h), 0b_10_11_00_01)); #else row4l = Sse2.Shuffle(row4l.AsUInt32(), 0b_10_11_00_01).AsUInt64(); row4h = Sse2.Shuffle(row4h.AsUInt32(), 0b_10_11_00_01).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); #if HWINTRINSICS_EXP row2l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2l), r24)); row2h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2h), r24)); #else row2l = Ssse3.Shuffle(row2l.AsByte(), r24).AsUInt64(); row2h = Ssse3.Shuffle(row2h.AsByte(), r24).AsUInt64(); #endif b0 = Sse2.UnpackLow(m1, m2); #if HWINTRINSICS_EXP b1 = Sse.StaticCast<ushort, ulong>(Sse41.Blend(Sse.StaticCast<ulong, ushort>(m3), Sse.StaticCast<ulong, ushort>(m2), 0b_1111_0000)); #else b1 = Sse41.Blend(m3.AsUInt16(), m2.AsUInt16(), 0b_1111_0000).AsUInt64(); #endif //G2 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4l), r16)); row4h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4h), r16)); #else row4l = Ssse3.Shuffle(row4l.AsByte(), r16).AsUInt64(); row4h = Ssse3.Shuffle(row4h.AsByte(), r16).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); row2l = Sse2.Xor(Sse2.ShiftRightLogical(row2l, 63), Sse2.Add(row2l, row2l)); row2h = Sse2.Xor(Sse2.ShiftRightLogical(row2h, 63), Sse2.Add(row2h, row2h)); //DIAGONALIZE #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2h), Sse.StaticCast<ulong, sbyte>(row2l), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2l), Sse.StaticCast<ulong, sbyte>(row2h), 8); row2l = Sse.StaticCast<sbyte, ulong>(t0); row2h = Sse.StaticCast<sbyte, ulong>(t1); #else t0 = Ssse3.AlignRight(row2h, row2l, 8); t1 = Ssse3.AlignRight(row2l, row2h, 8); row2l = t0; row2h = t1; #endif b0 = row3l; row3l = row3h; row3h = b0; #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4h), Sse.StaticCast<ulong, sbyte>(row4l), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4l), Sse.StaticCast<ulong, sbyte>(row4h), 8); row4l = Sse.StaticCast<sbyte, ulong>(t1); row4h = Sse.StaticCast<sbyte, ulong>(t0); #else t0 = Ssse3.AlignRight(row4h, row4l, 8); t1 = Ssse3.AlignRight(row4l, row4h, 8); row4l = t1; row4h = t0; #endif b0 = Sse2.UnpackHigh(m7, m4); b1 = Sse2.UnpackHigh(m1, m6); //G1 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4l), 0b_10_11_00_01)); row4h = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4h), 0b_10_11_00_01)); #else row4l = Sse2.Shuffle(row4l.AsUInt32(), 0b_10_11_00_01).AsUInt64(); row4h = Sse2.Shuffle(row4h.AsUInt32(), 0b_10_11_00_01).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); #if HWINTRINSICS_EXP row2l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2l), r24)); row2h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2h), r24)); #else row2l = Ssse3.Shuffle(row2l.AsByte(), r24).AsUInt64(); row2h = Ssse3.Shuffle(row2h.AsByte(), r24).AsUInt64(); #endif #if HWINTRINSICS_EXP b0 = Sse.StaticCast<sbyte, ulong>(Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(m7), Sse.StaticCast<ulong, sbyte>(m5), 8)); #else b0 = Ssse3.AlignRight(m7, m5, 8); #endif b1 = Sse2.UnpackLow(m6, m0); //G2 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4l), r16)); row4h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4h), r16)); #else row4l = Ssse3.Shuffle(row4l.AsByte(), r16).AsUInt64(); row4h = Ssse3.Shuffle(row4h.AsByte(), r16).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); row2l = Sse2.Xor(Sse2.ShiftRightLogical(row2l, 63), Sse2.Add(row2l, row2l)); row2h = Sse2.Xor(Sse2.ShiftRightLogical(row2h, 63), Sse2.Add(row2h, row2h)); //UNDIAGONALIZE #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2l), Sse.StaticCast<ulong, sbyte>(row2h), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2h), Sse.StaticCast<ulong, sbyte>(row2l), 8); row2l = Sse.StaticCast<sbyte, ulong>(t0); row2h = Sse.StaticCast<sbyte, ulong>(t1); #else t0 = Ssse3.AlignRight(row2l, row2h, 8); t1 = Ssse3.AlignRight(row2h, row2l, 8); row2l = t0; row2h = t1; #endif b0 = row3l; row3l = row3h; row3h = b0; #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4l), Sse.StaticCast<ulong, sbyte>(row4h), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4h), Sse.StaticCast<ulong, sbyte>(row4l), 8); row4l = Sse.StaticCast<sbyte, ulong>(t1); row4h = Sse.StaticCast<sbyte, ulong>(t0); #else t0 = Ssse3.AlignRight(row4l, row4h, 8); t1 = Ssse3.AlignRight(row4h, row4l, 8); row4l = t1; row4h = t0; #endif //ROUND 11 b0 = Sse2.UnpackLow(m0, m1); b1 = Sse2.UnpackLow(m2, m3); //G1 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4l), 0b_10_11_00_01)); row4h = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4h), 0b_10_11_00_01)); #else row4l = Sse2.Shuffle(row4l.AsUInt32(), 0b_10_11_00_01).AsUInt64(); row4h = Sse2.Shuffle(row4h.AsUInt32(), 0b_10_11_00_01).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); #if HWINTRINSICS_EXP row2l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2l), r24)); row2h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2h), r24)); #else row2l = Ssse3.Shuffle(row2l.AsByte(), r24).AsUInt64(); row2h = Ssse3.Shuffle(row2h.AsByte(), r24).AsUInt64(); #endif b0 = Sse2.UnpackHigh(m0, m1); b1 = Sse2.UnpackHigh(m2, m3); //G2 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4l), r16)); row4h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4h), r16)); #else row4l = Ssse3.Shuffle(row4l.AsByte(), r16).AsUInt64(); row4h = Ssse3.Shuffle(row4h.AsByte(), r16).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); row2l = Sse2.Xor(Sse2.ShiftRightLogical(row2l, 63), Sse2.Add(row2l, row2l)); row2h = Sse2.Xor(Sse2.ShiftRightLogical(row2h, 63), Sse2.Add(row2h, row2h)); //DIAGONALIZE #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2h), Sse.StaticCast<ulong, sbyte>(row2l), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2l), Sse.StaticCast<ulong, sbyte>(row2h), 8); row2l = Sse.StaticCast<sbyte, ulong>(t0); row2h = Sse.StaticCast<sbyte, ulong>(t1); #else t0 = Ssse3.AlignRight(row2h, row2l, 8); t1 = Ssse3.AlignRight(row2l, row2h, 8); row2l = t0; row2h = t1; #endif b0 = row3l; row3l = row3h; row3h = b0; #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4h), Sse.StaticCast<ulong, sbyte>(row4l), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4l), Sse.StaticCast<ulong, sbyte>(row4h), 8); row4l = Sse.StaticCast<sbyte, ulong>(t1); row4h = Sse.StaticCast<sbyte, ulong>(t0); #else t0 = Ssse3.AlignRight(row4h, row4l, 8); t1 = Ssse3.AlignRight(row4l, row4h, 8); row4l = t1; row4h = t0; #endif b0 = Sse2.UnpackLow(m4, m5); b1 = Sse2.UnpackLow(m6, m7); //G1 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4l), 0b_10_11_00_01)); row4h = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4h), 0b_10_11_00_01)); #else row4l = Sse2.Shuffle(row4l.AsUInt32(), 0b_10_11_00_01).AsUInt64(); row4h = Sse2.Shuffle(row4h.AsUInt32(), 0b_10_11_00_01).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); #if HWINTRINSICS_EXP row2l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2l), r24)); row2h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2h), r24)); #else row2l = Ssse3.Shuffle(row2l.AsByte(), r24).AsUInt64(); row2h = Ssse3.Shuffle(row2h.AsByte(), r24).AsUInt64(); #endif b0 = Sse2.UnpackHigh(m4, m5); b1 = Sse2.UnpackHigh(m6, m7); //G2 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4l), r16)); row4h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4h), r16)); #else row4l = Ssse3.Shuffle(row4l.AsByte(), r16).AsUInt64(); row4h = Ssse3.Shuffle(row4h.AsByte(), r16).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); row2l = Sse2.Xor(Sse2.ShiftRightLogical(row2l, 63), Sse2.Add(row2l, row2l)); row2h = Sse2.Xor(Sse2.ShiftRightLogical(row2h, 63), Sse2.Add(row2h, row2h)); //UNDIAGONALIZE #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2l), Sse.StaticCast<ulong, sbyte>(row2h), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2h), Sse.StaticCast<ulong, sbyte>(row2l), 8); row2l = Sse.StaticCast<sbyte, ulong>(t0); row2h = Sse.StaticCast<sbyte, ulong>(t1); #else t0 = Ssse3.AlignRight(row2l, row2h, 8); t1 = Ssse3.AlignRight(row2h, row2l, 8); row2l = t0; row2h = t1; #endif b0 = row3l; row3l = row3h; row3h = b0; #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4l), Sse.StaticCast<ulong, sbyte>(row4h), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4h), Sse.StaticCast<ulong, sbyte>(row4l), 8); row4l = Sse.StaticCast<sbyte, ulong>(t1); row4h = Sse.StaticCast<sbyte, ulong>(t0); #else t0 = Ssse3.AlignRight(row4l, row4h, 8); t1 = Ssse3.AlignRight(row4h, row4l, 8); row4l = t1; row4h = t0; #endif //ROUND 12 b0 = Sse2.UnpackLow(m7, m2); b1 = Sse2.UnpackHigh(m4, m6); //G1 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4l), 0b_10_11_00_01)); row4h = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4h), 0b_10_11_00_01)); #else row4l = Sse2.Shuffle(row4l.AsUInt32(), 0b_10_11_00_01).AsUInt64(); row4h = Sse2.Shuffle(row4h.AsUInt32(), 0b_10_11_00_01).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); #if HWINTRINSICS_EXP row2l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2l), r24)); row2h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2h), r24)); #else row2l = Ssse3.Shuffle(row2l.AsByte(), r24).AsUInt64(); row2h = Ssse3.Shuffle(row2h.AsByte(), r24).AsUInt64(); #endif b0 = Sse2.UnpackLow(m5, m4); #if HWINTRINSICS_EXP b1 = Sse.StaticCast<sbyte, ulong>(Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(m3), Sse.StaticCast<ulong, sbyte>(m7), 8)); #else b1 = Ssse3.AlignRight(m3, m7, 8); #endif //G2 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4l), r16)); row4h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4h), r16)); #else row4l = Ssse3.Shuffle(row4l.AsByte(), r16).AsUInt64(); row4h = Ssse3.Shuffle(row4h.AsByte(), r16).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); row2l = Sse2.Xor(Sse2.ShiftRightLogical(row2l, 63), Sse2.Add(row2l, row2l)); row2h = Sse2.Xor(Sse2.ShiftRightLogical(row2h, 63), Sse2.Add(row2h, row2h)); //DIAGONALIZE #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2h), Sse.StaticCast<ulong, sbyte>(row2l), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2l), Sse.StaticCast<ulong, sbyte>(row2h), 8); row2l = Sse.StaticCast<sbyte, ulong>(t0); row2h = Sse.StaticCast<sbyte, ulong>(t1); #else t0 = Ssse3.AlignRight(row2h, row2l, 8); t1 = Ssse3.AlignRight(row2l, row2h, 8); row2l = t0; row2h = t1; #endif b0 = row3l; row3l = row3h; row3h = b0; #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4h), Sse.StaticCast<ulong, sbyte>(row4l), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4l), Sse.StaticCast<ulong, sbyte>(row4h), 8); row4l = Sse.StaticCast<sbyte, ulong>(t1); row4h = Sse.StaticCast<sbyte, ulong>(t0); #else t0 = Ssse3.AlignRight(row4h, row4l, 8); t1 = Ssse3.AlignRight(row4l, row4h, 8); row4l = t1; row4h = t0; #endif #if HWINTRINSICS_EXP b0 = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(m0), 0b_01_00_11_10)); #else b0 = Sse2.Shuffle(m0.AsUInt32(), 0b_01_00_11_10).AsUInt64(); #endif b1 = Sse2.UnpackHigh(m5, m2); //G1 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4l), 0b_10_11_00_01)); row4h = Sse.StaticCast<uint, ulong>(Sse2.Shuffle(Sse.StaticCast<ulong, uint>(row4h), 0b_10_11_00_01)); #else row4l = Sse2.Shuffle(row4l.AsUInt32(), 0b_10_11_00_01).AsUInt64(); row4h = Sse2.Shuffle(row4h.AsUInt32(), 0b_10_11_00_01).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); #if HWINTRINSICS_EXP row2l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2l), r24)); row2h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row2h), r24)); #else row2l = Ssse3.Shuffle(row2l.AsByte(), r24).AsUInt64(); row2h = Ssse3.Shuffle(row2h.AsByte(), r24).AsUInt64(); #endif b0 = Sse2.UnpackLow(m6, m1); b1 = Sse2.UnpackHigh(m3, m1); //G2 row1l = Sse2.Add(Sse2.Add(row1l, b0), row2l); row1h = Sse2.Add(Sse2.Add(row1h, b1), row2h); row4l = Sse2.Xor(row4l, row1l); row4h = Sse2.Xor(row4h, row1h); #if HWINTRINSICS_EXP row4l = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4l), r16)); row4h = Sse.StaticCast<sbyte, ulong>(Ssse3.Shuffle(Sse.StaticCast<ulong, sbyte>(row4h), r16)); #else row4l = Ssse3.Shuffle(row4l.AsByte(), r16).AsUInt64(); row4h = Ssse3.Shuffle(row4h.AsByte(), r16).AsUInt64(); #endif row3l = Sse2.Add(row3l, row4l); row3h = Sse2.Add(row3h, row4h); row2l = Sse2.Xor(row2l, row3l); row2h = Sse2.Xor(row2h, row3h); row2l = Sse2.Xor(Sse2.ShiftRightLogical(row2l, 63), Sse2.Add(row2l, row2l)); row2h = Sse2.Xor(Sse2.ShiftRightLogical(row2h, 63), Sse2.Add(row2h, row2h)); //UNDIAGONALIZE #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2l), Sse.StaticCast<ulong, sbyte>(row2h), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row2h), Sse.StaticCast<ulong, sbyte>(row2l), 8); row2l = Sse.StaticCast<sbyte, ulong>(t0); row2h = Sse.StaticCast<sbyte, ulong>(t1); #else t0 = Ssse3.AlignRight(row2l, row2h, 8); t1 = Ssse3.AlignRight(row2h, row2l, 8); row2l = t0; row2h = t1; #endif b0 = row3l; row3l = row3h; row3h = b0; #if HWINTRINSICS_EXP t0 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4l), Sse.StaticCast<ulong, sbyte>(row4h), 8); t1 = Ssse3.AlignRight(Sse.StaticCast<ulong, sbyte>(row4h), Sse.StaticCast<ulong, sbyte>(row4l), 8); row4l = Sse.StaticCast<sbyte, ulong>(t1); row4h = Sse.StaticCast<sbyte, ulong>(t0); #else t0 = Ssse3.AlignRight(row4l, row4h, 8); t1 = Ssse3.AlignRight(row4h, row4l, 8); row4l = t1; row4h = t0; #endif row1l = Sse2.Xor(row1l, row3l); row1h = Sse2.Xor(row1h, row3h); row1l = Sse2.Xor(row1l, Sse2.LoadVector128(sh)); row1h = Sse2.Xor(row1h, Sse2.LoadVector128(sh + 2)); Sse2.Store(sh, row1l); Sse2.Store(sh + 2, row1h); row2l = Sse2.Xor(row2l, row4l); row2h = Sse2.Xor(row2h, row4h); row2l = Sse2.Xor(row2l, Sse2.LoadVector128(sh + 4)); row2h = Sse2.Xor(row2h, Sse2.LoadVector128(sh + 6)); Sse2.Store(sh + 4, row2l); Sse2.Store(sh + 6, row2h); } } } #endif
34.530074
135
0.679081
[ "MIT" ]
buybackoff/Blake2Fast
src/Blake2Fast/Blake2b/Blake2bSse4.cs
79,801
C#
namespace EventStore.Core.LogAbstraction { public interface ISystemStreamLookup<TStreamId> { TStreamId AllStream { get; } TStreamId SettingsStream { get; } bool IsMetaStream(TStreamId streamId); bool IsSystemStream(TStreamId streamId); TStreamId MetaStreamOf(TStreamId streamId); TStreamId OriginalStreamOf(TStreamId streamId); } }
29
50
0.79023
[ "Apache-2.0", "CC0-1.0" ]
roketworks/EventStore
src/EventStore.Core/LogAbstraction/ISystemStreamLookup.cs
350
C#
using Hoteles.BL; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Hoteles { public partial class Form3 : Form { public Form3() { InitializeComponent(); } public void cargarDatos(FacturaBL facturasBL, ClientesBL clientesBL, HabitacionesBL habitacionesBL) { listaDeFacturasBindingSource.DataSource = facturasBL.ListaDeFacturas; listaDeClientesBindingSource.DataSource = clientesBL.ListaDeClientes; listaDeHabitacionesBindingSource.DataSource = habitacionesBL.ListaDeHabitaciones; } } }
14.740741
107
0.693467
[ "MIT" ]
yosephf02f/P
Hoteles/Hoteles/Form3.cs
798
C#
using Ninject; namespace LAST.Business.DependencyResolvers.Ninject { public class InstanceFactory { public static T GetInstance<T>() { return new StandardKernel(new BusinessModule()).Get<T>(); } } }
19.153846
69
0.618474
[ "MIT" ]
aTiKhan/layered-architecture-solution-template
TemplateProject/LAST.Business/DependencyResolvers/Ninject/InstanceFactory.cs
251
C#
using UnityEngine; using System.Collections; public class LandoltTouch : MonoBehaviour { public Color normalColor = Color.green; public Color touchedColor = Color.blue; private Renderer renderer_; void Start() { renderer_ = GetComponent<Renderer>(); } void OnTouchStart(Vector2 pos) { renderer_.material.color = touchedColor; } void OnTouchMove(Vector2 pos) { } void OnTouchEnd(Vector2 pos) { renderer_.material.color = normalColor; } }
15.5
42
0.735484
[ "MIT" ]
hecomi/LITTAI-game
Assets/Scripts/Recognition/LandoltTouch.cs
467
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.AliCloud.CloudSso { /// <summary> /// Provides a Cloud SSO Group resource. /// /// For information about Cloud SSO Group and how to use it, see [What is Group](https://www.alibabacloud.com/help/doc-detail/264683.html). /// /// &gt; **NOTE:** Available in v1.138.0+. /// /// &gt; **NOTE:** Cloud SSO Only Support `cn-shanghai` And `us-west-1` Region /// /// ## Import /// /// Cloud SSO Group can be imported using the id, e.g. /// /// ```sh /// $ pulumi import alicloud:cloudsso/group:Group example &lt;directory_id&gt;:&lt;group_id&gt; /// ``` /// </summary> [AliCloudResourceType("alicloud:cloudsso/group:Group")] public partial class Group : Pulumi.CustomResource { /// <summary> /// The Description of the group. /// </summary> [Output("description")] public Output<string?> Description { get; private set; } = null!; /// <summary> /// The ID of the Directory. /// </summary> [Output("directoryId")] public Output<string> DirectoryId { get; private set; } = null!; /// <summary> /// The GroupId of the group. /// </summary> [Output("groupId")] public Output<string> GroupId { get; private set; } = null!; /// <summary> /// The Name of the group. /// </summary> [Output("groupName")] public Output<string> GroupName { get; private set; } = null!; /// <summary> /// Create a Group 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 Group(string name, GroupArgs args, CustomResourceOptions? options = null) : base("alicloud:cloudsso/group:Group", name, args ?? new GroupArgs(), MakeResourceOptions(options, "")) { } private Group(string name, Input<string> id, GroupState? state = null, CustomResourceOptions? options = null) : base("alicloud:cloudsso/group:Group", 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 Group 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 Group Get(string name, Input<string> id, GroupState? state = null, CustomResourceOptions? options = null) { return new Group(name, id, state, options); } } public sealed class GroupArgs : Pulumi.ResourceArgs { /// <summary> /// The Description of the group. /// </summary> [Input("description")] public Input<string>? Description { get; set; } /// <summary> /// The ID of the Directory. /// </summary> [Input("directoryId", required: true)] public Input<string> DirectoryId { get; set; } = null!; /// <summary> /// The Name of the group. /// </summary> [Input("groupName", required: true)] public Input<string> GroupName { get; set; } = null!; public GroupArgs() { } } public sealed class GroupState : Pulumi.ResourceArgs { /// <summary> /// The Description of the group. /// </summary> [Input("description")] public Input<string>? Description { get; set; } /// <summary> /// The ID of the Directory. /// </summary> [Input("directoryId")] public Input<string>? DirectoryId { get; set; } /// <summary> /// The GroupId of the group. /// </summary> [Input("groupId")] public Input<string>? GroupId { get; set; } /// <summary> /// The Name of the group. /// </summary> [Input("groupName")] public Input<string>? GroupName { get; set; } public GroupState() { } } }
34.910256
143
0.573448
[ "ECL-2.0", "Apache-2.0" ]
pulumi/pulumi-alicloud
sdk/dotnet/CloudSso/Group.cs
5,446
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.Migrate.Support { /// <summary>TypeConverter implementation for ProtectionHealth.</summary> public partial class ProtectionHealthTypeConverter : global::System.Management.Automation.PSTypeConverter { /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c>. /// </returns> public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => true; /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c>. /// </returns> public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; /// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns> /// an instance of <see cref="ProtectionHealth" />, or <c>null</c> if there is no suitable conversion. /// </returns> public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ProtectionHealth.CreateFrom(sourceValue); /// <summary>NotImplemented -- this will return <c>null</c></summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns>will always return <c>null</c>.</returns> public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; } }
63.440678
209
0.649212
[ "MIT" ]
Click4PV/azure-powershell
src/Migrate/generated/api/Support/ProtectionHealth.TypeConverter.cs
3,685
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.EventGrid.Inputs { public sealed class SystemTopicEventSubscriptionAdvancedFilterNumberLessThanGetArgs : Pulumi.ResourceArgs { /// <summary> /// Specifies the field within the event data that you want to use for filtering. Type of the field can be a number, boolean, or string. /// </summary> [Input("key", required: true)] public Input<string> Key { get; set; } = null!; /// <summary> /// Specifies a single value to compare to when using a single value operator. /// </summary> [Input("value", required: true)] public Input<double> Value { get; set; } = null!; public SystemTopicEventSubscriptionAdvancedFilterNumberLessThanGetArgs() { } } }
34.40625
144
0.668483
[ "ECL-2.0", "Apache-2.0" ]
ScriptBox99/pulumi-azure
sdk/dotnet/EventGrid/Inputs/SystemTopicEventSubscriptionAdvancedFilterNumberLessThanGetArgs.cs
1,101
C#
/* MIT License Copyright (c) 2016 JetBrains http://www.jetbrains.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; #pragma warning disable 1591 // ReSharper disable UnusedMember.Global // ReSharper disable MemberCanBePrivate.Global // ReSharper disable UnusedAutoPropertyAccessor.Global // ReSharper disable IntroduceOptionalParameters.Global // ReSharper disable MemberCanBeProtected.Global // ReSharper disable InconsistentNaming namespace EksiSozluk.CloneUI.Extension.Notify { /// <summary> /// Indicates that the value of the marked element could be <c>null</c> sometimes, /// so the check for <c>null</c> is necessary before its usage. /// </summary> /// <example><code> /// [CanBeNull] object Test() => null; /// /// void UseTest() { /// var p = Test(); /// var s = p.ToString(); // Warning: Possible 'System.NullReferenceException' /// } /// </code></example> [AttributeUsage( AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.GenericParameter)] public sealed class CanBeNullAttribute : Attribute { } /// <summary> /// Indicates that the value of the marked element could never be <c>null</c>. /// </summary> /// <example><code> /// [NotNull] object Foo() { /// return null; // Warning: Possible 'null' assignment /// } /// </code></example> [AttributeUsage( AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.GenericParameter)] public sealed class NotNullAttribute : Attribute { } /// <summary> /// Can be appplied to symbols of types derived from IEnumerable as well as to symbols of Task /// and Lazy classes to indicate that the value of a collection item, of the Task.Result property /// or of the Lazy.Value property can never be null. /// </summary> [AttributeUsage( AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field)] public sealed class ItemNotNullAttribute : Attribute { } /// <summary> /// Can be appplied to symbols of types derived from IEnumerable as well as to symbols of Task /// and Lazy classes to indicate that the value of a collection item, of the Task.Result property /// or of the Lazy.Value property can be null. /// </summary> [AttributeUsage( AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field)] public sealed class ItemCanBeNullAttribute : Attribute { } /// <summary> /// Indicates that the marked method builds string by format pattern and (optional) arguments. /// Parameter, which contains format string, should be given in constructor. The format string /// should be in <see cref="string.Format(IFormatProvider,string,object[])"/>-like form. /// </summary> /// <example><code> /// [StringFormatMethod("message")] /// void ShowError(string message, params object[] args) { /* do something */ } /// /// void Foo() { /// ShowError("Failed: {0}"); // Warning: Non-existing argument in format string /// } /// </code></example> [AttributeUsage( AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Delegate)] public sealed class StringFormatMethodAttribute : Attribute { /// <param name="formatParameterName"> /// Specifies which parameter of an annotated method should be treated as format-string /// </param> public StringFormatMethodAttribute([NotNull] string formatParameterName) { FormatParameterName = formatParameterName; } [NotNull] public string FormatParameterName { get; private set; } } /// <summary> /// For a parameter that is expected to be one of the limited set of values. /// Specify fields of which type should be used as values for this parameter. /// </summary> [AttributeUsage( AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true)] public sealed class ValueProviderAttribute : Attribute { public ValueProviderAttribute([NotNull] string name) { Name = name; } [NotNull] public string Name { get; private set; } } /// <summary> /// Indicates that the function argument should be string literal and match one /// of the parameters of the caller function. For example, ReSharper annotates /// the parameter of <see cref="System.ArgumentNullException"/>. /// </summary> /// <example><code> /// void Foo(string param) { /// if (param == null) /// throw new ArgumentNullException("par"); // Warning: Cannot resolve symbol /// } /// </code></example> [AttributeUsage(AttributeTargets.Parameter)] public sealed class InvokerParameterNameAttribute : Attribute { } /// <summary> /// Indicates that the method is contained in a type that implements /// <c>System.ComponentModel.INotifyPropertyChanged</c> interface and this method /// is used to notify that some property value changed. /// </summary> /// <remarks> /// The method should be non-static and conform to one of the supported signatures: /// <list> /// <item><c>NotifyChanged(string)</c></item> /// <item><c>NotifyChanged(params string[])</c></item> /// <item><c>NotifyChanged{T}(Expression{Func{T}})</c></item> /// <item><c>NotifyChanged{T,U}(Expression{Func{T,U}})</c></item> /// <item><c>SetProperty{T}(ref T, T, string)</c></item> /// </list> /// </remarks> /// <example><code> /// public class Foo : INotifyPropertyChanged { /// public event PropertyChangedEventHandler PropertyChanged; /// /// [NotifyPropertyChangedInvocator] /// protected virtual void NotifyChanged(string propertyName) { ... } /// /// string _name; /// /// public string Name { /// get { return _name; } /// set { _name = value; NotifyChanged("LastName"); /* Warning */ } /// } /// } /// </code> /// Examples of generated notifications: /// <list> /// <item><c>NotifyChanged("Property")</c></item> /// <item><c>NotifyChanged(() =&gt; Property)</c></item> /// <item><c>NotifyChanged((VM x) =&gt; x.Property)</c></item> /// <item><c>SetProperty(ref myField, value, "Property")</c></item> /// </list> /// </example> [AttributeUsage(AttributeTargets.Method)] public sealed class NotifyPropertyChangedInvocatorAttribute : Attribute { public NotifyPropertyChangedInvocatorAttribute() { } public NotifyPropertyChangedInvocatorAttribute([NotNull] string parameterName) { ParameterName = parameterName; } [CanBeNull] public string ParameterName { get; private set; } } /// <summary> /// Describes dependency between method input and output. /// </summary> /// <syntax> /// <p>Function Definition Table syntax:</p> /// <list> /// <item>FDT ::= FDTRow [;FDTRow]*</item> /// <item>FDTRow ::= Input =&gt; Output | Output &lt;= Input</item> /// <item>Input ::= ParameterName: Value [, Input]*</item> /// <item>Output ::= [ParameterName: Value]* {halt|stop|void|nothing|Value}</item> /// <item>Value ::= true | false | null | notnull | canbenull</item> /// </list> /// If method has single input parameter, it's name could be omitted.<br/> /// Using <c>halt</c> (or <c>void</c>/<c>nothing</c>, which is the same) for method output /// means that the methos doesn't return normally (throws or terminates the process).<br/> /// Value <c>canbenull</c> is only applicable for output parameters.<br/> /// You can use multiple <c>[ContractAnnotation]</c> for each FDT row, or use single attribute /// with rows separated by semicolon. There is no notion of order rows, all rows are checked /// for applicability and applied per each program state tracked by R# analysis.<br/> /// </syntax> /// <examples><list> /// <item><code> /// [ContractAnnotation("=&gt; halt")] /// public void TerminationMethod() /// </code></item> /// <item><code> /// [ContractAnnotation("halt &lt;= condition: false")] /// public void Assert(bool condition, string text) // regular assertion method /// </code></item> /// <item><code> /// [ContractAnnotation("s:null =&gt; true")] /// public bool IsNullOrEmpty(string s) // string.IsNullOrEmpty() /// </code></item> /// <item><code> /// // A method that returns null if the parameter is null, /// // and not null if the parameter is not null /// [ContractAnnotation("null =&gt; null; notnull =&gt; notnull")] /// public object Transform(object data) /// </code></item> /// <item><code> /// [ContractAnnotation("=&gt; true, result: notnull; =&gt; false, result: null")] /// public bool TryParse(string s, out Person result) /// </code></item> /// </list></examples> [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public sealed class ContractAnnotationAttribute : Attribute { public ContractAnnotationAttribute([NotNull] string contract) : this(contract, false) { } public ContractAnnotationAttribute([NotNull] string contract, bool forceFullStates) { Contract = contract; ForceFullStates = forceFullStates; } [NotNull] public string Contract { get; private set; } public bool ForceFullStates { get; private set; } } /// <summary> /// Indicates that marked element should be localized or not. /// </summary> /// <example><code> /// [LocalizationRequiredAttribute(true)] /// class Foo { /// string str = "my string"; // Warning: Localizable string /// } /// </code></example> [AttributeUsage(AttributeTargets.All)] public sealed class LocalizationRequiredAttribute : Attribute { public LocalizationRequiredAttribute() : this(true) { } public LocalizationRequiredAttribute(bool required) { Required = required; } public bool Required { get; private set; } } /// <summary> /// Indicates that the value of the marked type (or its derivatives) /// cannot be compared using '==' or '!=' operators and <c>Equals()</c> /// should be used instead. However, using '==' or '!=' for comparison /// with <c>null</c> is always permitted. /// </summary> /// <example><code> /// [CannotApplyEqualityOperator] /// class NoEquality { } /// /// class UsesNoEquality { /// void Test() { /// var ca1 = new NoEquality(); /// var ca2 = new NoEquality(); /// if (ca1 != null) { // OK /// bool condition = ca1 == ca2; // Warning /// } /// } /// } /// </code></example> [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct)] public sealed class CannotApplyEqualityOperatorAttribute : Attribute { } /// <summary> /// When applied to a target attribute, specifies a requirement for any type marked /// with the target attribute to implement or inherit specific type or types. /// </summary> /// <example><code> /// [BaseTypeRequired(typeof(IComponent)] // Specify requirement /// class ComponentAttribute : Attribute { } /// /// [Component] // ComponentAttribute requires implementing IComponent interface /// class MyComponent : IComponent { } /// </code></example> [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] [BaseTypeRequired(typeof(Attribute))] public sealed class BaseTypeRequiredAttribute : Attribute { public BaseTypeRequiredAttribute([NotNull] Type baseType) { BaseType = baseType; } [NotNull] public Type BaseType { get; private set; } } /// <summary> /// Indicates that the marked symbol is used implicitly (e.g. via reflection, in external library), /// so this symbol will not be marked as unused (as well as by other usage inspections). /// </summary> [AttributeUsage(AttributeTargets.All)] public sealed class UsedImplicitlyAttribute : Attribute { public UsedImplicitlyAttribute() : this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { } public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags) : this(useKindFlags, ImplicitUseTargetFlags.Default) { } public UsedImplicitlyAttribute(ImplicitUseTargetFlags targetFlags) : this(ImplicitUseKindFlags.Default, targetFlags) { } public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags) { UseKindFlags = useKindFlags; TargetFlags = targetFlags; } public ImplicitUseKindFlags UseKindFlags { get; private set; } public ImplicitUseTargetFlags TargetFlags { get; private set; } } /// <summary> /// Should be used on attributes and causes ReSharper to not mark symbols marked with such attributes /// as unused (as well as by other usage inspections) /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.GenericParameter)] public sealed class MeansImplicitUseAttribute : Attribute { public MeansImplicitUseAttribute() : this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { } public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags) : this(useKindFlags, ImplicitUseTargetFlags.Default) { } public MeansImplicitUseAttribute(ImplicitUseTargetFlags targetFlags) : this(ImplicitUseKindFlags.Default, targetFlags) { } public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags) { UseKindFlags = useKindFlags; TargetFlags = targetFlags; } [UsedImplicitly] public ImplicitUseKindFlags UseKindFlags { get; private set; } [UsedImplicitly] public ImplicitUseTargetFlags TargetFlags { get; private set; } } [Flags] public enum ImplicitUseKindFlags { Default = Access | Assign | InstantiatedWithFixedConstructorSignature, /// <summary>Only entity marked with attribute considered used.</summary> Access = 1, /// <summary>Indicates implicit assignment to a member.</summary> Assign = 2, /// <summary> /// Indicates implicit instantiation of a type with fixed constructor signature. /// That means any unused constructor parameters won't be reported as such. /// </summary> InstantiatedWithFixedConstructorSignature = 4, /// <summary>Indicates implicit instantiation of a type.</summary> InstantiatedNoFixedConstructorSignature = 8, } /// <summary> /// Specify what is considered used implicitly when marked /// with <see cref="MeansImplicitUseAttribute"/> or <see cref="UsedImplicitlyAttribute"/>. /// </summary> [Flags] public enum ImplicitUseTargetFlags { Default = Itself, Itself = 1, /// <summary>Members of entity marked with attribute are considered used.</summary> Members = 2, /// <summary>Entity marked with attribute and all its members considered used.</summary> WithMembers = Itself | Members } /// <summary> /// This attribute is intended to mark publicly available API /// which should not be removed and so is treated as used. /// </summary> [MeansImplicitUse(ImplicitUseTargetFlags.WithMembers)] public sealed class PublicAPIAttribute : Attribute { public PublicAPIAttribute() { } public PublicAPIAttribute([NotNull] string comment) { Comment = comment; } [CanBeNull] public string Comment { get; private set; } } /// <summary> /// Tells code analysis engine if the parameter is completely handled when the invoked method is on stack. /// If the parameter is a delegate, indicates that delegate is executed while the method is executed. /// If the parameter is an enumerable, indicates that it is enumerated while the method is executed. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] public sealed class InstantHandleAttribute : Attribute { } /// <summary> /// Indicates that a method does not make any observable state changes. /// The same as <c>System.Diagnostics.Contracts.PureAttribute</c>. /// </summary> /// <example><code> /// [Pure] int Multiply(int x, int y) => x * y; /// /// void M() { /// Multiply(123, 42); // Waring: Return value of pure method is not used /// } /// </code></example> [AttributeUsage(AttributeTargets.Method)] public sealed class PureAttribute : Attribute { } /// <summary> /// Indicates that the return value of method invocation must be used. /// </summary> [AttributeUsage(AttributeTargets.Method)] public sealed class MustUseReturnValueAttribute : Attribute { public MustUseReturnValueAttribute() { } public MustUseReturnValueAttribute([NotNull] string justification) { Justification = justification; } [CanBeNull] public string Justification { get; private set; } } /// <summary> /// Indicates the type member or parameter of some type, that should be used instead of all other ways /// to get the value that type. This annotation is useful when you have some "context" value evaluated /// and stored somewhere, meaning that all other ways to get this value must be consolidated with existing one. /// </summary> /// <example><code> /// class Foo { /// [ProvidesContext] IBarService _barService = ...; /// /// void ProcessNode(INode node) { /// DoSomething(node, node.GetGlobalServices().Bar); /// // ^ Warning: use value of '_barService' field /// } /// } /// </code></example> [AttributeUsage( AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct | AttributeTargets.GenericParameter)] public sealed class ProvidesContextAttribute : Attribute { } /// <summary> /// Indicates that a parameter is a path to a file or a folder within a web project. /// Path can be relative or absolute, starting from web root (~). /// </summary> [AttributeUsage(AttributeTargets.Parameter)] public sealed class PathReferenceAttribute : Attribute { public PathReferenceAttribute() { } public PathReferenceAttribute([NotNull, PathReference] string basePath) { BasePath = basePath; } [CanBeNull] public string BasePath { get; private set; } } /// <summary> /// An extension method marked with this attribute is processed by ReSharper code completion /// as a 'Source Template'. When extension method is completed over some expression, it's source code /// is automatically expanded like a template at call site. /// </summary> /// <remarks> /// Template method body can contain valid source code and/or special comments starting with '$'. /// Text inside these comments is added as source code when the template is applied. Template parameters /// can be used either as additional method parameters or as identifiers wrapped in two '$' signs. /// Use the <see cref="MacroAttribute"/> attribute to specify macros for parameters. /// </remarks> /// <example> /// In this example, the 'forEach' method is a source template available over all values /// of enumerable types, producing ordinary C# 'foreach' statement and placing caret inside block: /// <code> /// [SourceTemplate] /// public static void forEach&lt;T&gt;(this IEnumerable&lt;T&gt; xs) { /// foreach (var x in xs) { /// //$ $END$ /// } /// } /// </code> /// </example> [AttributeUsage(AttributeTargets.Method)] public sealed class SourceTemplateAttribute : Attribute { } /// <summary> /// Allows specifying a macro for a parameter of a <see cref="SourceTemplateAttribute">source template</see>. /// </summary> /// <remarks> /// You can apply the attribute on the whole method or on any of its additional parameters. The macro expression /// is defined in the <see cref="MacroAttribute.Expression"/> property. When applied on a method, the target /// template parameter is defined in the <see cref="MacroAttribute.Target"/> property. To apply the macro silently /// for the parameter, set the <see cref="MacroAttribute.Editable"/> property value = -1. /// </remarks> /// <example> /// Applying the attribute on a source template method: /// <code> /// [SourceTemplate, Macro(Target = "item", Expression = "suggestVariableName()")] /// public static void forEach&lt;T&gt;(this IEnumerable&lt;T&gt; collection) { /// foreach (var item in collection) { /// //$ $END$ /// } /// } /// </code> /// Applying the attribute on a template method parameter: /// <code> /// [SourceTemplate] /// public static void something(this Entity x, [Macro(Expression = "guid()", Editable = -1)] string newguid) { /// /*$ var $x$Id = "$newguid$" + x.ToString(); /// x.DoSomething($x$Id); */ /// } /// </code> /// </example> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method, AllowMultiple = true)] public sealed class MacroAttribute : Attribute { /// <summary> /// Allows specifying a macro that will be executed for a <see cref="SourceTemplateAttribute">source template</see> /// parameter when the template is expanded. /// </summary> [CanBeNull] public string Expression { get; set; } /// <summary> /// Allows specifying which occurrence of the target parameter becomes editable when the template is deployed. /// </summary> /// <remarks> /// If the target parameter is used several times in the template, only one occurrence becomes editable; /// other occurrences are changed synchronously. To specify the zero-based index of the editable occurrence, /// use values >= 0. To make the parameter non-editable when the template is expanded, use -1. /// </remarks>> public int Editable { get; set; } /// <summary> /// Identifies the target parameter of a <see cref="SourceTemplateAttribute">source template</see> if the /// <see cref="MacroAttribute"/> is applied on a template method. /// </summary> [CanBeNull] public string Target { get; set; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] public sealed class AspMvcAreaMasterLocationFormatAttribute : Attribute { public AspMvcAreaMasterLocationFormatAttribute([NotNull] string format) { Format = format; } [NotNull] public string Format { get; private set; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] public sealed class AspMvcAreaPartialViewLocationFormatAttribute : Attribute { public AspMvcAreaPartialViewLocationFormatAttribute([NotNull] string format) { Format = format; } [NotNull] public string Format { get; private set; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] public sealed class AspMvcAreaViewLocationFormatAttribute : Attribute { public AspMvcAreaViewLocationFormatAttribute([NotNull] string format) { Format = format; } [NotNull] public string Format { get; private set; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] public sealed class AspMvcMasterLocationFormatAttribute : Attribute { public AspMvcMasterLocationFormatAttribute([NotNull] string format) { Format = format; } [NotNull] public string Format { get; private set; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] public sealed class AspMvcPartialViewLocationFormatAttribute : Attribute { public AspMvcPartialViewLocationFormatAttribute([NotNull] string format) { Format = format; } [NotNull] public string Format { get; private set; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] public sealed class AspMvcViewLocationFormatAttribute : Attribute { public AspMvcViewLocationFormatAttribute([NotNull] string format) { Format = format; } [NotNull] public string Format { get; private set; } } /// <summary> /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter /// is an MVC action. If applied to a method, the MVC action name is calculated /// implicitly from the context. Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)] public sealed class AspMvcActionAttribute : Attribute { public AspMvcActionAttribute() { } public AspMvcActionAttribute([NotNull] string anonymousProperty) { AnonymousProperty = anonymousProperty; } [CanBeNull] public string AnonymousProperty { get; private set; } } /// <summary> /// ASP.NET MVC attribute. Indicates that a parameter is an MVC area. /// Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] public sealed class AspMvcAreaAttribute : Attribute { public AspMvcAreaAttribute() { } public AspMvcAreaAttribute([NotNull] string anonymousProperty) { AnonymousProperty = anonymousProperty; } [CanBeNull] public string AnonymousProperty { get; private set; } } /// <summary> /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter is /// an MVC controller. If applied to a method, the MVC controller name is calculated /// implicitly from the context. Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String, String)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)] public sealed class AspMvcControllerAttribute : Attribute { public AspMvcControllerAttribute() { } public AspMvcControllerAttribute([NotNull] string anonymousProperty) { AnonymousProperty = anonymousProperty; } [CanBeNull] public string AnonymousProperty { get; private set; } } /// <summary> /// ASP.NET MVC attribute. Indicates that a parameter is an MVC Master. Use this attribute /// for custom wrappers similar to <c>System.Web.Mvc.Controller.View(String, String)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] public sealed class AspMvcMasterAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. Indicates that a parameter is an MVC model type. Use this attribute /// for custom wrappers similar to <c>System.Web.Mvc.Controller.View(String, Object)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] public sealed class AspMvcModelTypeAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter is an MVC /// partial view. If applied to a method, the MVC partial view name is calculated implicitly /// from the context. Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Html.RenderPartialExtensions.RenderPartial(HtmlHelper, String)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)] public sealed class AspMvcPartialViewAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. Allows disabling inspections for MVC views within a class or a method. /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public sealed class AspMvcSuppressViewErrorAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. Indicates that a parameter is an MVC display template. /// Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Html.DisplayExtensions.DisplayForModel(HtmlHelper, String)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] public sealed class AspMvcDisplayTemplateAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. Indicates that a parameter is an MVC editor template. /// Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Html.EditorExtensions.EditorForModel(HtmlHelper, String)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] public sealed class AspMvcEditorTemplateAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. Indicates that a parameter is an MVC template. /// Use this attribute for custom wrappers similar to /// <c>System.ComponentModel.DataAnnotations.UIHintAttribute(System.String)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] public sealed class AspMvcTemplateAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter /// is an MVC view component. If applied to a method, the MVC view name is calculated implicitly /// from the context. Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Controller.View(Object)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)] public sealed class AspMvcViewAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter /// is an MVC view component name. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] public sealed class AspMvcViewComponentAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter /// is an MVC view component view. If applied to a method, the MVC view component view name is default. /// </summary> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)] public sealed class AspMvcViewComponentViewAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. When applied to a parameter of an attribute, /// indicates that this parameter is an MVC action name. /// </summary> /// <example><code> /// [ActionName("Foo")] /// public ActionResult Login(string returnUrl) { /// ViewBag.ReturnUrl = Url.Action("Foo"); // OK /// return RedirectToAction("Bar"); // Error: Cannot resolve action /// } /// </code></example> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property)] public sealed class AspMvcActionSelectorAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Field)] public sealed class HtmlElementAttributesAttribute : Attribute { public HtmlElementAttributesAttribute() { } public HtmlElementAttributesAttribute([NotNull] string name) { Name = name; } [CanBeNull] public string Name { get; private set; } } [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property)] public sealed class HtmlAttributeValueAttribute : Attribute { public HtmlAttributeValueAttribute([NotNull] string name) { Name = name; } [NotNull] public string Name { get; private set; } } /// <summary> /// Razor attribute. Indicates that a parameter or a method is a Razor section. /// Use this attribute for custom wrappers similar to /// <c>System.Web.WebPages.WebPageBase.RenderSection(String)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)] public sealed class RazorSectionAttribute : Attribute { } /// <summary> /// Indicates how method, constructor invocation or property access /// over collection type affects content of the collection. /// </summary> [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Property)] public sealed class CollectionAccessAttribute : Attribute { public CollectionAccessAttribute(CollectionAccessType collectionAccessType) { CollectionAccessType = collectionAccessType; } public CollectionAccessType CollectionAccessType { get; private set; } } [Flags] public enum CollectionAccessType { /// <summary>Method does not use or modify content of the collection.</summary> None = 0, /// <summary>Method only reads content of the collection but does not modify it.</summary> Read = 1, /// <summary>Method can change content of the collection but does not add new elements.</summary> ModifyExistingContent = 2, /// <summary>Method can add new elements to the collection.</summary> UpdatedContent = ModifyExistingContent | 4 } /// <summary> /// Indicates that the marked method is assertion method, i.e. it halts control flow if /// one of the conditions is satisfied. To set the condition, mark one of the parameters with /// <see cref="AssertionConditionAttribute"/> attribute. /// </summary> [AttributeUsage(AttributeTargets.Method)] public sealed class AssertionMethodAttribute : Attribute { } /// <summary> /// Indicates the condition parameter of the assertion method. The method itself should be /// marked by <see cref="AssertionMethodAttribute"/> attribute. The mandatory argument of /// the attribute is the assertion type. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] public sealed class AssertionConditionAttribute : Attribute { public AssertionConditionAttribute(AssertionConditionType conditionType) { ConditionType = conditionType; } public AssertionConditionType ConditionType { get; private set; } } /// <summary> /// Specifies assertion type. If the assertion method argument satisfies the condition, /// then the execution continues. Otherwise, execution is assumed to be halted. /// </summary> public enum AssertionConditionType { /// <summary>Marked parameter should be evaluated to true.</summary> IS_TRUE = 0, /// <summary>Marked parameter should be evaluated to false.</summary> IS_FALSE = 1, /// <summary>Marked parameter should be evaluated to null value.</summary> IS_NULL = 2, /// <summary>Marked parameter should be evaluated to not null value.</summary> IS_NOT_NULL = 3, } /// <summary> /// Indicates that the marked method unconditionally terminates control flow execution. /// For example, it could unconditionally throw exception. /// </summary> [Obsolete("Use [ContractAnnotation('=> halt')] instead")] [AttributeUsage(AttributeTargets.Method)] public sealed class TerminatesProgramAttribute : Attribute { } /// <summary> /// Indicates that method is pure LINQ method, with postponed enumeration (like Enumerable.Select, /// .Where). This annotation allows inference of [InstantHandle] annotation for parameters /// of delegate type by analyzing LINQ method chains. /// </summary> [AttributeUsage(AttributeTargets.Method)] public sealed class LinqTunnelAttribute : Attribute { } /// <summary> /// Indicates that IEnumerable, passed as parameter, is not enumerated. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] public sealed class NoEnumerationAttribute : Attribute { } /// <summary> /// Indicates that parameter is regular expression pattern. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] public sealed class RegexPatternAttribute : Attribute { } /// <summary> /// Prevents the Member Reordering feature from tossing members of the marked class. /// </summary> /// <remarks> /// The attribute must be mentioned in your member reordering patterns /// </remarks> [AttributeUsage( AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct | AttributeTargets.Enum)] public sealed class NoReorderAttribute : Attribute { } /// <summary> /// XAML attribute. Indicates the type that has <c>ItemsSource</c> property and should be treated /// as <c>ItemsControl</c>-derived type, to enable inner items <c>DataContext</c> type resolve. /// </summary> [AttributeUsage(AttributeTargets.Class)] public sealed class XamlItemsControlAttribute : Attribute { } /// <summary> /// XAML attribute. Indicates the property of some <c>BindingBase</c>-derived type, that /// is used to bind some item of <c>ItemsControl</c>-derived type. This annotation will /// enable the <c>DataContext</c> type resolve for XAML bindings for such properties. /// </summary> /// <remarks> /// Property should have the tree ancestor of the <c>ItemsControl</c> type or /// marked with the <see cref="XamlItemsControlAttribute"/> attribute. /// </remarks> [AttributeUsage(AttributeTargets.Property)] public sealed class XamlItemBindingOfItemsControlAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public sealed class AspChildControlTypeAttribute : Attribute { public AspChildControlTypeAttribute([NotNull] string tagName, [NotNull] Type controlType) { TagName = tagName; ControlType = controlType; } [NotNull] public string TagName { get; private set; } [NotNull] public Type ControlType { get; private set; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Method)] public sealed class AspDataFieldAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Method)] public sealed class AspDataFieldsAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property)] public sealed class AspMethodPropertyAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public sealed class AspRequiredAttributeAttribute : Attribute { public AspRequiredAttributeAttribute([NotNull] string attribute) { Attribute = attribute; } [NotNull] public string Attribute { get; private set; } } [AttributeUsage(AttributeTargets.Property)] public sealed class AspTypePropertyAttribute : Attribute { public bool CreateConstructorReferences { get; private set; } public AspTypePropertyAttribute(bool createConstructorReferences) { CreateConstructorReferences = createConstructorReferences; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] public sealed class RazorImportNamespaceAttribute : Attribute { public RazorImportNamespaceAttribute([NotNull] string name) { Name = name; } [NotNull] public string Name { get; private set; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] public sealed class RazorInjectionAttribute : Attribute { public RazorInjectionAttribute([NotNull] string type, [NotNull] string fieldName) { Type = type; FieldName = fieldName; } [NotNull] public string Type { get; private set; } [NotNull] public string FieldName { get; private set; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] public sealed class RazorDirectiveAttribute : Attribute { public RazorDirectiveAttribute([NotNull] string directive) { Directive = directive; } [NotNull] public string Directive { get; private set; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] public sealed class RazorPageBaseTypeAttribute : Attribute { public RazorPageBaseTypeAttribute([NotNull] string baseType) { BaseType = baseType; } public RazorPageBaseTypeAttribute([NotNull] string baseType, string pageName) { BaseType = baseType; PageName = pageName; } [NotNull] public string BaseType { get; private set; } [CanBeNull] public string PageName { get; private set; } } [AttributeUsage(AttributeTargets.Method)] public sealed class RazorHelperCommonAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property)] public sealed class RazorLayoutAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method)] public sealed class RazorWriteLiteralMethodAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method)] public sealed class RazorWriteMethodAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter)] public sealed class RazorWriteMethodParameterAttribute : Attribute { } }
37.442308
123
0.6599
[ "MIT" ]
bozd4g/EksiSozluk.CloneUI
EksiSozluk.CloneUI/EksiSozluk.CloneUI/Extension/Notify/Annotations.cs
44,783
C#
// // Enums.cs // // Author: // Natalia Portillo <claunia@claunia.com> // // Copyright (c) 2017-2018 Copyright © Claunia.com // // 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.namespace libexeinfo.Geos using System; namespace libexeinfo { public partial class Geos { [Flags] enum Attributes : ushort { GA_PROCESS = 0x8000, GA_LIBRARY = 0x4000, GA_DRIVER = 0x2000, GA_KEEP_FILE_OPEN = 0x1000, GA_SYSTEM = 0x0800, GA_MULTI_LAUNCHABLE = 0x0400, GA_APPLICATION = 0x0200, GA_DRIVER_INITIALIZED = 0x0100, GA_LIBRARY_INITIALIZED = 0x0080, GA_GEODE_INITIALIZED = 0x0040, GA_USES_COPROC = 0x0020, GA_REQUIRES_COPROC = 0x0010, GA_HAS_GENERAL_CONSUMER_MODE = 0x0008, GA_ENTRY_POINTS_IN_C = 0x0004 } enum FileType2 : ushort { /// <summary> /// The file is not a GEOS file. /// </summary> GFT_NOT_GEOS_FILE = 0, /// <summary> /// The file is executable. /// </summary> GFT_EXECUTABLE = 1, /// <summary> /// The file is a VM file. /// </summary> GFT_VM = 2, /// <summary> /// The file is a GEOS byte file. /// </summary> GFT_DATA = 3, /// <summary> /// The file is a GEOS directory. /// </summary> GFT_DIRECTORY = 4, /// <summary> /// The file is a symbolic link. /// </summary> GFT_LINK = 5 } enum ApplicationType : ushort { Application = 1, Library = 2, Driver = 3 } enum FileType : ushort { /// <summary> /// The file is executable. /// </summary> GFT_EXECUTABLE = 0, /// <summary> /// The file is a VM file. /// </summary> GFT_VM = 1 } // These are defined in GEOS SDK but itself says they stopped using numerical IDs and should use ASCII ones. enum ManufacturerId : ushort { GeoWorks = 0, App = 1, Palm = 2, Wizard = 3, CreativeLabs = 4, DosLauncher = 5, AmericaOnline = 6, Intuit = 7, Sdk = 8, Agd = 9, Generic = 10, Tbd = 11, Socket = 12 } [Flags] enum SegmentFlags : ushort { /// <summary> /// The block will not move from its place in the global heap until it is freed. /// </summary> HF_FIXED = 0x80, /// <summary> /// The block may be locked by threads belonging to geodes other than the block's owner. /// </summary> HF_SHARABLE = 0x40, /// <summary> /// The block may be discarded when unlocked. /// </summary> HF_DISCARDABLE = 0x20, /// <summary> /// The block may be swapped to extended/expanded memory or to the disk swap space when it is unlocked. /// </summary> HF_SWAPABLE = 0x10, /// <summary> /// The block contains a local memory heap. /// </summary> HF_LMEM = 0x08, /// <summary> /// The memory manager turns this bit on when it discards a block. /// </summary> HF_DISCARDED = 0x02, /// <summary> /// The memory manager turns this bit on when it swaps a block to extended/expanded memory or to the disk swap space. /// </summary> HF_SWAPPED = 0x01, HF_STATIC = HF_DISCARDABLE | HF_SWAPABLE, HF_DYNAMIC = HF_SWAPABLE, /// <summary> /// The memory manager should initialize the block to null bytes. /// </summary> HAF_ZERO_INIT = 0x8000, /// <summary> /// The memory manager should lock the block after allocating it. /// </summary> HAF_LOCK = 0x4000, /// <summary> /// The memory manager should not return errors. If it cannot allocate block, GEOS will tell the user that there is no /// memory available and crash. /// </summary> HAF_NO_ERR = 0x2000, /// <summary> /// If both <see cref="HAF_UI" /> and <see cref="HAF_OBJECT_RESOURCE" /> are set, this block will be run by the /// application's UI thread. /// </summary> HAF_UI = 0x1000, /// <summary> /// The block's data will not be modified. /// </summary> HAF_READ_ONLY = 0x0800, /// <summary> /// This block will be an object block. /// </summary> HAF_OBJECT_RESOURCE = 0x0400, /// <summary> /// This block contains executable code. /// </summary> HAF_CODE = 0x0200, /// <summary> /// If the block contains code, the code may be run by a less privileged entity. If the block contains data, the data /// may be accessed or altered by a less privileged entity. /// </summary> HAF_CONFORMING = 0x0100 } } }
37.256684
134
0.498206
[ "MIT" ]
claunia/libexeinfo
libexeinfo/Geos/Enums.cs
6,970
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: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Martijn.HouseInsight.EntityFramework")] [assembly: AssemblyTrademark("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("820966c0-ce3a-4303-a2ae-82424936f0c0")]
42.3
84
0.786052
[ "MIT" ]
Martijn-Sharp/House-Insight
src/Martijn.HouseInsight.EntityFramework/Properties/AssemblyInfo.cs
848
C#
using IdentityWithDapper.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; namespace IdentityWithDapper.Controllers { public class HomeController : Controller { private readonly ILogger<HomeController> _logger; public HomeController(ILogger<HomeController> logger) { _logger = logger; } public IActionResult Index() { return View(); } public IActionResult Privacy() { return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } }
24.605263
112
0.645989
[ "MIT" ]
renebentes/1977
IdentityWithDapper/Controllers/HomeController.cs
937
C#
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using AmazonPay.CommonRequests; using Common.Logging; namespace AmazonPay { public class Signature { //pass only the required accesskey,secret key private Configuration clientConfig = null; // Final URL to where the API parameters POST done,based off the config["region"] and respective mwsServiceUrls private string mwsServiceUrl = null; private string mwsEndpointUrl = string.Empty; private string mwsEndpointPath = string.Empty; // UserAgent to track the request and usage in the Logs private string userAgent = string.Empty; private string parametersAsString = string.Empty; private string serviceVersion = string.Empty; /// <summary> /// Common Looger Property /// </summary> public ILog Logger { private get; set; } public Signature(Configuration configuration, string serviceVersion) { this.clientConfig = configuration; this.serviceVersion = serviceVersion; } /// <summary> /// /// </summary> /// <param name="parameters"></param> /// <param name="timeStamp"></param> /// <param name="mwsDevoUrl"></param> /// <returns></returns> public string CalculateSignatureAndReturnParametersAsString(IDictionary<String, String> parameters, string timeStamp = "", string mwsDevoUrl = "") { parameters.Add("AWSAccessKeyId", this.clientConfig.GetAccessKey()); if (string.IsNullOrEmpty(timeStamp)) { parameters.Add("Timestamp", GetFormattedTimestamp()); } else { parameters.Add("Timestamp", timeStamp); } parameters.Add("Version", serviceVersion); parameters.Add("SignatureVersion", "2"); this.CreateServiceUrl(mwsDevoUrl); parameters.Add("Signature", SignParameters(parameters, this.clientConfig.GetSecretKey())); return GetParametersAsString(parameters); } /// <summary> /// Computes RFC 2104-compliant HMAC signature for request parameters /// Implements AWS Signature,as per following spec: /// /// If Signature Version is 0,it signs concatenated Action and Timestamp /// /// If Signature Version is 1,it performs the following: /// /// Sorts all parameters (including SignatureVersion and excluding Signature, /// the value of which is being created),ignoring case. /// /// Iterate over the sorted list and append the parameter name (in original case) /// and then its value. It will not URL-encode the parameter values before /// constructing this string. There are no separators. /// /// If Signature Version is 2,string to sign is based on following: /// /// 1. The HTTP Request Method followed by an ASCII newline (%0A) /// 2. The HTTP Host header in the form of lowercase host,followed by an ASCII newline. /// 3. The URL encoded HTTP absolute path component of the URI /// (up to but not including the query string parameters); /// if this is empty use a forward "/". This parameter is followed by an ASCII newline. /// 4. The concatenation of all query string components (names and values) /// as UTF-8 characters which are URL encoded as per RFC 3986 /// (hex characters MUST be uppercase),sorted using lexicographic byte ordering. /// Parameter names are separated from their values by the "=" character /// (ASCII character 61),even if the value is empty. /// Pairs of parameter and values are separated by the "&" character (ASCII code 38). /// </summary> /// <param name="parameters"></param> /// <param name="key"></param> /// <returns>signature string</returns> private String SignParameters(IDictionary<String, String> parameters, String key) { String signatureVersion = parameters["SignatureVersion"]; KeyedHashAlgorithm algorithm = new HMACSHA1(); String stringToSign = null; if ("2".Equals(signatureVersion)) { String signatureMethod = "HmacSHA256"; algorithm = KeyedHashAlgorithm.Create(signatureMethod.ToUpper()); parameters.Add("SignatureMethod", signatureMethod); stringToSign = CalculateStringToSignV2(parameters); } else { throw new InvalidDataException("Invalid Signature Version specified"); } return Sign(stringToSign, key, algorithm); } /// <summary> /// compute the string signature as per the V2 specifications /// </summary> /// <param name="parameters"></param> /// <returns></returns> private String CalculateStringToSignV2(IDictionary<String, String> parameters) { StringBuilder data = new StringBuilder(); IDictionary<String, String> sorted = new SortedDictionary<String, String>(parameters, StringComparer.Ordinal); data.Append("POST"); data.Append("\n"); data.Append(mwsEndpointUrl); data.Append("\n"); data.Append(mwsEndpointPath); data.Append("\n"); foreach (KeyValuePair<String, String> pair in sorted) { if (pair.Value != null) { data.Append(UrlEncode(pair.Key, false)); data.Append("="); data.Append(UrlEncode(pair.Value, false)); data.Append("&"); } } String result = data.ToString().Remove(data.Length - 1); LogMessage(result, SanitizeData.DataType.Request); return result; } private String UrlEncode(String data, bool path) { StringBuilder encoded = new StringBuilder(); String unreservedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~" + (path ? "/" : ""); foreach (char symbol in Encoding.UTF8.GetBytes(data)) { if (unreservedChars.IndexOf(symbol) != -1) { encoded.Append(symbol); } else { encoded.Append("%" + String.Format("{0:X2}", (int)symbol)); } } return encoded.ToString(); } /// <summary> /// Computes RFC 2104-compliant HMAC signature. /// </summary> /// <param name="data"></param> /// <param name="key"></param> /// <param name="algorithm"></param> /// <returns>string signature</returns> private String Sign(String data, String key, KeyedHashAlgorithm algorithm) { Encoding encoding = new UTF8Encoding(); algorithm.Key = encoding.GetBytes(key); return Convert.ToBase64String(algorithm.ComputeHash( encoding.GetBytes(data.ToCharArray()))); } /// <summary> /// Formats date as ISO 8601 timestamp /// </summary> /// <returns>DateTime object</returns> private String GetFormattedTimestamp() { return DateTime.UtcNow.ToString("yyyy-MM-dd\\THH:mm:ss.fff\\Z", CultureInfo.InvariantCulture); } /// <summary> /// Create MWS service URL and the Endpoint path /// </summary> /// <param name="mwsTestUrl"></param> private void CreateServiceUrl(string mwsTestUrl) { string region = ""; string mode = ""; mode = Convert.ToBoolean(this.clientConfig.GetSandbox()) ? "OffAmazonPayments_Sandbox" : "OffAmazonPayments"; if (!string.IsNullOrEmpty(this.clientConfig.GetRegion())) { region = this.clientConfig.GetRegion(); if (Regions.regionMappings.ContainsKey(region)) { // Set the Endpoint for the internal development else get the value from the if (mwsTestUrl != null && mwsTestUrl.Trim() != "") { this.mwsServiceUrl = mwsTestUrl; mwsEndpointPath = ""; } else { mwsEndpointUrl = Regions.mwsServiceUrls[Regions.regionMappings[region]]; mwsServiceUrl = "https://" + mwsEndpointUrl + "/" + mode + "/" + serviceVersion; mwsEndpointPath = "/" + mode + "/" + serviceVersion; } } else { throw new InvalidDataException(region + " is not a valid region"); } } else { throw new NullReferenceException("region is a required parameter and is not set"); } } /// <summary> /// /// </summary> /// <param name="additionalNameValuePairs"></param> public void SetUserAgentHeader(params string[] additionalNameValuePairs) { StringBuilder sb = new StringBuilder(); sb.Append(Constants.SDKName + "/" + Constants.SDKClientVersion); sb.Append(" ( "); if (!String.IsNullOrEmpty(this.clientConfig.GetApplicationName()) && !String.IsNullOrEmpty(this.clientConfig.GetApplicationVersion())) { sb.Append(QuoteApplicationName(this.clientConfig.GetApplicationName())); sb.Append("/"); sb.Append(QuoteApplicationVersion(this.clientConfig.GetApplicationVersion())); sb.Append("; "); } else if (!String.IsNullOrEmpty(this.clientConfig.GetApplicationName())) { sb.Append(QuoteApplicationName(this.clientConfig.GetApplicationName())); sb.Append("; "); } else if (!String.IsNullOrEmpty(this.clientConfig.GetApplicationVersion())) { sb.Append(QuoteApplicationVersion(this.clientConfig.GetApplicationVersion())); sb.Append("; "); } int i = 0; while (i < additionalNameValuePairs.Length) { string input = additionalNameValuePairs[i]; sb.Append(QuoteAttributeValue(input)); sb.Append("; "); i++; } sb.Append(")"); userAgent = sb.ToString(); } /// <summary> /// Convert Dictionary of parameters to Url encoded query string /// </summary> /// <param name="parameters"></param> /// <returns>string</returns> private string GetParametersAsString(IDictionary<String, String> parameters) { StringBuilder data = new StringBuilder(); foreach (String key in (IEnumerable<String>)parameters.Keys) { String input = parameters[key]; if (input != null) { data.Append(key); data.Append("="); data.Append(UrlEncode(input, false)); data.Append("&"); } } String result = data.ToString(); return result.Remove(result.Length - 1); } /// <summary> /// Replace all whitespace characters by a single space /// </summary> /// <param name="s"></param> /// <returns>string s</returns> private static string Clean(string s) { // matched character sequences are passed to a MatchEvaluator // delegate. The returned string from the delegate replaces // the matched sequence. return Regex.Replace(s, @" {2,}|\s", delegate(Match m) { return " "; }); } /// <summary> /// Collapse whitespace,and escape the following characters are escaped /// </summary> /// <param name="s"></param> /// <returns>string s</returns> private static string QuoteApplicationName(string s) { return Clean(s).Replace(@"\", @"\\").Replace("@/", @"\/"); } /// <summary> /// Collapse whitespace,and escape the following characters are escaped /// </summary> /// <param name="s"></param> /// <returns>string s</returns> private static string QuoteApplicationVersion(string s) { return Clean(s).Replace(@"\", @"\\").Replace(@"(", @"\("); } /// <summary> /// Collapse whitespace,and escape the following characters are escaped /// </summary> /// <param name="s"></param> /// <returns>string s</returns> private static string QuoteAttributeName(string s) { return Clean(s).Replace(@"\", @"\\").Replace(@"=", @"\="); } /// <summary> /// Collapse whitespace,and escape the following characters are escaped /// </summary> /// <param name="s"></param> /// <returns>string s</returns> private static string QuoteAttributeValue(string s) { return Clean(s).Replace(@"\", @"\\").Replace(@";", @"\;").Replace(@")", @"\)"); } public string GetMwsServiceUrl() { return this.mwsServiceUrl; } public string GetMwsEndpointUrl() { return this.mwsEndpointUrl; } public string GetMwsEndpointPath() { return this.mwsEndpointPath; } public string GetUserAgent() { return this.userAgent; } public string GetParametersAsString() { return this.parametersAsString; } /// <summary> /// Helper method to log data within Signature /// </summary> /// <param name="message">Data to be sanitized</param> /// <param name="type">Type of data</param> private void LogMessage(string message, SanitizeData.DataType type) { if (this.Logger != null && this.Logger.IsDebugEnabled) { this.Logger.Debug(SanitizeData.SanitizeGivenData(message, type)); } } } }
36.806373
154
0.542652
[ "Apache-2.0" ]
4SELLERS/amazon-pay-sdk-csharp
AmazonPay/Signature.cs
15,019
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace GoGreenV3.Attributes { public class AccessDeniedAuthorizeAttribute : AuthorizeAttribute { public override void OnAuthorization(AuthorizationContext filterContext) { base.OnAuthorization(filterContext); if (!filterContext.HttpContext.User.Identity.IsAuthenticated) { filterContext.Result = new RedirectResult("~/Account/Logon"); return; } if (filterContext.Result is HttpUnauthorizedResult) { filterContext.Result = new RedirectResult("~/Account/Denied"); } } } }
28.846154
80
0.629333
[ "MIT" ]
Jessi810/GoGreenV3
GoGreenV3/Attributes/AccessDeniedAuthorizeAttribute.cs
752
C#
namespace RabbitMQManager { public class Constants { public const string RabbitMQConfigPropertyName = "rabbitMQConfig"; } }
18.125
74
0.696552
[ "MIT" ]
DittmannAxel/iotedge-industrial-service-bus
src/iotedge/modules/RabbitMQManager/Constants.cs
147
C#
// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using ICSharpCode.Decompiler.TypeSystem.Implementation; namespace ICSharpCode.Decompiler.TypeSystem { /// <summary> /// Base class for the visitor pattern on <see cref="IType"/>. /// </summary> public abstract class TypeVisitor { public virtual IType VisitTypeDefinition(ITypeDefinition type) { return type.VisitChildren(this); } public virtual IType VisitTypeParameter(ITypeParameter type) { return type.VisitChildren(this); } public virtual IType VisitParameterizedType(ParameterizedType type) { return type.VisitChildren(this); } public virtual IType VisitArrayType(ArrayType type) { return type.VisitChildren(this); } public virtual IType VisitPointerType(PointerType type) { return type.VisitChildren(this); } public virtual IType VisitByReferenceType(ByReferenceType type) { return type.VisitChildren(this); } public virtual IType VisitTupleType(TupleType type) { return type.VisitChildren(this); } public virtual IType VisitOtherType(IType type) { return type.VisitChildren(this); } public virtual IType VisitModReq(ModifiedType type) { return type.VisitChildren(this); } public virtual IType VisitModOpt(ModifiedType type) { return type.VisitChildren(this); } public virtual IType VisitNullabilityAnnotatedType(NullabilityAnnotatedType type) { return type.VisitChildren(this); } } }
30.282353
93
0.753302
[ "MIT" ]
164306530/ILSpy
ICSharpCode.Decompiler/TypeSystem/TypeVisitor.cs
2,576
C#
namespace Treats.Models { public class TreatFlavor { public int TreatFlavorId { get; set; } public int FlavorId { get; set; } public int TreatId { get; set; } public Flavor Flavor { get; set; } public Treat Treat { get; set; } } }
26.090909
46
0.56446
[ "Unlicense" ]
MagpieMortician/Treats.Solution
Models/TreatFlavor.cs
287
C#
namespace Birthday.Telegram.Bot.Domain.AggregationModels; /// <summary> /// Repository for manage chat members /// </summary> public interface IChatMemberRepository { /// <summary> /// Create new Chat member in store /// </summary> /// <param name="value">Model for create new chat member</param> /// <param name="cancellationToken">Instance of Cancellation token</param> /// <returns>Identifier of new chat row</returns> Task<long> CreateAsync(ChatMember value, CancellationToken cancellationToken); /// <summary> /// Update chat member information /// </summary> /// <param name="value">Chat member model for update</param> /// <param name="cancellationToken">Instance of Cancellation token</param> Task UpdateAsync(ChatMember value, CancellationToken cancellationToken); /// <summary> /// Delete chat member row by chat info /// </summary> /// <param name="value">Chat member row for delete</param> /// <param name="cancellationToken">Instance of Cancellation token</param> Task DeleteAsync(ChatMember value, CancellationToken cancellationToken); /// <summary> /// Delete chat member row by chat id /// </summary> /// <param name="chatMemberId">Chat member id</param> /// <param name="cancellationToken">Instance of Cancellation token</param> Task DeleteAsync(long chatMemberId, CancellationToken cancellationToken); /// <summary> /// Get member info by chat member id /// </summary> /// <param name="chatMemberId">Chat member id for search</param> /// <param name="cancellationToken">Instance of Cancellation token</param> /// <returns>Information about chat member</returns> Task<ChatMember?> GetByChatMemberIdAsync(long chatMemberId, CancellationToken cancellationToken); /// <summary> /// Get members info by chat member id /// </summary> /// <param name="chatMembersIds">Chat members ids for search</param> /// <param name="cancellationToken">Instance of Cancellation token</param> /// <returns>Information about chat members</returns> Task<List<ChatMember>> GetByChatMembersIdsAsync(ICollection<long> chatMembersIds, CancellationToken cancellationToken); }
43.018868
124
0.685088
[ "MIT" ]
kokos-coding/birthday-telegram-bot
src/Birthday.Telegram.Bot.Domain/AggregationModels/IChatMemberRepository.cs
2,280
C#
//----------------------------------------------------------------------- // <copyright file="Player.cs" company="Akka.NET Project"> // Copyright (C) 2009-2019 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2019 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Immutable; using System.Linq; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; using Akka.Actor; using Akka.Actor.Internal; using Akka.Annotations; using Akka.Configuration; using Akka.Event; using Akka.Pattern; using Akka.Remote.Transport; using Akka.Util; using Akka.Util.Internal; using DotNetty.Transport.Channels; namespace Akka.Remote.TestKit { /// <summary> /// The Player is the client component of the /// test conductor extension. It registers with /// the conductor's controller /// in order to participate in barriers and enable network failure injection /// </summary> partial class TestConductor //Player trait in JVM version { IActorRef _client; public IActorRef Client { get { if(_client == null) throw new IllegalStateException("TestConductor client not yet started"); if(_system.WhenTerminated.IsCompleted) throw new IllegalStateException("TestConductor unavailable because system is terminated; you need to StartNewSystem() before this point"); return _client; } } /// <summary> /// Connect to the conductor on the given port (the host is taken from setting /// `akka.testconductor.host`). The connection is made asynchronously, but you /// should await completion of the returned Future because that implies that /// all expected participants of this test have successfully connected (i.e. /// this is a first barrier in itself). The number of expected participants is /// set in <see cref="TestConductor"/>`.startController()`. /// </summary> public Task<Done> StartClient(RoleName name, IPEndPoint controllerAddr) { if(_client != null) throw new IllegalStateException("TestConductorClient already started"); _client = _system.ActorOf(Props.Create(() => new ClientFSM(name, controllerAddr)), "TestConductorClient"); //TODO: IRequiresMessageQueue var a = _system.ActorOf(Props.Create<WaitForClientFSMToConnect>()); return a.Ask<Done>(_client); } private class WaitForClientFSMToConnect : UntypedActor { IActorRef _waiting; protected override void OnReceive(object message) { var fsm = message as IActorRef; if (fsm != null) { _waiting = Sender; fsm.Tell(new FSMBase.SubscribeTransitionCallBack(Self)); return; } var transition = message as FSMBase.Transition<ClientFSM.State>; if (transition != null) { if (transition.From == ClientFSM.State.Connecting && transition.To == ClientFSM.State.AwaitDone) return; if (transition.From == ClientFSM.State.AwaitDone && transition.To == ClientFSM.State.Connected) { _waiting.Tell(Done.Instance); Context.Stop(Self); return; } _waiting.Tell(new Exception("unexpected transition: " + transition)); Context.Stop(Self); } var currentState = message as FSMBase.CurrentState<ClientFSM.State>; if (currentState != null) { if (currentState.State == ClientFSM.State.Connected) { _waiting.Tell(Done.Instance); Context.Stop(Self); return; } } } } /// <summary> /// Enter the named barriers, one after the other, in the order given. Will /// throw an exception in case of timeouts or other errors. /// </summary> public void Enter(string name) { Enter(Settings.BarrierTimeout, ImmutableList.Create(name)); } /// <summary> /// Enter the named barriers, one after the other, in the order given. Will /// throw an exception in case of timeouts or other errors. /// </summary> public void Enter(TimeSpan timeout, ImmutableList<string> names) { _system.Log.Debug("entering barriers {0}", names.Aggregate((a, b) => "(" + a + "," + b + ")")); var stop = Deadline.Now + timeout; foreach (var name in names) { var barrierTimeout = stop.TimeLeft; if (barrierTimeout.Ticks < 0) { _client.Tell(new ToServer<FailBarrier>(new FailBarrier(name))); throw new TimeoutException("Server timed out while waiting for barrier " + name); } try { var askTimeout = barrierTimeout + Settings.QueryTimeout; // Need to force barrier to wait here, so we can pass along a "fail barrier" message in the event // of a failed operation var result = _client.Ask(new ToServer<EnterBarrier>(new EnterBarrier(name, barrierTimeout)), askTimeout).Result; } catch (AggregateException) { _client.Tell(new ToServer<FailBarrier>(new FailBarrier(name))); throw new TimeoutException("Client timed out while waiting for barrier " + name); } catch (OperationCanceledException) { _system.Log.Debug("OperationCanceledException was thrown instead of AggregateException"); } _system.Log.Debug("passed barrier {0}", name); } } public Task<Address> GetAddressFor(RoleName name) { return _client.Ask<Address>(new ToServer<GetAddress>(new GetAddress(name)), Settings.QueryTimeout); } } /// <summary> /// This is the controlling entity on the player /// side: in a first step it registers itself with a symbolic name and its remote /// address at the <see cref="Controller"/>, then waits for the /// `Done` message which signals that all other expected test participants have /// done the same. After that, it will pass barrier requests to and from the /// coordinator and react to the Conductors’s /// requests for failure injection. /// /// Note that you can't perform requests concurrently, e.g. enter barrier /// from one thread and ask for node address from another thread. /// /// INTERNAL API. /// </summary> [InternalApi] class ClientFSM : FSM<ClientFSM.State, ClientFSM.Data>, ILoggingFSM //TODO: RequireMessageQueue { public enum State { Connecting, AwaitDone, Connected, Failed } internal class Data { readonly IChannel _channel; public IChannel Channel { get { return _channel; } } readonly (string, IActorRef)? _runningOp; public (string, IActorRef)? RunningOp => _runningOp; public Data(IChannel channel, (string, IActorRef)? runningOp) { _channel = channel; _runningOp = runningOp; } /// <inheritdoc/> protected bool Equals(Data other) { return Equals(_channel, other._channel) && Equals(_runningOp, other._runningOp); } /// <inheritdoc/> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((Data) obj); } /// <inheritdoc/> public override int GetHashCode() { unchecked { return ((_channel != null ? _channel.GetHashCode() : 0) * 397) ^ (_runningOp != null ? _runningOp.GetHashCode() : 0); } } /// <summary> /// Compares two specified <see cref="Data"/> for equality. /// </summary> /// <param name="left">The first <see cref="Data"/> used for comparison</param> /// <param name="right">The second <see cref="Data"/> used for comparison</param> /// <returns><c>true</c> if both <see cref="Data"/> are equal; otherwise <c>false</c></returns> public static bool operator ==(Data left, Data right) { return Equals(left, right); } /// <summary> /// Compares two specified <see cref="Data"/> for inequality. /// </summary> /// <param name="left">The first <see cref="Data"/> used for comparison</param> /// <param name="right">The second <see cref="Data"/> used for comparison</param> /// <returns><c>true</c> if both <see cref="Data"/> are not equal; otherwise <c>false</c></returns> public static bool operator !=(Data left, Data right) { return !Equals(left, right); } public Data Copy((string, IActorRef)? runningOp) { return new Data(Channel, runningOp); } } internal class Connected : INoSerializationVerificationNeeded { readonly IChannel _channel; public IChannel Channel{get { return _channel; }} public Connected(IChannel channel) { _channel = channel; } protected bool Equals(Connected other) { return Equals(_channel, other._channel); } /// <inheritdoc/> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((Connected) obj); } /// <inheritdoc/> public override int GetHashCode() { return (_channel != null ? _channel.GetHashCode() : 0); } /// <summary> /// Compares two specified <see cref="Connected"/> for equality. /// </summary> /// <param name="left">The first <see cref="Connected"/> used for comparison</param> /// <param name="right">The second <see cref="Connected"/> used for comparison</param> /// <returns><c>true</c> if both <see cref="Connected"/> are equal; otherwise <c>false</c></returns> public static bool operator ==(Connected left, Connected right) { return Equals(left, right); } /// <summary> /// Compares two specified <see cref="Connected"/> for inequality. /// </summary> /// <param name="left">The first <see cref="Connected"/> used for comparison</param> /// <param name="right">The second <see cref="Connected"/> used for comparison</param> /// <returns><c>true</c> if both <see cref="Connected"/> are not equal; otherwise <c>false</c></returns> public static bool operator !=(Connected left, Connected right) { return !Equals(left, right); } } /// <summary> /// TBD /// </summary> internal class ConnectionFailure : Exception { /// <summary> /// Initializes a new instance of the <see cref="ConnectionFailure"/> class. /// </summary> /// <param name="message">The message that describes the error.</param> public ConnectionFailure(string message) : base(message) { } } internal class Disconnected { private Disconnected() { } private static readonly Disconnected _instance = new Disconnected(); public static Disconnected Instance { get { return _instance; } } } private readonly ILoggingAdapter _log = Context.GetLogger(); readonly TestConductorSettings _settings; readonly PlayerHandler _handler; readonly RoleName _name; public ClientFSM(RoleName name, IPEndPoint controllerAddr) { _settings = TestConductor.Get(Context.System).Settings; _handler = new PlayerHandler(controllerAddr, _settings.ClientReconnects, _settings.ReconnectBackoff, _settings.ClientSocketWorkerPoolSize, Self, Logging.GetLogger(Context.System, "PlayerHandler"), Context.System.Scheduler); _name = name; InitFSM(); } public void InitFSM() { StartWith(State.Connecting, new Data(null, null)); When(State.Connecting, @event => { if (@event.FsmEvent is IClientOp) { return Stay().Replying(new Status.Failure(new IllegalStateException("not connected yet"))); } var connected = @event.FsmEvent as Connected; if (connected != null) { connected.Channel.WriteAndFlushAsync(new Hello(_name.Name, TestConductor.Get(Context.System).Address)); return GoTo(State.AwaitDone).Using(new Data(connected.Channel, null)); } if (@event.FsmEvent is ConnectionFailure) { return GoTo(State.Failed); } if (@event.FsmEvent is StateTimeout) { _log.Error($"Failed to connect to test conductor within {_settings.ConnectTimeout.TotalMilliseconds} ms."); return GoTo(State.Failed); } return null; }, _settings.ConnectTimeout); When(State.AwaitDone, @event => { if (@event.FsmEvent is Done) { _log.Debug("received Done: starting test"); return GoTo(State.Connected); } if (@event.FsmEvent is INetworkOp) { _log.Error("Received {0} instead of Done", @event.FsmEvent); return GoTo(State.Failed); } if (@event.FsmEvent is IServerOp) { return Stay().Replying(new Failure(new IllegalStateException("not connected yet"))); } if (@event.FsmEvent is StateTimeout) { _log.Error("connect timeout to TestConductor"); return GoTo(State.Failed); } return null; }, _settings.BarrierTimeout); When(State.Connected, @event => { if (@event.FsmEvent is Disconnected) { _log.Info("disconnected from TestConductor"); throw new ConnectionFailure("disconnect"); } if(@event.FsmEvent is ToServer<Done> && @event.StateData.Channel != null) { @event.StateData.Channel.WriteAndFlushAsync(Done.Instance); return Stay(); } var toServer = @event.FsmEvent as IToServer; if (toServer != null && @event.StateData.Channel != null && @event.StateData.RunningOp == null) { @event.StateData.Channel.WriteAndFlushAsync(toServer.Msg); string token = null; var enterBarrier = @event.FsmEvent as ToServer<EnterBarrier>; if (enterBarrier != null) token = enterBarrier.Msg.Name; else { var getAddress = @event.FsmEvent as ToServer<GetAddress>; if (getAddress != null) token = getAddress.Msg.Node.Name; } return Stay().Using(@event.StateData.Copy(runningOp: (token, Sender))); } if (toServer != null && @event.StateData.Channel != null && @event.StateData.RunningOp != null) { _log.Error("cannot write {0} while waiting for {1}", toServer.Msg, @event.StateData.RunningOp); return Stay(); } if (@event.FsmEvent is IClientOp && @event.StateData.Channel != null) { var barrierResult = @event.FsmEvent as BarrierResult; if (barrierResult != null) { if (@event.StateData.RunningOp == null) { _log.Warning("did not expect {0}", @event.FsmEvent); } else { object response; if (barrierResult.Name != @event.StateData.RunningOp.Value.Item1) { response = new Failure( new Exception("wrong barrier " + barrierResult + " received while waiting for " + @event.StateData.RunningOp.Value.Item1)); } else if (!barrierResult.Success) { response = new Failure( new Exception("barrier failed:" + @event.StateData.RunningOp.Value.Item1)); } else { response = barrierResult.Name; } @event.StateData.RunningOp.Value.Item2.Tell(response); } return Stay().Using(@event.StateData.Copy(runningOp: null)); } var addressReply = @event.FsmEvent as AddressReply; if (addressReply != null) { if (@event.StateData.RunningOp == null) { _log.Warning("did not expect {0}", @event.FsmEvent); } else { @event.StateData.RunningOp.Value.Item2.Tell(addressReply.Addr); } return Stay().Using(@event.StateData.Copy(runningOp: null)); } var throttleMsg = @event.FsmEvent as ThrottleMsg; if (@event.FsmEvent is ThrottleMsg) { ThrottleMode mode; if (throttleMsg.RateMBit < 0.0f) mode = Unthrottled.Instance; else if (throttleMsg.RateMBit == 0.0f) mode = Blackhole.Instance; else mode = new Transport.TokenBucket(1000, throttleMsg.RateMBit*125000, 0, 0); var cmdTask = TestConductor.Get(Context.System) .Transport.ManagementCommand(new SetThrottle(throttleMsg.Target, throttleMsg.Direction, mode)); var self = Self; cmdTask.ContinueWith(t => { if (t.IsFaulted) throw new ConfigurationException("Throttle was requested from the TestConductor, but no transport " + "adapters available that support throttling. Specify 'testTransport(on=true)' in your MultiNodeConfig"); self.Tell(new ToServer<Done>(Done.Instance)); }); return Stay(); } if (@event.FsmEvent is DisconnectMsg) return Stay(); //FIXME is this the right EC for the future below? var terminateMsg = @event.FsmEvent as TerminateMsg; if (terminateMsg != null) { _log.Info("Received TerminateMsg - shutting down..."); if (terminateMsg.ShutdownOrExit.IsLeft && terminateMsg.ShutdownOrExit.ToLeft().Value == false) { Context.System.Terminate(); return Stay(); } if (terminateMsg.ShutdownOrExit.IsLeft && terminateMsg.ShutdownOrExit.ToLeft().Value == true) { Context.System.AsInstanceOf<ActorSystemImpl>().Abort(); return Stay(); } if (terminateMsg.ShutdownOrExit.IsRight) { Environment.Exit(terminateMsg.ShutdownOrExit.ToRight().Value); return Stay(); } } if (@event.FsmEvent is Done) return Stay(); //FIXME what should happen? } return null; }); When(State.Failed, @event => { if (@event.FsmEvent is IClientOp) { return Stay().Replying(new Status.Failure(new Exception("cannot do " + @event.FsmEvent + " while failed"))); } if (@event.FsmEvent is INetworkOp) { _log.Warning("ignoring network message {0} while Failed", @event.FsmEvent); return Stay(); } return null; }); OnTermination(e => { _log.Info("Terminating connection to multi-node test controller due to [{0}]", e.Reason); if (e.StateData.Channel != null) { var disconnectTimeout = TimeSpan.FromSeconds(2); //todo: make into setting loaded from HOCON if (!e.StateData.Channel.CloseAsync().Wait(disconnectTimeout)) { _log.Warning("Failed to disconnect from conductor within {0}", disconnectTimeout); } } }); Initialize(); } } /// <summary> /// This handler only forwards messages received from the conductor to the <see cref="ClientFSM"/> /// /// INTERNAL API. /// </summary> internal class PlayerHandler : ChannelHandlerAdapter { readonly IPEndPoint _server; int _reconnects; readonly TimeSpan _backoff; readonly int _poolSize; readonly IActorRef _fsm; readonly ILoggingAdapter _log; readonly IScheduler _scheduler; private bool _loggedDisconnect = false; Deadline _nextAttempt; /// <summary> /// Shareable, since the handler may be added multiple times during reconnect /// </summary> public override bool IsSharable => true; public PlayerHandler(IPEndPoint server, int reconnects, TimeSpan backoff, int poolSize, IActorRef fsm, ILoggingAdapter log, IScheduler scheduler) { _server = server; _reconnects = reconnects; _backoff = backoff; _poolSize = poolSize; _fsm = fsm; _log = log; _scheduler = scheduler; Reconnect(); } private static string FormatConnectionFailure(IChannelHandlerContext context, Exception exception) { var sb = new StringBuilder(); sb.AppendLine($"Connection between [Local: {context.Channel.LocalAddress}] and [Remote: {context.Channel.RemoteAddress}] has failed."); sb.AppendLine($"Cause: {exception}"); sb.AppendLine($"Trace: {exception.StackTrace}"); return sb.ToString(); } public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) { _log.Debug("channel {0} exception {1}", context.Channel, exception); if (exception is ConnectException && _reconnects > 0) { _reconnects -= 1; if (_nextAttempt.IsOverdue) { Reconnect(); } else { _scheduler.Advanced.ScheduleOnce(_nextAttempt.TimeLeft, Reconnect); } return; } _fsm.Tell(new ClientFSM.ConnectionFailure(FormatConnectionFailure(context, exception))); } private void Reconnect() { _log.Debug("Connecting..."); _nextAttempt = Deadline.Now + _backoff; RemoteConnection.CreateConnection(Role.Client, _server, _poolSize, this).ContinueWith(tr => { _log.Debug("Failed to connect.... Retrying again in {0}s. {1} attempts left.", _nextAttempt.TimeLeft,_reconnects); if (_reconnects > 0) { _reconnects -= 1; if (_nextAttempt.IsOverdue) { Reconnect(); } else { _scheduler.Advanced.ScheduleOnce(_nextAttempt.TimeLeft, Reconnect); } } }, TaskContinuationOptions.NotOnRanToCompletion); } public override void ChannelActive(IChannelHandlerContext context) { _log.Debug("connected to {0}", context.Channel.RemoteAddress); _fsm.Tell(new ClientFSM.Connected(context.Channel)); context.FireChannelActive(); } public override void ChannelInactive(IChannelHandlerContext context) { if (!_loggedDisconnect) //added this to help mute log messages { _loggedDisconnect = true; _log.Debug("disconnected from {0}", context.Channel.RemoteAddress); } _fsm.Tell(PoisonPill.Instance); // run outside of the Helios / DotNetty threadpool Task.Factory.StartNew(() => { RemoteConnection.Shutdown(context.Channel); RemoteConnection.ReleaseAll(); // yep, let it run asynchronously. }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); context.FireChannelInactive(); } public override void ChannelRead(IChannelHandlerContext context, object message) { var channel = context.Channel; _log.Debug("message from {0}, {1}", channel.RemoteAddress, message); if (message is INetworkOp) { _fsm.Tell(message); return; } _log.Info("server {0} sent garbage '{1}', disconnecting", channel.RemoteAddress, message); channel.CloseAsync(); } public override Task CloseAsync(IChannelHandlerContext context) { _log.Info("Client: disconnecting {0} from {1}", context.Channel.LocalAddress, context.Channel.RemoteAddress); return base.CloseAsync(context); } } }
41.360632
193
0.507139
[ "Apache-2.0" ]
chrillejb/akka.net
src/core/Akka.Remote.TestKit/Player.cs
28,791
C#
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Kappa.RestServices.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
42.763158
261
0.553282
[ "MIT" ]
Divailo/CodeForBulgaria
KappaServer/Kappa.RestServices/Areas/HelpPage/SampleGeneration/ObjectGenerator.cs
19,500
C#
namespace Microsoft.Examples.V3 { using Microsoft.AspNet.OData; using Microsoft.AspNet.OData.Query; using Microsoft.AspNetCore.Mvc; using Microsoft.Examples.Models; using Microsoft.OData; using System; using System.Collections.Generic; using System.Linq; using static Microsoft.AspNet.OData.Query.AllowedQueryOptions; using static Microsoft.AspNetCore.Http.StatusCodes; /// <summary> /// Represents a RESTful people service. /// </summary> [ApiVersion( "3.0" )] public class PeopleController : ODataController { /// <summary> /// Gets all people. /// </summary> /// <param name="options">The current OData query options.</param> /// <returns>All available people.</returns> /// <response code="200">The successfully retrieved people.</response> [Produces( "application/json" )] [ProducesResponseType( typeof( ODataValue<IEnumerable<Person>> ), Status200OK )] public IActionResult Get( ODataQueryOptions<Person> options ) { var validationSettings = new ODataValidationSettings() { AllowedQueryOptions = Select | OrderBy | Top | Skip | Count, AllowedOrderByProperties = { "firstName", "lastName" }, AllowedArithmeticOperators = AllowedArithmeticOperators.None, AllowedFunctions = AllowedFunctions.None, AllowedLogicalOperators = AllowedLogicalOperators.None, MaxOrderByNodeCount = 2, MaxTop = 100, }; try { options.Validate( validationSettings ); } catch ( ODataException ) { return BadRequest(); } var people = new[] { new Person() { Id = 1, FirstName = "John", LastName = "Doe", Email = "john.doe@somewhere.com", Phone = "555-987-1234", }, new Person() { Id = 2, FirstName = "Bob", LastName = "Smith", Email = "bob.smith@somewhere.com", Phone = "555-654-4321", }, new Person() { Id = 3, FirstName = "Jane", LastName = "Doe", Email = "jane.doe@somewhere.com", Phone = "555-789-3456", } }; return Ok( options.ApplyTo( people.AsQueryable() ) ); } /// <summary> /// Gets a single person. /// </summary> /// <param name="key">The requested person identifier.</param> /// <param name="options">The current OData query options.</param> /// <returns>The requested person.</returns> /// <response code="200">The person was successfully retrieved.</response> /// <response code="404">The person does not exist.</response> [Produces( "application/json" )] [ProducesResponseType( typeof( Person ), Status200OK )] [ProducesResponseType( Status404NotFound )] public IActionResult Get( int key, ODataQueryOptions<Person> options ) { var people = new[] { new Person() { Id = key, FirstName = "John", LastName = "Doe", Email = "john.doe@somewhere.com", Phone = "555-987-1234", } }; var person = options.ApplyTo( people.AsQueryable() ).SingleOrDefault(); if ( person == null ) { return NotFound(); } return Ok( person ); } /// <summary> /// Creates a new person. /// </summary> /// <param name="person">The person to create.</param> /// <returns>The created person.</returns> /// <response code="201">The person was successfully created.</response> /// <response code="400">The person was invalid.</response> [Produces( "application/json" )] [ProducesResponseType( typeof( Person ), Status201Created )] [ProducesResponseType( Status400BadRequest )] public IActionResult Post( [FromBody] Person person ) { if ( !ModelState.IsValid ) { return BadRequest( ModelState ); } person.Id = 42; return Created( person ); } /// <summary> /// Gets the new hires since the specified date. /// </summary> /// <param name="since">The date and time since people were hired.</param> /// <param name="options">The current OData query options.</param> /// <returns>The matching new hires.</returns> /// <response code="200">The people were successfully retrieved.</response> [HttpGet] [Produces( "application/json" )] [ProducesResponseType( typeof( ODataValue<IEnumerable<Person>> ), Status200OK )] public IActionResult NewHires( DateTime since, ODataQueryOptions<Person> options ) => Get( options ); /// <summary> /// Promotes a person. /// </summary> /// <param name="key">The identifier of the person to promote.</param> /// <param name="parameters">The action parameters.</param> /// <returns>None</returns> /// <response code="204">The person was successfully promoted.</response> /// <response code="400">The parameters are invalid.</response> /// <response code="404">The person does not exist.</response> [HttpPost] [ProducesResponseType( Status204NoContent )] [ProducesResponseType( Status400BadRequest )] [ProducesResponseType( Status404NotFound )] public IActionResult Promote( int key, ODataActionParameters parameters ) { if ( !ModelState.IsValid ) { return BadRequest( ModelState ); } var title = (string) parameters["title"]; return NoContent(); } /// <summary> /// Gets the home address of a person. /// </summary> /// <param name="key">The person identifier.</param> /// <returns>The person's home address.</returns> /// <response code="200">The home address was successfully retrieved.</response> /// <response code="404">The person does not exist.</response> [HttpGet] [Produces( "application/json" )] [ProducesResponseType( typeof( Address ), Status200OK )] [ProducesResponseType( Status404NotFound )] public IActionResult GetHomeAddress( int key ) => Ok( new Address() { Id = 42, Street = "123 Some Place", City = "Seattle", State = "WA", ZipCode = "98101" } ); /// <summary> /// Gets the work address of a person. /// </summary> /// <param name="key">The person identifier.</param> /// <returns>The person's work address.</returns> /// <response code="200">The work address was successfully retrieved.</response> /// <response code="404">The person does not exist.</response> [HttpGet] [Produces( "application/json" )] [ProducesResponseType( typeof( Address ), Status200OK )] [ProducesResponseType( Status404NotFound )] public IActionResult GetWorkAddress( int key ) => Ok( new Address() { Id = 42, Street = "1 Microsoft Way", City = "Redmond", State = "WA", ZipCode = "98052" } ); } }
37.291667
109
0.524022
[ "MIT" ]
Bhaskers-Blu-Org2/aspnet-api-versioning
samples/aspnetcore/SwaggerODataSample/V3/PeopleController.cs
8,057
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; namespace SyncKusto.Validation.ErrorMessages { public class NonSpecificOperationError : IOperationError { public NonSpecificOperationError(Exception exception) { Exception = exception; } public Exception Exception { get; } } }
23.294118
61
0.681818
[ "MIT" ]
Bhaskers-Blu-Org2/synckusto
SyncKusto/Validation/ErrorMessages/NonSpecificOperationError.cs
398
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Servicios.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
40.37037
152
0.566972
[ "MIT" ]
marcopuccio/pocs
uai/2016/eeExam/csharp-module/FinalEconomia/Services/Properties/Settings.Designer.cs
1,092
C#
using System; using System.Threading.Tasks; using System.Linq.Expressions; using System.Collections.Generic; namespace Company.Domain { public interface IRolePermissionService { Task<RoleEntity> FindRole(Expression<Func<RoleEntity, bool>> expression); IAsyncEnumerable<RoleEntity> GetRoles(); IAsyncEnumerable<PermissionEntity> GetPermissions(); IAsyncEnumerable<PermissionEntity> GetPermissionsByRole(RoleEntity role); } }
29.3125
81
0.759062
[ "MIT" ]
CristianBonilla/company-news-auth-backend
Company.Domain/Services/IRolePermissionService.cs
469
C#
using HelixToolkit.Wpf; using HX7_Render; using System.Windows; using System.Windows.Data; using System; using System.Collections.Generic; using System.Text; using System.Configuration; using System.Linq; using System.Threading.Tasks; using System.Diagnostics; namespace final_uni_project { public partial class MainWindow : Window { public IDataFeed feed; private SerialInterface _port; public MainWindow() { InitializeComponent(); var port = new HelixViewport3D(); feed = new DataFeed(); var vm = new VisualizeViewModel(feed, port); port.ItemsSource = vm.ViewController.Models; grid.Children.Add(port); } private void MenuItem_Click(object sender, RoutedEventArgs e) { var window = new OptionsWindow(); if (window.ShowDialog() == true) { var nodes = window.GetNodes(); var thisVm = DataContext as VisualizeViewModel; feed.Stop(); this.nodes = nodes; feed.Configure(nodes); feed.Start(); } } private void MenuItem_Click_1(object sender, RoutedEventArgs e) { var window = new ConnectWindow(); window.onPortSelected += Window_onPortSelected; window.Show(); } private void Window_onPortSelected(SerialInterface port) { try { _port = port; _port.NewSerialDataRecieved += DataRecieved; _port.StartListening(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } /// <summary> /// Serial Interface On Data Received variables /// </summary> private string dataBlock = null; private IEnumerable<MenuNode> nodes; private void DataRecieved(object sender, SerialDataEventArgs e) { var graph = new Dictionary<string, List<Tuple<string, double>>>(); try { var dataReceived = Encoding.ASCII.GetString(e.Data); // Forming Data Block if (dataReceived.Length > 0) dataBlock += dataReceived; var sq = dataBlock.Split(new char[] { '\n' }); if (sq.Length > 50) dataBlock = new string(dataBlock.Skip(sq.Length - 50).Take(50).ToArray()); var splittedDataBlock = sq.Reverse().Take(50).Reverse(); // Process Received Data foreach (var line in splittedDataBlock) { // Find measurements if (line.Contains("R") && line.Contains("T") && line.Contains("A") && line.IndexOf("A") != line.Length - 1) { // "R" = _node, "T" = _key, "A" = _value var _node = line.Substring(line.IndexOf("R") + 1, line.IndexOf("T") - line.IndexOf("R") - 2); var _key = line.Substring(line.IndexOf("T") + 1, line.IndexOf("Q") - line.IndexOf("T") - 2); var _value = double.Parse(line.Substring(line.IndexOf("A") + 1, line.Length - line.IndexOf("A") - 1)); // without self connected nodes if (_node != _key) { // If node exist? if (graph.ContainsKey(_node)) { var exists = graph[_node].FirstOrDefault(x => x.Item1 == _node); if (exists != null) { // update connection graph[_node].Remove(exists); graph[_node].Add(new Tuple<string, double>(_key, _value)); } else { // add new connection graph[_node].Add(new Tuple<string, double>(_key, _value)); } } else { // add new node graph.Add(_node, new List<Tuple<string, double>>() { new Tuple<string, double>(_key, _value) }); } } } } var rem = new List<string>(); foreach (var node in graph) if (nodes.Any(x => x.Id == node.Key)) rem.Add(node.Key); feed.Push(graph.Where(v => !rem.Contains(v.Key)).ToDictionary(x => x.Key, y => y.Value), graph); } catch (Exception) { } } private void MenuItem_Click_2(object sender, RoutedEventArgs e) { var window = new ScryptWindow() { _port = _port }; window.Show(); } } }
34.324675
128
0.449489
[ "Apache-2.0" ]
ch-hristov/final_project
final_uni_project/MainWindow.xaml.cs
5,288
C#
using System; using UnityEngine; namespace HT.Framework { /// <summary> /// 步骤操作之间的连线 /// </summary> [Serializable] public sealed class StepWired { [SerializeField] internal int Left = 0; [SerializeField] internal int Right = 0; #if UNITY_EDITOR /// <summary> /// 克隆 /// </summary> /// <returns>新的对象</returns> internal StepWired Clone() { StepWired wired = new StepWired(); wired.Left = Left; wired.Right = Right; return wired; } #endif } }
20.655172
48
0.51586
[ "MIT" ]
LZhenHong/HTFramework
RunTime/StepMaster/Base/StepWired.cs
631
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Darts; namespace ChallengeSimpleDarts { public class Game { private Player _player1; private Player _player2; private Random _random; public Game(string player1Name, string player2Name) { _player1 = new Player(); _player1.Name = player1Name; _player2 = new Player(); _player2.Name = player2Name; _random = new Random(); } public string Play() { while (_player1.Score < 300 && _player2.Score < 300) { playRound(_player1); playRound(_player2); } return displayResults(); } private string displayResults() { string result = String.Format("{0}: {1}<br/>{2}: {3}", _player1.Name, _player1.Score, _player2.Name, _player2.Score); return result += "<br/>Winner: " + (_player1.Score > _player2.Score ? _player1.Name : _player2.Name); } private void playRound(Player player) { for (int i = 0; i < 3; i++) { Dart dart = new Dart(_random); dart.Throw(); Score.ScoreDart(player, dart); } } } }
24.083333
82
0.489273
[ "MIT" ]
AbdulRehmanTekhqs/CS-ASP-045-Solution
Lesson-45-Solution/ChallengeSimpleDarts/Game.cs
1,447
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Server_Game_Frame.Script.proto { public class MsgGetText:MsgBase { public MsgGetText() { proName = "MsgGetText"; } public string text = ""; } }
17.315789
40
0.635258
[ "Apache-2.0" ]
biaomopopo/Unity3D-Server
Server Game Frame/Server Game Frame/Script/proto/MsgGetText.cs
331
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.Device.Gpio; namespace Iot.Device.RotaryEncoder { /// <summary> /// Scaled Quadrature Rotary Controller binding /// </summary> public class ScaledQuadratureEncoder : QuadratureRotaryEncoder { private double _rangeMax; private double _rangeMin; private double _pulseIncrement; /// <summary>The Value property represents current value associated with the RotaryEncoder.</summary> public double Value { get; set; } /// <summary>The AccelerationSlope property along with the AccelerationOffset property represents how the /// increase or decrease in value should grow as the incremental encoder is turned faster.</summary> public float AccelerationSlope { get; set; } = -0.05F; /// <summary>The AccelerationOffset property along with the AccelerationSlope property represents how the /// increase or decrease in value should grow as the incremental encoder is turned faster.</summary> public float AccelerationOffset { get; set; } = 6.0F; /// <summary> /// EventHandler to allow the notification of value changes. /// </summary> public event RotaryEncoderEventHandler? ValueChanged; /// <summary> /// ScaledQuadratureEncoder constructor /// </summary> /// <param name="pinA">Pin A that is connected to the rotary encoder. Sometimes called clk</param> /// <param name="pinB">Pin B that is connected to the rotary encoder. Sometimes called data</param> /// <param name="edges">The pin event types to 'listen' for.</param> /// <param name="pulsesPerRotation">The number of pulses to be received for every full rotation of the encoder.</param> /// <param name="pulseIncrement">The amount that the value increases or decreases on each pulse from the rotary encoder</param> /// <param name="rangeMin">Minimum value permitted. The value is clamped to this.</param> /// <param name="rangeMax">Maximum value permitted. The value is clamped to this.</param> /// <param name="controller">GpioController that hosts Pins A and B.</param> /// <param name="shouldDispose">Dispose the controller if true</param> public ScaledQuadratureEncoder(int pinA, int pinB, PinEventTypes edges, int pulsesPerRotation, double pulseIncrement, double rangeMin, double rangeMax, GpioController? controller = null, bool shouldDispose = true) : base(pinA, pinB, edges, pulsesPerRotation, controller, shouldDispose) { _pulseIncrement = pulseIncrement; _rangeMin = rangeMin; _rangeMax = rangeMax; Value = _rangeMin; } /// <summary> /// ScaledQuadratureEncoder constructor /// </summary> /// <param name="pinA">Pin A that is connected to the rotary encoder. Sometimes called clk</param> /// <param name="pinB">Pin B that is connected to the rotary encoder. Sometimes called data</param> /// <param name="edges">The pin event types to 'listen' for.</param> /// <param name="pulsesPerRotation">The number of pulses to be received for every full rotation of the encoder.</param> /// <param name="pulseIncrement">The amount that the value increases or decreases on each pulse from the rotary encoder</param> /// <param name="rangeMin">Minimum value permitted. The value is clamped to this.</param> /// <param name="rangeMax">Maximum value permitted. The value is clamped to this.</param> public ScaledQuadratureEncoder(int pinA, int pinB, PinEventTypes edges, int pulsesPerRotation, double pulseIncrement, double rangeMin, double rangeMax) : this(pinA, pinB, edges, pulsesPerRotation, pulseIncrement, rangeMin, rangeMax, new GpioController(), true) { } /// <summary> /// ScaledQuadratureEncoder constructor for a 0..100 range with 100 steps /// </summary> /// <param name="pinA">Pin A that is connected to the rotary encoder. Sometimes called clk</param> /// <param name="pinB">Pin B that is connected to the rotary encoder. Sometimes called data</param> /// <param name="edges">The pin event types to 'listen' for.</param> /// <param name="pulsesPerRotation">The number of pulses to be received for every full rotation of the encoder.</param> public ScaledQuadratureEncoder(int pinA, int pinB, PinEventTypes edges, int pulsesPerRotation) : this(pinA, pinB, edges, pulsesPerRotation, new GpioController(), true) { } /// <summary> /// ScaledQuadratureEncoder constructor for a 0..100 range with 100 steps /// </summary> /// <param name="pinA">Pin A that is connected to the rotary encoder. Sometimes called clk</param> /// <param name="pinB">Pin B that is connected to the rotary encoder. Sometimes called data</param> /// <param name="edges">The pin event types to 'listen' for.</param> /// <param name="pulsesPerRotation">The number of pulses to be received for every full rotation of the encoder.</param> /// <param name="controller">GpioController that hosts Pins A and B.</param> /// <param name="shouldDispose">Dispose the controller if true</param> public ScaledQuadratureEncoder(int pinA, int pinB, PinEventTypes edges, int pulsesPerRotation, GpioController? controller = null, bool shouldDispose = true) : base(pinA, pinB, edges, pulsesPerRotation, controller, shouldDispose) { _pulseIncrement = 1; _rangeMin = 0; _rangeMax = 100; Value = _rangeMin; } /// <summary> /// Read the current Value /// </summary> /// <returns>The value associated with the rotary encoder.</returns> public double ReadValue() => Value; /// <summary> /// Calculate the amount of acceleration to be applied to the increment of the encoder. /// </summary> /// <remarks> /// This uses a straight line function output = input * AccelerationSlope + Acceleration offset but can be overridden /// to perform different algorithms. /// </remarks> /// <param name="milliSecondsSinceLastPulse">The amount of time elapsed since the last data pulse from the encoder in milliseconds.</param> /// <returns>A value that can be used to apply acceleration to the rotary encoder.</returns> protected virtual int Acceleration(int milliSecondsSinceLastPulse) { // apply a straight line line function to the pulseWidth to determine the acceleration but clamp the lower value to 1 return Math.Max(1, (int)(milliSecondsSinceLastPulse * AccelerationSlope + AccelerationOffset)); } /// <summary> /// Modify the current value on receipt of a pulse from the encoder. /// </summary> /// <param name="blnUp">When true then the value should be incremented otherwise it should be decremented.</param> /// <param name="milliSecondsSinceLastPulse">The amount of time elapsed since the last data pulse from the encoder in milliseconds.</param> protected override void OnPulse(bool blnUp, int milliSecondsSinceLastPulse) { // call the OnPulse method on the base class to ensure the pulsecount is kept up to date base.OnPulse(blnUp, milliSecondsSinceLastPulse); // calculate how much to change the value by double valueChange = (blnUp ? _pulseIncrement : -_pulseIncrement) * Acceleration(milliSecondsSinceLastPulse); // set the value to the new value clamped by the maximum and minumum of the range. Value = Math.Max(Math.Min(Value + valueChange, _rangeMax), _rangeMin); // fire an event if an event handler has been attached ValueChanged?.Invoke(this, new RotaryEncoderEventArgs(Value)); } } }
56.861111
221
0.666952
[ "MIT" ]
CarlosSardo/nanoFramework.IoT.Device
devices/RotaryEncoder/ScaledQuadratureEncoder.cs
8,188
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.DeviceFarm; using Amazon.DeviceFarm.Model; namespace Amazon.PowerShell.Cmdlets.DF { /// <summary> /// Gets information about artifacts.<br/><br/>This cmdlet automatically pages all available results to the pipeline - parameters related to iteration are only needed if you want to manually control the paginated output. To disable autopagination, use -NoAutoIteration. /// </summary> [Cmdlet("Get", "DFArtifactList")] [OutputType("Amazon.DeviceFarm.Model.Artifact")] [AWSCmdlet("Calls the AWS Device Farm ListArtifacts API operation.", Operation = new[] {"ListArtifacts"}, SelectReturnType = typeof(Amazon.DeviceFarm.Model.ListArtifactsResponse))] [AWSCmdletOutput("Amazon.DeviceFarm.Model.Artifact or Amazon.DeviceFarm.Model.ListArtifactsResponse", "This cmdlet returns a collection of Amazon.DeviceFarm.Model.Artifact objects.", "The service call response (type Amazon.DeviceFarm.Model.ListArtifactsResponse) can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack." )] public partial class GetDFArtifactListCmdlet : AmazonDeviceFarmClientCmdlet, IExecutor { #region Parameter Arn /// <summary> /// <para> /// <para>The Run, Job, Suite, or Test ARN.</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 Arn { get; set; } #endregion #region Parameter Type /// <summary> /// <para> /// <para>The artifacts' type.</para><para>Allowed values include:</para><ul><li><para>FILE: The artifacts are files.</para></li><li><para>LOG: The artifacts are logs.</para></li><li><para>SCREENSHOT: The artifacts are screenshots.</para></li></ul> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] #else [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] [AWSConstantClassSource("Amazon.DeviceFarm.ArtifactCategory")] public Amazon.DeviceFarm.ArtifactCategory Type { get; set; } #endregion #region Parameter NextToken /// <summary> /// <para> /// <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> /// </para> /// <para> /// <br/><b>Note:</b> This parameter is only used if you are manually controlling output pagination of the service API call. /// <br/>In order to manually control output pagination, use '-NextToken $null' for the first call and '-NextToken $AWSHistory.LastServiceResponse.NextToken' for subsequent calls. /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String NextToken { get; set; } #endregion #region Parameter Select /// <summary> /// Use the -Select parameter to control the cmdlet output. The default value is 'Artifacts'. /// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.DeviceFarm.Model.ListArtifactsResponse). /// Specifying the name of a property of type Amazon.DeviceFarm.Model.ListArtifactsResponse 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; } = "Artifacts"; #endregion #region Parameter PassThru /// <summary> /// Changes the cmdlet behavior to return the value passed to the Arn parameter. /// The -PassThru parameter is deprecated, use -Select '^Arn' instead. This parameter will be removed in a future version. /// </summary> [System.Obsolete("The -PassThru parameter is deprecated, use -Select '^Arn' instead. This parameter will be removed in a future version.")] [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter PassThru { get; set; } #endregion #region Parameter NoAutoIteration /// <summary> /// By default the cmdlet will auto-iterate and retrieve all results to the pipeline by performing multiple /// service calls. If set, the cmdlet will retrieve only the next 'page' of results using the value of NextToken /// as the start point. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter NoAutoIteration { get; set; } #endregion protected override void ProcessRecord() { base.ProcessRecord(); 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.DeviceFarm.Model.ListArtifactsResponse, GetDFArtifactListCmdlet>(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.Arn; } #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute context.Arn = this.Arn; #if MODULAR if (this.Arn == null && ParameterWasBound(nameof(this.Arn))) { WriteWarning("You are passing $null as a value for parameter Arn 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.NextToken = this.NextToken; context.Type = this.Type; #if MODULAR if (this.Type == null && ParameterWasBound(nameof(this.Type))) { WriteWarning("You are passing $null as a value for parameter Type 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; #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute var useParameterSelect = this.Select.StartsWith("^") || this.PassThru.IsPresent; #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute // create request and set iteration invariants var request = new Amazon.DeviceFarm.Model.ListArtifactsRequest(); if (cmdletContext.Arn != null) { request.Arn = cmdletContext.Arn; } if (cmdletContext.Type != null) { request.Type = cmdletContext.Type; } // Initialize loop variant and commence piping var _nextToken = cmdletContext.NextToken; var _userControllingPaging = this.NoAutoIteration.IsPresent || ParameterWasBound(nameof(this.NextToken)); var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); do { request.NextToken = _nextToken; CmdletOutput output; try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; if (!useParameterSelect) { pipelineOutput = cmdletContext.Select(response, this); } output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; _nextToken = response.NextToken; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } ProcessOutput(output); } while (!_userControllingPaging && AutoIterationHelpers.HasValue(_nextToken)); if (useParameterSelect) { WriteObject(cmdletContext.Select(null, this)); } return null; } public ExecutorContext CreateContext() { return new CmdletContext(); } #endregion #region AWS Service Operation Call private Amazon.DeviceFarm.Model.ListArtifactsResponse CallAWSServiceOperation(IAmazonDeviceFarm client, Amazon.DeviceFarm.Model.ListArtifactsRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "AWS Device Farm", "ListArtifacts"); try { #if DESKTOP return client.ListArtifacts(request); #elif CORECLR return client.ListArtifactsAsync(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 Arn { get; set; } public System.String NextToken { get; set; } public Amazon.DeviceFarm.ArtifactCategory Type { get; set; } public System.Func<Amazon.DeviceFarm.Model.ListArtifactsResponse, GetDFArtifactListCmdlet, object> Select { get; set; } = (response, cmdlet) => response.Artifacts; } } }
46.676056
275
0.601992
[ "Apache-2.0" ]
5u5hma/aws-tools-for-powershell
modules/AWSPowerShell/Cmdlets/DeviceFarm/Basic/Get-DFArtifactList-Cmdlet.cs
13,256
C#
using System; using System.Collections.Generic; using Newtonsoft.Json; using Qiniu.Auth; using Qiniu.Conf; using Qiniu.RPC; namespace Qiniu.RSF { /// <summary> /// RS Fetch /// </summary> public class RSFClient : QiniuAuthClient { private const int MAX_LIMIT = 1000; //失败重试次数 private const int RETRY_TIME = 3; private string bucketName; /// <summary> /// bucket name /// </summary> public string BucketName { get; private set; } private int limit; /// <summary> /// Fetch返回结果条目数量限制 /// </summary> public int Limit { get { return limit; } set { limit = value > MAX_LIMIT ? MAX_LIMIT : value; } } private bool end = false; private string prefix; /// <summary> /// 文件前缀 /// </summary> /// <value> /// The prefix. /// </value> public string Prefix { get { return prefix; } set { prefix = value; } } private string marker; /// <summary> /// Fetch 定位符. /// </summary> public string Marker { get { return marker; } set { marker = value; } } /// <summary> /// RS Fetch Client /// </summary> /// <param name="bucketName">七牛云存储空间名称</param> public RSFClient (string bucketName) { this.bucketName = bucketName; } /// <summary> /// The origin Fetch interface,we recomment to use Next(). /// </summary> /// <returns> /// Dump /// </returns> /// <param name='bucketName'> /// Bucket name. /// </param> /// <param name='prefix'> /// Prefix. /// </param> /// <param name='markerIn'> /// Marker in. /// </param> /// <param name='limit'> /// Limit. /// </param> public DumpRet ListPrefix(string bucketName, string prefix = "", string markerIn = "", int limit = 0) { string url = Config.RSF_HOST + string.Format ("/list?bucket={0}", bucketName);// + bucketName + if (!string.IsNullOrEmpty (markerIn)) { url += string.Format ("&marker={0}", markerIn); } if (!string.IsNullOrEmpty (prefix)) { url += string.Format ("&prefix={0}", prefix); } if (limit > 0) { url += string.Format ("&limit={0}", limit); } for (int i = 0; i < RETRY_TIME; i++) { CallRet ret = Call (url); if (ret.OK) { return JsonConvert.DeserializeObject<DumpRet> (ret.Response); } else { continue; } } return null; } /// <summary> /// call this func before invoke Next() /// </summary> public void Init () { end = false; this.marker = string.Empty; } /// <summary> /// Next. /// <example> /// <code> /// public static void List (string bucket) ///{ /// RSF.RSFClient rsf = new Qiniu.RSF.RSFClient(bucket); /// rsf.Prefix = "test"; /// rsf.Limit = 100; /// List<DumpItem> items; /// while ((items=rsf.Next())!=null) /// { /// //todo /// } ///}s /// </code> /// </example> /// </summary> public List<DumpItem> Next () { if (end) { return null; } try { DumpRet ret = ListPrefix(this.bucketName, this.prefix, this.marker, this.limit); if (ret.Items.Count == 0) { end = true; return null; } this.marker = ret.Marker; if (this.marker == null) end = true; return ret.Items; } catch (Exception e) { throw e; } } } }
19.608187
109
0.543096
[ "MIT" ]
meloht/yihuiServer
YihuiMgr/Qiniu/RSF/RSFClient.cs
3,417
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; using System.Reflection.Metadata; using Internal.TypeSystem; using Internal.TypeSystem.Ecma; namespace ILCompiler { public enum SpecialMethodKind { Unknown, PInvoke, RuntimeImport }; internal static class MethodExtensions { public static string GetAttributeStringValue(this EcmaMethod This, string nameSpace, string name) { var metadataReader = This.MetadataReader; foreach (var attributeHandle in metadataReader.GetMethodDefinition(This.Handle).GetCustomAttributes()) { EntityHandle attributeType, attributeCtor; if (!metadataReader.GetAttributeTypeAndConstructor(attributeHandle, out attributeType, out attributeCtor)) { continue; } StringHandle namespaceHandle, nameHandle; if (!metadataReader.GetAttributeTypeNamespaceAndName(attributeType, out namespaceHandle, out nameHandle)) { continue; } if (metadataReader.StringComparer.Equals(namespaceHandle, nameSpace) && metadataReader.StringComparer.Equals(nameHandle, name)) { var constructor = This.Module.GetMethod(attributeCtor); if (constructor.Signature.Length != 1 && constructor.Signature.Length != 2) throw new BadImageFormatException(); for (int i = 0; i < constructor.Signature.Length; i++) if (constructor.Signature[i] != This.Context.GetWellKnownType(WellKnownType.String)) throw new BadImageFormatException(); var attributeBlob = metadataReader.GetBlobReader(metadataReader.GetCustomAttribute(attributeHandle).Value); if (attributeBlob.ReadInt16() != 1) throw new BadImageFormatException(); // Skip module name if present if (constructor.Signature.Length == 2) attributeBlob.ReadSerializedString(); return attributeBlob.ReadSerializedString(); } } return null; } public static SpecialMethodKind DetectSpecialMethodKind(this MethodDesc method) { if (method.IsPInvoke) { // Marshalling is never required for pregenerated interop code if (Internal.IL.McgInteropSupport.IsPregeneratedInterop(method)) { return SpecialMethodKind.PInvoke; } if (!Internal.IL.Stubs.PInvokeMarshallingILEmitter.RequiresMarshalling(method)) { return SpecialMethodKind.PInvoke; } } if (method.HasCustomAttribute("System.Runtime", "RuntimeImportAttribute")) { return SpecialMethodKind.RuntimeImport; } return SpecialMethodKind.Unknown; } } }
35.774194
127
0.575293
[ "MIT" ]
ZZHGit/corert
src/ILCompiler.Compiler/src/Compiler/MethodExtensions.cs
3,329
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.txt file in the project root for more information. using System.IO; using System.Text; namespace roslyn.optprof.lib { public static class StreamExtensions { public static string ReadToEnd(this Stream stream) { string result; using (StreamReader reader = new StreamReader(stream, Encoding.UTF8, detectEncodingFromByteOrderMarks: true, bufferSize: 2048, leaveOpen: true)) { result = reader.ReadToEnd(); } return result; } } }
30.217391
156
0.65036
[ "MIT" ]
MiYanni/roslyn-tools
src/OptProf/roslyn.optprof.lib/Vsix/StreamExtensions.cs
697
C#
//=================================================================================== // Microsoft patterns & practices // Composite Application Guidance for Windows Presentation Foundation and Silverlight //=================================================================================== // Copyright (c) Microsoft Corporation. All rights reserved. // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT // LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS FOR A PARTICULAR PURPOSE. //=================================================================================== // The example companies, organizations, products, domain names, // e-mail addresses, logos, people, places, and events depicted // herein are fictitious. No association with any real company, // organization, product, domain name, email address, logo, person, // places, or events is intended or should be inferred. //=================================================================================== using System; using System.Collections.Generic; using System.Linq; namespace Microsoft.Practices.Prism.Events { internal class WeakDelegatesManager { private readonly List<DelegateReference> listeners = new List<DelegateReference>(); public void AddListener(Delegate listener) { this.listeners.Add(new DelegateReference(listener, false)); } public void RemoveListener(Delegate listener) { this.listeners.RemoveAll(reference => { //Remove the listener, and prune collected listeners Delegate target = reference.Target; return listener.Equals(target) || target == null; }); } public void Raise(params object[] args) { this.listeners.RemoveAll(listener => listener.Target == null); foreach (Delegate handler in this.listeners.ToList().Select(listener => listener.Target).Where(listener => listener != null)) { handler.DynamicInvoke(args); } } } }
40.962264
137
0.563795
[ "Apache-2.0" ]
andrewdbond/CompositeWPF
sourceCode/compositewpf/V4/PrismLibrary/Desktop/Prism/Events/WeakDelegatesManager.cs
2,171
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using Foundation; using osu.Framework.iOS; using osu.Game.Tests; namespace osu.Game.Rulesets.Mania.Tests.iOS { [Register("AppDelegate")] public class AppDelegate : GameAppDelegate { protected override Framework.Game CreateGame() { return new OsuTestBrowser(); } } }
25.684211
80
0.653689
[ "MIT" ]
oldschool-otaku/osu
osu.Game.Rulesets.Mania.Tests.iOS/AppDelegate.cs
472
C#
 namespace CLDR.LocaleDataMarkupLanguage { public enum listPatternPartDraft { approved, contributed, provisional, unconfirmed, } }
11.916667
39
0.755245
[ "MIT", "Unlicense" ]
lirmont/Font-Tool
Font Tool/Support Classes/CLDR/ldml/parts/listPatternPartDraft.cs
145
C#
namespace Stump.DofusProtocol.Messages { using System; using System.Linq; using System.Text; using Stump.DofusProtocol.Types; using Stump.Core.IO; [Serializable] public class GameRolePlayDelayedObjectUseMessage : GameRolePlayDelayedActionMessage { public new const uint Id = 6425; public override uint MessageId { get { return Id; } } public ushort ObjectGID { get; set; } public GameRolePlayDelayedObjectUseMessage(double delayedCharacterId, sbyte delayTypeId, double delayEndTime, ushort objectGID) { this.DelayedCharacterId = delayedCharacterId; this.DelayTypeId = delayTypeId; this.DelayEndTime = delayEndTime; this.ObjectGID = objectGID; } public GameRolePlayDelayedObjectUseMessage() { } public override void Serialize(IDataWriter writer) { base.Serialize(writer); writer.WriteVarUShort(ObjectGID); } public override void Deserialize(IDataReader reader) { base.Deserialize(reader); ObjectGID = reader.ReadVarUShort(); } } }
27.930233
135
0.630308
[ "Apache-2.0" ]
Daymortel/Stump
src/Stump.DofusProtocol/Messages/Messages/Game/Context/Roleplay/Delay/GameRolePlayDelayedObjectUseMessage.cs
1,203
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Aurora.Profiles.LeagueOfLegends.GSI.Nodes { public class SlotNode : Node { public bool HasItem => Item != ItemID.None; public bool CanUse; public bool Consumable; public int Count; public string Name = ""; public ItemID Item = ItemID.None; public SlotNode() { } public SlotNode(_Item item) { CanUse = item.canUse; Consumable = item.consumable; Count = item.count; Name = item.displayName; if (Enum.IsDefined(typeof(ItemID), item.itemID)) Item = (ItemID)item.itemID; else Item = ItemID.None; } } public enum ItemID { Unknown = -1, None = 0, BootsofSpeed = 1001, FaerieCharm = 1004, RejuvenationBead = 1006, GiantsBelt = 1011, CloakofAgility = 1018, BlastingWand = 1026, SapphireCrystal = 1027, RubyCrystal = 1028, ClothArmor = 1029, ChainVest = 1031, NullMagicMantle = 1033, LongSword = 1036, Pickaxe = 1037, BFSword = 1038, HuntersTalisman = 1039, HuntersMachete = 1041, Dagger = 1042, RecurveBow = 1043, AmplifyingTome = 1052, VampiricScepter = 1053, DoransShield = 1054, DoransBlade = 1055, DoransRing = 1056, NegatronCloak = 1057, NeedlesslyLargeRod = 1058, DarkSeal = 1082, Cull = 1083, //Enchantment:Warrior = 1400, //Enchantment:Cinderhulk = 1401, //Enchantment:RunicEchoes = 1402, //Enchantment:Warrior = 1412, //Enchantment:Cinderhulk = 1413, //Enchantment:RunicEchoes = 1414, //Enchantment:Bloodrazor = 1416, //Enchantment:Bloodrazor = 1419, HealthPotion = 2003, ShowdownHealthPotion = 2006, TotalBiscuitofRejuvenation = 2009, TotalBiscuitofEverlastingWill = 2010, KircheisShard = 2015, RefillablePotion = 2031, CorruptingPotion = 2033, OraclesExtract = 2047, GuardiansHorn = 2051, PoroSnax = 2052, DietPoroSnax = 2054, ControlWard = 2055, ShurelyasReverie = 2065, ElixirofIron = 2138, ElixirofSorcery = 2139, ElixirofWrath = 2140, MinionDematerializer = 2403, CommencingStopwatch = 2419, Stopwatch = 2420, BrokenStopwatch = 2421, SlightlyMagicalBoots = 2422, //Stopwatch = 2423, //BrokenStopwatch = 2424, AbyssalMask = 3001, ArchangelsStaff = 3003, Manamune = 3004, BerserkersGreaves = 3006, //ArchangelsStaff(QuickCharge) = 3007, //Manamune(QuickCharge) = 3008, BootsofSwiftness = 3009, CatalystofAeons = 3010, SorcerersShoes = 3020, FrozenMallet = 3022, GlacialShroud = 3024, IcebornGauntlet = 3025, GuardianAngel = 3026, RodofAges = 3027, ChaliceofHarmony = 3028, //RodofAges(QuickCharge) = 3029, HextechGLP800 = 3030, InfinityEdge = 3031, MortalReminder = 3033, LastWhisper = 3035, LordDominiksRegards = 3036, SeraphsEmbrace = 3040, MejaisSoulstealer = 3041, Muramana = 3042, //Muramana = 3043, Phage = 3044, PhantomDancer = 3046, NinjaTabi = 3047, //SeraphsEmbrace = 3048, ZekesConvergence = 3050, JaurimsFist = 3052, SteraksGage = 3053, Sheen = 3057, SpiritVisage = 3065, Kindlegem = 3067, SunfireCape = 3068, TearoftheGoddess = 3070, BlackCleaver = 3071, Bloodthirster = 3072, //TearoftheGoddess(QuickCharge) = 3073, RavenousHydra = 3074, Thornmail = 3075, BrambleVest = 3076, Tiamat = 3077, TrinityForce = 3078, WardensMail = 3082, WarmogsArmor = 3083, OverlordsBloodmail = 3084, RunaansHurricane = 3085, Zeal = 3086, StatikkShiv = 3087, RabadonsDeathcap = 3089, WitsEnd = 3091, RapidFirecannon = 3094, Stormrazor = 3095, LichBane = 3100, Stinger = 3101, BansheesVeil = 3102, AegisoftheLegion = 3105, Redemption = 3107, FiendishCodex = 3108, KnightsVow = 3109, FrozenHeart = 3110, MercurysTreads = 3111, GuardiansOrb = 3112, AetherWisp = 3113, ForbiddenIdol = 3114, NashorsTooth = 3115, RylaisCrystalScepter = 3116, BootsofMobility = 3117, ExecutionersCalling = 3123, GuinsoosRageblade = 3124, CaulfieldsWarhammer = 3133, SerratedDirk = 3134, VoidStaff = 3135, HauntingGuise = 3136, DervishBlade = 3137, MercurialScimitar = 3139, QuicksilverSash = 3140, YoumuusGhostblade = 3142, RanduinsOmen = 3143, BilgewaterCutlass = 3144, HextechRevolver = 3145, HextechGunblade = 3146, DuskbladeofDraktharr = 3147, LiandrysTorment = 3151, HextechProtobelt01 = 3152, BladeoftheRuinedKing = 3153, Hexdrinker = 3155, MawofMalmortius = 3156, ZhonyasHourglass = 3157, IonianBootsofLucidity = 3158, SpearofShojin = 3161, Morellonomicon = 3165, AthenesUnholyGrail = 3174, HeadofKhaZix = 3175, UmbralGlaive = 3179, SanguineBlade = 3181, GuardiansHammer = 3184, LocketoftheIronSolari = 3190, SeekersArmguard = 3191, GargoyleStoneplate = 3193, AdaptiveHelm = 3194, HexCoremk1 = 3196, HexCoremk2 = 3197, PerfectHexCore = 3198, PrototypeHexCore = 3200, SpectresCowl = 3211, MikaelsCrucible = 3222, LudensEcho = 3285, WardingTotemTrinket = 3340, ArcaneSweeper = 3348, GreaterStealthTotemTrinket = 3361, GreaterVisionTotemTrinket = 3362, FarsightAlteration = 3363, OracleLens = 3364, MoltenEdge = 3371, ForgefireCape = 3373, RabadonsDeathcrown = 3374, InfernalMask = 3379, ObsidianCleaver = 3380, Salvation = 3382, CircletoftheIronSolari = 3383, TrinityFusion = 3384, ZhonyasParadox = 3386, FrozenFist = 3387, YoumuusWraithblade = 3388, MightoftheRuinedKing = 3389, LudensPulse = 3390, YourCut = 3400, //HeadofKhaZix = 3410, //HeadofKhaZix = 3416, //HeadofKhaZix = 3422, //HeadofKhaZix = 3455, ArdentCenser = 3504, EssenceReaver = 3508, EyeoftheHerald = 3513, //EyeoftheHerald = 3514, GhostPoro = 3520, BlackSpear = 3599, // BlackSpear = 3600, //Enchantment:Warrior = 3671, //Enchantment:Cinderhulk = 3672, //Enchantment:RunicEchoes = 3673, //Enchantment:Bloodrazor = 3675, FrostedSnax = 3680, SuperSpicySnax = 3681, EspressoSnax = 3682, RainbowSnaxPartyPack = 3683, DawnbringerSnax = 3684, NightbringerSnax = 3685, CosmicShackle = 3690, SingularityLantern = 3691, DarkMatterScythe = 3692, GravityBoots = 3693, CloakofStars = 3694, DarkStarSigil = 3695, StalkersBlade = 3706, SkirmishersSabre = 3715, DeadMansPlate = 3742, TitanicHydra = 3748, BamisCinder = 3751, RighteousGlory = 3800, CrystallineBracer = 3801, LostChapter = 3802, DeathsDance = 3812, EdgeofNight = 3814, SpellthiefsEdge = 3850, Frostfang = 3851, ShardofTrueIce = 3853, SteelShoulderguards = 3854, RunesteelSpaulders = 3855, PauldronsofWhiterock = 3857, RelicShield = 3858, TargonsBuckler = 3859, BulwarkoftheMountain = 3860, SpectralSickle = 3862, HarrowingCrescent = 3863, BlackMistScythe = 3864, FireatWill = 3901, DeathsDaughter = 3902, RaiseMorale = 3903, TwinShadows = 3905, Spellbinder = 3907, OblivionOrb = 3916 } }
30.72028
61
0.552584
[ "MIT" ]
ADoesGit/Aurora
Project-Aurora/Project-Aurora/Profiles/LeagueOfLegends/GSI/Nodes/ItemNode.cs
8,503
C#
namespace CarDealer.Data.Models { using System.Collections.Generic; using System.ComponentModel.DataAnnotations; public class Supplier { public int Id { get; set; } [Required] [MaxLength(100)] public string Name { get; set; } public bool IsImporter { get; set; } public List<Part> Parts { get; set; } } }
18.95
48
0.596306
[ "MIT" ]
tanyogeorgiev/ASP.NET-Core-MVC
CarDealer/CarDealer.Web/CarDealer.Data/Models/Supplier.cs
381
C#
/* * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) * See https://github.com/openiddict/openiddict-core for more information concerning * the license and the contributors participating to this project. */ using System; using System.Collections.Concurrent; using System.Text; using JetBrains.Annotations; using Microsoft.Extensions.DependencyInjection; using OpenIddict.Abstractions; using OpenIddict.Core; using OpenIddict.Extensions; using OpenIddict.NHibernate.Models; namespace OpenIddict.NHibernate { /// <summary> /// Exposes a method allowing to resolve an authorization store. /// </summary> public class OpenIddictAuthorizationStoreResolver : IOpenIddictAuthorizationStoreResolver { private static readonly ConcurrentDictionary<Type, Type> _cache = new ConcurrentDictionary<Type, Type>(); private readonly IServiceProvider _provider; public OpenIddictAuthorizationStoreResolver([NotNull] IServiceProvider provider) => _provider = provider; /// <summary> /// Returns an authorization store compatible with the specified authorization type or throws an /// <see cref="InvalidOperationException"/> if no store can be built using the specified type. /// </summary> /// <typeparam name="TAuthorization">The type of the Authorization entity.</typeparam> /// <returns>An <see cref="IOpenIddictAuthorizationStore{TAuthorization}"/>.</returns> public IOpenIddictAuthorizationStore<TAuthorization> Get<TAuthorization>() where TAuthorization : class { var store = _provider.GetService<IOpenIddictAuthorizationStore<TAuthorization>>(); if (store != null) { return store; } var type = _cache.GetOrAdd(typeof(TAuthorization), key => { var root = OpenIddictHelpers.FindGenericBaseType(key, typeof(OpenIddictAuthorization<,,>)); if (root == null) { throw new InvalidOperationException(new StringBuilder() .AppendLine("The specified authorization type is not compatible with the NHibernate stores.") .Append("When enabling the NHibernate stores, make sure you use the built-in ") .Append("'OpenIddictAuthorization' entity (from the 'OpenIddict.NHibernate.Models' package) ") .Append("or a custom entity that inherits from the generic 'OpenIddictAuthorization' entity.") .ToString()); } return typeof(OpenIddictAuthorizationStore<,,,>).MakeGenericType( /* TAuthorization: */ key, /* TApplication: */ root.GenericTypeArguments[1], /* TToken: */ root.GenericTypeArguments[2], /* TKey: */ root.GenericTypeArguments[0]); }); return (IOpenIddictAuthorizationStore<TAuthorization>) _provider.GetRequiredService(type); } } }
45.720588
118
0.650048
[ "Apache-2.0" ]
RlolN/openiddict-core
src/OpenIddict.NHibernate/Resolvers/OpenIddictAuthorizationStoreResolver.cs
3,111
C#
using System; using System.Reflection; namespace Reflection { public class MyType { public MyType() { Console.WriteLine(); Console.WriteLine(value: "MyType instantiated!"); } } class Test { public static void Call() { AppDomain currentDomain = AppDomain.CurrentDomain; // This call will fail to create an instance of MyType since the // assembly resolver is not set InstantiateMyTypeFail(domain: currentDomain); currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler); // This call will succeed in creating an instance of MyType since the // assembly resolver is now set. InstantiateMyTypeFail(domain: currentDomain); // This call will succeed in creating an instance of MyType since the // assembly name is valid. InstantiateMyTypeSucceed(domain: currentDomain); } private static void InstantiateMyTypeFail(AppDomain domain) { // Calling InstantiateMyType will always fail since the assembly info // given to CreateInstance is invalid. try { // You must supply a valid fully qualified assembly name here. domain.CreateInstance(assemblyName: "Assembly text name, Version, Culture, PublicKeyToken", typeName: "MyType"); } catch (Exception e) { Console.WriteLine(); Console.WriteLine(value: e.Message); } } private static void InstantiateMyTypeSucceed(AppDomain domain) { try { string asmname = Assembly.GetCallingAssembly().FullName; domain.CreateInstance(assemblyName: asmname, typeName: "MyType"); } catch (Exception e) { Console.WriteLine(); Console.WriteLine(value: e.Message); } } private static Assembly MyResolveEventHandler(object sender, ResolveEventArgs args) { Console.WriteLine(value: "Resolving..."); return typeof(MyType).Assembly; } } }
31.575342
128
0.573102
[ "MIT" ]
EnD1ZeR/otus_serializer
Reflection/AssemblyResolver.cs
2,307
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 Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars { /// <summary> /// Helper service that takes the raw text of a string token and produces the individual /// characters that raw string token represents (i.e. with escapes collapsed). The difference /// between this and the result from token.ValueText is that for each collapsed character /// returned the original span of text in the original token can be found. i.e. if you had the /// following in C#: /// /// "G\u006fo" /// /// Then you'd get back: /// /// 'G' -> [0, 1) 'o' -> [1, 7) 'o' -> [7, 1) /// /// This allows for embedded language processing that can refer back to the users' original code /// instead of the escaped value we're processing. /// </summary> internal interface IVirtualCharService : ILanguageService { /// <summary> /// Takes in a string token and return the <see cref="VirtualChar"/>s corresponding to each /// char of the tokens <see cref="SyntaxToken.ValueText"/>. In other words, for each char /// in ValueText there will be a VirtualChar in the resultant array. Each VirtualChar will /// specify what char the language considers them to represent, as well as the span of text /// in the original <see cref="SourceText"/> that the language created that char from. /// /// For most chars this will be a single character span. i.e. 'c' -> 'c'. However, for /// escapes this may be a multi character span. i.e. 'c' -> '\u0063' /// /// If the token is not a string literal token, or the string literal has any diagnostics on /// it, then <see langword="default"/> will be returned. Additionally, because a /// VirtualChar can only represent a single char, while some escape sequences represent /// multiple chars, <see langword="default"/> will also be returned in those cases. All /// these cases could be relaxed in the future. But they greatly simplify the /// implementation. /// /// If this function succeeds, certain invariants will hold. First, each character in the /// sequence of characters in <paramref name="token"/>.ValueText will become a single /// VirtualChar in the result array with a matching <see cref="VirtualChar.Char"/> property. /// Similarly, each VirtualChar's <see cref="VirtualChar.Span"/> will abut each other, and /// the union of all of them will cover the span of the token's <see /// cref="SyntaxToken.Text"/> /// *not* including the start and quotes. /// /// In essence the VirtualChar array acts as the information explaining how the <see /// cref="SyntaxToken.Text"/> of the token between the quotes maps to each character in the /// token's <see cref="SyntaxToken.ValueText"/>. /// </summary> VirtualCharSequence TryConvertToVirtualChars(SyntaxToken token); } }
54.916667
100
0.659484
[ "Apache-2.0" ]
Sliptory/roslyn
src/Workspaces/Core/Portable/EmbeddedLanguages/VirtualChars/IVirtualCharService.cs
3,297
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 kinesisanalyticsv2-2018-05-23.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.KinesisAnalyticsV2.Model { /// <summary> /// Container for the parameters to the DescribeApplicationSnapshot operation. /// Returns information about a snapshot of application state data. /// </summary> public partial class DescribeApplicationSnapshotRequest : AmazonKinesisAnalyticsV2Request { private string _applicationName; private string _snapshotName; /// <summary> /// Gets and sets the property ApplicationName. /// <para> /// The name of an existing application. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=128)] public string ApplicationName { get { return this._applicationName; } set { this._applicationName = value; } } // Check to see if ApplicationName property is set internal bool IsSetApplicationName() { return this._applicationName != null; } /// <summary> /// Gets and sets the property SnapshotName. /// <para> /// The identifier of an application snapshot. You can retrieve this value using . /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=128)] public string SnapshotName { get { return this._snapshotName; } set { this._snapshotName = value; } } // Check to see if SnapshotName property is set internal bool IsSetSnapshotName() { return this._snapshotName != null; } } }
31.846154
116
0.644122
[ "Apache-2.0" ]
FoxBearBear/aws-sdk-net
sdk/src/Services/KinesisAnalyticsV2/Generated/Model/DescribeApplicationSnapshotRequest.cs
2,484
C#
/*<FILE_LICENSE> * NFX (.NET Framework Extension) Unistack Library * Copyright 2003-2018 Agnicore Inc. portions ITAdapter Corp. Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. </FILE_LICENSE>*/ using System; using System.Linq; using NFX.Web; using NFX.Graphics; using NFX.DataAccess.CRUD; using NFX.Serialization.JSON; namespace NFX.Wave.MVC { /// <summary> /// Decorates entities that get returned by MVC actions and can get executed to generate some result action (command pattern) /// </summary> public interface IActionResult { void Execute(Controller controller, WorkContext work); } /// <summary> /// Represents MVC action result that downloads a local file /// </summary> public struct FileDownload : IActionResult { public FileDownload(string fileName, bool isAttachment = false, int bufferSize = Response.DEFAULT_DOWNLOAD_BUFFER_SIZE) { LocalFileName = fileName; IsAttachment = isAttachment; BufferSize = bufferSize; } /// <summary> /// Local file name /// </summary> public readonly string LocalFileName; /// <summary> /// Download buffer size. Leave unchanged in most cases /// </summary> public readonly int BufferSize; /// <summary> /// When true, asks user to save as attachment /// </summary> public readonly bool IsAttachment; public void Execute(Controller controller, WorkContext work) { work.Response.WriteFile(LocalFileName, BufferSize, IsAttachment); } } /// <summary> /// Represents MVC action result that redirects user to some URL /// </summary> public struct Redirect : IActionResult { public Redirect(string url, WebConsts.RedirectCode code = WebConsts.RedirectCode.Found_302) { URL = url; Code = code; } /// <summary> /// Where to redirect user /// </summary> public readonly string URL; /// <summary> /// Redirect code /// </summary> public readonly WebConsts.RedirectCode Code; public void Execute(Controller controller, WorkContext work) { work.Response.Redirect(URL, Code); } } /// <summary> /// Represents MVC action result that returns/downloads an image /// </summary> public struct Picture : IActionResult, IDisposable { public Picture(Image image, ImageFormat format, string attachmentFileName = null) { m_Image = image; m_Format = format; m_AttachmentFileName = attachmentFileName; } private Image m_Image; private ImageFormat m_Format; public string m_AttachmentFileName; /// <summary> /// Picture image /// </summary> public Image Image{ get{ return m_Image;} } /// <summary> /// Download buffer size. Leave unchanged in most cases /// </summary> public ImageFormat Format{ get{ return m_Format;} } /// <summary> /// When non-null asks user to download picture as a named attached file /// </summary> public string AttachmentFileName{ get{ return m_AttachmentFileName;} } public void Execute(Controller controller, WorkContext work) { if (m_Image==null) return; if (m_AttachmentFileName.IsNotNullOrWhiteSpace()) work.Response.Headers.Add(WebConsts.HTTP_HDR_CONTENT_DISPOSITION, "attachment; filename={0}".Args(m_AttachmentFileName)); work.Response.ContentType = Format.WebContentType; m_Image.Save(work.Response.GetDirectOutputStreamForWriting(), Format); } public void Dispose() { DisposableObject.DisposeAndNull(ref m_Image); } } /// <summary> /// Represents MVC action result that returns ROW as JSON object for WV.RecordModel(...) ctor init /// </summary> public struct ClientRecord : IActionResult { public ClientRecord(Row row, Exception validationError, string recID = null, string target = null, string isoLang = null, Client.ModelFieldValueListLookupFunc valueListLookupFunc = null) { RecID = recID; Row = row; ValidationError = validationError; Target = target; IsoLang = isoLang; ValueListLookupFunc = valueListLookupFunc; } public ClientRecord(Row row, Exception validationError, Func<Schema.FieldDef, JSONDataMap> simpleValueListLookupFunc, string recID = null, string target = null, string isoLang = null) { RecID = recID; Row = row; ValidationError = validationError; Target = target; IsoLang = isoLang; if (simpleValueListLookupFunc!=null) ValueListLookupFunc = (_sender, _row, _def, _target, _iso) => simpleValueListLookupFunc(_def); else ValueListLookupFunc = null; } public readonly string RecID; public readonly Row Row; public readonly Exception ValidationError; public readonly string Target; public readonly string IsoLang; public readonly Client.ModelFieldValueListLookupFunc ValueListLookupFunc; public void Execute(Controller controller, WorkContext work) { var gen = (work.Portal!=null) ? work.Portal.RecordModelGenerator : Client.RecordModelGenerator.DefaultInstance; work.Response.WriteJSON( gen.RowToRecordInitJSON(Row, ValidationError, RecID, Target, IsoLang, ValueListLookupFunc) ); } } /// <summary> /// Represents MVC action result that returns JSON object with options. /// If JSON options are not needed then just return CLR object directly from controller action without this wrapper /// </summary> public struct JSONResult : IActionResult { public JSONResult(object data, JSONWritingOptions options) { Data = data; Options = options; } public JSONResult(Exception error, JSONWritingOptions options) { var http = WebConsts.STATUS_500; var descr = WebConsts.STATUS_500_DESCRIPTION; if (error != null) { descr = error.Message; var httpError = error as HTTPStatusException; if (httpError != null) { http = httpError.StatusCode; descr = httpError.StatusDescription; } } Data = new { OK = false, http = http, descr = descr }; Options = options; } public readonly object Data; public readonly JSONWritingOptions Options; public void Execute(Controller controller, WorkContext work) { work.Response.WriteJSON( Data, Options); } } /// <summary> /// Returns HTTP 404 - not found. /// This should be used in place of returning exceptions where needed as it is faster /// </summary> public struct Http404NotFound : IActionResult { public Http404NotFound(string descr = null) { Description = descr; } public readonly string Description; public void Execute(Controller controller, WorkContext work) { var txt = WebConsts.STATUS_404_DESCRIPTION; if (Description.IsNotNullOrWhiteSpace()) txt += (": " + Description); work.Response.StatusCode = WebConsts.STATUS_404; work.Response.StatusDescription = txt; if (work.RequestedJSON) work.Response.WriteJSON( new {OK = false, http = WebConsts.STATUS_404, descr = txt}); else work.Response.Write(txt); } } /// <summary> /// Returns HTTP 403 - forbidden /// This should be used in place of returning exceptions where needed as it is faster /// </summary> public struct Http403Forbidden : IActionResult { public Http403Forbidden(string descr = null) { Description = descr; } public readonly string Description; public void Execute(Controller controller, WorkContext work) { var txt = WebConsts.STATUS_403_DESCRIPTION; if (Description.IsNotNullOrWhiteSpace()) txt += (": " + Description); work.Response.StatusCode = WebConsts.STATUS_403; work.Response.StatusDescription = txt; if (work.RequestedJSON) work.Response.WriteJSON( new {OK = false, http = WebConsts.STATUS_403, descr = txt}); else work.Response.Write(txt); } } }
28.810458
131
0.657668
[ "Apache-2.0" ]
agnicore/nfx
src/NFX.Wave/MVC/ActionResult.cs
8,816
C#
/****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * * * Use subject to the terms of the Apache License 2.0 available at * * http://www.apache.org/licenses/LICENSE-2.0, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using UnityEngine; namespace Leap.Unity.AR { //[ExecuteInEditMode] public class IPDAdjuster : MonoBehaviour { [Header("IPD")] public float ipd = 0.064f; public float heightOffset = 0f; public float depthOffset = 0f; public float pitchOffset = 0f; public float yawOffset = 0f; //public float screenForwardOffset; private float? _lastKnownIPD = null; private float? _lastKnownHeight = null; private float? _lastKnownDepth = null; private float? _lastKnownPitch = null; private float? _lastKnownYaw = null; //private float? _lastKnownScreenForwardOffset = null; //private Vector3 startingScreenLeft, startingScreenRight; //private int lastSentCommand = 0; [Header("Left Eye")] [Tooltip("When IPD is adjusted, this transform's local X coordinate is moved.")] public Transform leftEyeIPDTransform; [Tooltip("When IPD is adjusted, CalculateDistortionMesh() is called.")] public ARRaytracer leftEyeARRaytracer; //[Tooltip("Adjusts the screen depth for the varifocal headset.")] //public Transform leftScreenTransform; [Header("Right Eye")] [Tooltip("When IPD is adjusted, this transform's local X coordinate is moved.")] public Transform rightEyeIPDTransform; [Tooltip("When IPD is adjusted, CalculateDistortionMesh() is called.")] public ARRaytracer rightEyeARRaytracer; //[Tooltip("Adjusts the screen depth for the varifocal headset.")] //public Transform rightScreenTransform; [Header("Leap Hand Tracker")] [Tooltip("Adjusts the pitch and yaw of the hand tracker.")] public Transform leapTransform; [Header("Hotkeys")] [Tooltip("Nudges the IPD wider by 1 millimeter.")] public KeyCode adjustWiderKey = KeyCode.Plus; [Tooltip("Nudges the IPD narrower by 1 millimeter.")] public KeyCode adjustNarrowerKey = KeyCode.Minus; [Tooltip("Nudges the Eye Height higher by 1 millimeter.")] public KeyCode adjustHigherKey = KeyCode.UpArrow; [Tooltip("Nudges the Eye Height lower by 1 millimeter.")] public KeyCode adjustLowerKey = KeyCode.DownArrow; [Tooltip("Nudges the Eye Recession closer by 1 millimeter.")] public KeyCode adjustCloserKey = KeyCode.LeftArrow; [Tooltip("Nudges the Eye Recession farther by 1 millimeter.")] public KeyCode adjustFartherKey = KeyCode.RightArrow; [Tooltip("Nudges the Leap Tracker to point higher by 1 millimeter.")] public KeyCode adjustTrackerHigherKey = KeyCode.Keypad8; [Tooltip("Nudges the Leap Tracker to point lower by 1 millimeter.")] public KeyCode adjustTrackerLowerKey = KeyCode.Keypad2; [Tooltip("Nudges the Leap Tracker to point leftward by 1 millimeter.")] public KeyCode adjustTrackerLeftKey = KeyCode.Keypad4; [Tooltip("Nudges the Leap Tracker to point rightward by 1 millimeter.")] public KeyCode adjustTrackerRightKey = KeyCode.Keypad6; //[Tooltip("Nudges the Screen Recession forward by 1 millimeter.")] //public KeyCode screenForwardKey = KeyCode.Period; //[Tooltip("Nudges the Screen Recession backward by 1 millimeter.")] //public KeyCode screenBackwardKey = KeyCode.Comma; [Header("Debug")] public TextMesh debugText; private bool isConfigured { get { return !(leftEyeIPDTransform == null || leftEyeARRaytracer == null || rightEyeIPDTransform == null || rightEyeARRaytracer == null || leapTransform == null); } } private void Start() { if (isConfigured) { ipd = rightEyeIPDTransform.localPosition.x * 2f; heightOffset = rightEyeIPDTransform.localPosition.y; depthOffset = rightEyeIPDTransform.localPosition.z; pitchOffset = leapTransform.localEulerAngles.x; yawOffset = leapTransform.localEulerAngles.y; //startingScreenLeft = leftScreenTransform.localPosition; //startingScreenRight = rightScreenTransform.localPosition; } } public void resetEyes() { enabled = true; Start(); ipd = 0.064f; heightOffset = -0.011f; depthOffset = -0.005f; RefreshIPD(); } void Update() { if (!isConfigured) return; if (Application.isPlaying) { if (Input.GetKey(adjustWiderKey)) { ipd += 0.004f * Time.deltaTime; } if (Input.GetKey(adjustNarrowerKey)) { ipd -= 0.004f * Time.deltaTime; } if (Input.GetKey(adjustHigherKey)) { heightOffset += 0.05f * Time.deltaTime; } if (Input.GetKey(adjustLowerKey)) { heightOffset -= 0.05f * Time.deltaTime; } //heightOffset += 0.01f * Time.deltaTime * Input.GetAxis("6"); if (Input.GetKey(adjustCloserKey)) { depthOffset += 0.05f * Time.deltaTime; } if (Input.GetKey(adjustFartherKey)) { depthOffset -= 0.05f * Time.deltaTime; } if (Input.GetKey(adjustTrackerHigherKey)){// || Input.GetAxis("joystick button 0")) { pitchOffset -= 20f * Time.deltaTime; } if (Input.GetKey(adjustTrackerLowerKey)) { pitchOffset += 20f * Time.deltaTime; } if (Input.GetKey(adjustTrackerRightKey)) { yawOffset += 20f * Time.deltaTime; } if (Input.GetKey(adjustTrackerLeftKey)) { yawOffset -= 20f * Time.deltaTime; } /*if (Input.GetKey(screenForwardKey)) { screenForwardOffset += 0.01f * Time.deltaTime; } if (Input.GetKey(screenBackwardKey)) { screenForwardOffset -= 0.01f * Time.deltaTime; } screenForwardOffset = Mathf.Clamp(screenForwardOffset, -0.013f, 0f); int currentServoOffset = (int)screenForwardOffset.Remap(0, -0.013f, 0, 25); if (currentServoOffset != lastSentCommand) { string command = currentServoOffset.ToString(); ThreadedVarifocalSerialProcessor processor = FindObjectOfType<ThreadedVarifocalSerialProcessor>(); if(processor != null) processor.SerialCommands.TryEnqueue(command); lastSentCommand = currentServoOffset; }*/ } if (!_lastKnownIPD.HasValue || _lastKnownIPD.Value != ipd || !_lastKnownHeight.HasValue || _lastKnownHeight.Value != heightOffset || !_lastKnownDepth.HasValue || _lastKnownDepth.Value != depthOffset || !_lastKnownPitch.HasValue || _lastKnownPitch.Value != pitchOffset || !_lastKnownYaw.HasValue || _lastKnownYaw.Value != yawOffset) { //|| !_lastKnownScreenForwardOffset.HasValue || _lastKnownScreenForwardOffset.Value != screenForwardOffset) { RefreshIPD(); _lastKnownIPD = ipd; _lastKnownHeight = heightOffset; _lastKnownDepth = depthOffset; _lastKnownPitch = pitchOffset; _lastKnownYaw = yawOffset; if (debugText != null) debugText.text = "IPD: " + (ipd * 1000f).ToString("n2") + "mm\n" + "Height: " + (heightOffset * 1000f).ToString("n2") + "mm\n" + "Depth: " + (depthOffset * 1000f).ToString("n2") + "mm"; } } public void RefreshIPD() { if (!isConfigured) return; Vector3 lPos = leftEyeIPDTransform.localPosition; Vector3 rPos = rightEyeIPDTransform.localPosition; lPos.x = -ipd / 2f; rPos.x = ipd / 2f; lPos.y = heightOffset; rPos.y = heightOffset; lPos.z = depthOffset; rPos.z = depthOffset; leftEyeIPDTransform.localPosition = lPos; rightEyeIPDTransform.localPosition = rPos; leapTransform.localEulerAngles = new Vector3(pitchOffset, yawOffset, 0f); //if (Application.isPlaying) { // leftScreenTransform.localPosition = startingScreenLeft + (leftScreenTransform.localRotation * Vector3.forward) * screenForwardOffset; // rightScreenTransform.localPosition = startingScreenRight + (rightScreenTransform.localRotation * Vector3.forward) * screenForwardOffset; //} OpticalCalibrationManager manager = GetComponent<OpticalCalibrationManager>(); if (manager != null) { manager.currentCalibration.leftEye.eyePosition = lPos; manager.currentCalibration.rightEye.eyePosition = rPos; manager.UpdateCalibrationFromObjects(); } leftEyeARRaytracer.ScheduleCreateDistortionMesh(); rightEyeARRaytracer.ScheduleCreateDistortionMesh(); } } }
41.26009
147
0.627106
[ "MIT" ]
HyperLethalVector/ProjectEsky-UnityIntegration
Assets/Plugins/LeapMotion/North Star/Scripts/IPDAdjuster.cs
9,201
C#
using Android.App; using Android.Widget; using Android.OS; using Android.Content.PM; using Android.Views; namespace TeslaUiSample.Droid { [Activity( MainLauncher = true, ConfigurationChanges = global::Uno.UI.ActivityHelper.AllConfigChanges, WindowSoftInputMode = SoftInput.AdjustPan | SoftInput.StateHidden )] public class MainActivity : Windows.UI.Xaml.ApplicationActivity { } }
20.947368
73
0.776382
[ "MIT" ]
MartinZikmund/uno-tesla-ui-sample
TeslaUiSample/TeslaUiSample.Droid/MainActivity.cs
400
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Text; namespace HappyCoding.WinUISimple.Util { public class PropertyChangedBase : INotifyPropertyChanged { public event PropertyChangedEventHandler? PropertyChanged; //*** Code from project PRISM (https://github.com/PrismLibrary/Prism) /// <summary> /// Checks if a property already matches a desired value. Sets the property and /// notifies listeners only when necessary. /// </summary> /// <typeparam name="T">Type of the property.</typeparam> /// <param name="storage">Reference to a property with both getter and setter.</param> /// <param name="value">Desired value for the property.</param> /// <param name="propertyName">Name of the property used to notify listeners. This /// value is optional and can be provided automatically when invoked from compilers that /// support CallerMemberName.</param> /// <returns>True if the value was changed, false if the existing value matched the /// desired value.</returns> protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = "") { if (EqualityComparer<T>.Default.Equals(storage, value)) return false; storage = value; this.RaisePropertyChanged(propertyName); return true; } //*** Code from project PRISM (https://github.com/PrismLibrary/Prism) /// <summary> /// Checks if a property already matches a desired value. Sets the property and /// notifies listeners only when necessary. /// </summary> /// <typeparam name="T">Type of the property.</typeparam> /// <param name="storage">Reference to a property with both getter and setter.</param> /// <param name="value">Desired value for the property.</param> /// <param name="propertyName">Name of the property used to notify listeners. This /// value is optional and can be provided automatically when invoked from compilers that /// support CallerMemberName.</param> /// <param name="onChanged">Action that is called after the property value has been changed.</param> /// <returns>True if the value was changed, false if the existing value matched the /// desired value.</returns> protected virtual bool SetProperty<T>(ref T storage, T value, Action onChanged, [CallerMemberName] string propertyName = "") { if (EqualityComparer<T>.Default.Equals(storage, value)) return false; storage = value; onChanged?.Invoke(); this.RaisePropertyChanged(propertyName); return true; } public void RaisePropertyChanged([CallerMemberName] string propName = "") { this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName)); } } }
45.552239
132
0.651376
[ "MIT" ]
RolandKoenig/HappyCoding
2021/HappyCoding.WinUISimple/HappyCoding.WinUISimple/HappyCoding.WinUISimple/Util/PropertyChangedBase.cs
3,054
C#
using System.Windows; namespace ReactiveBingViewer { /// <summary> /// App.xaml の相互作用ロジック /// </summary> public partial class App : Application { public static string BingApiAccountKey { get; private set; } public static string VisionApiSubscriptionKey { get; private set; } protected override void OnStartup(StartupEventArgs e) { Reactive.Bindings.UIDispatcherScheduler.Initialize(); base.OnStartup(e); if (e.Args.Length >= 2) { BingApiAccountKey = e.Args[0]; VisionApiSubscriptionKey = e.Args[1]; } else { BingApiAccountKey = ReactiveBingViewer.Properties.Settings.Default.BingApiAccountKey; VisionApiSubscriptionKey = ReactiveBingViewer.Properties.Settings.Default.VisionApiSubscriptionKey; } } } }
30
115
0.598925
[ "MIT" ]
pierre3/ReactiveBingViewer
ReactiveBingViewer/App.xaml.cs
950
C#
namespace LeagueManager.Tryouts.Models { public interface ITryout { } }
12.142857
39
0.670588
[ "MIT" ]
kicker3082/LeagueManager
Business Logic/Entities/LeagueManager.Tryouts.Models/ITryout.cs
87
C#
using System; using KBot.Common.Extension; using KBot.Game.Enum; namespace KBot.Network.Packet.Inventories { public class Ivn : IPacket { public InventoryType InventoryType { get; set; } public InventorySub Item { get; set; } } public class IvnCreator : IPacketCreator { public string Header { get; } = "ivn"; public PacketType PacketType { get; } = PacketType.Received; public IPacket Create(string[] content) { InventoryType type = content[0].ToEnum<InventoryType>(); InventorySub item = null; string[] data = content[1].Split('.'); if (data.Length == 4) { item = new InventorySub { Slot = data[0].ToInt(), ModelId = data[1].ToInt(), Amount = data[2].ToInt(), }; } else if (data.Length == 6) { item = new InventorySub { Slot = data[0].ToInt(), ModelId = data[1].ToInt(), Amount = 1, Rarity = data[2].ToInt(), Upgrade = data[3].ToInt(), Perfection = type == InventoryType.Specialist ? data[4].ToInt() : 0, RuneLevel = type == InventoryType.Equipment ? data[4].ToInt() : 0 }; } if (item == null) { throw new InvalidOperationException("Failed to create item"); } return new Ivn { InventoryType = type, Item = item }; } } }
29.233333
89
0.444128
[ "Apache-2.0" ]
Roxeez/KBot
srcs/KBot.Network/Packet/Inventories/Ivn.cs
1,756
C#
using System; using Xunit; namespace NonFactors.Mvc.Lookup.Tests.Unit { public class LookupColumnTests { [Fact] public void LookupColumn_NullKey_Throws() { Assert.Equal("key", Assert.Throws<ArgumentNullException>(() => new LookupColumn(null!, "Test")).ParamName); } [Fact] public void LookupColumn_Defaults() { LookupColumn actual = new LookupColumn("Test", "Headers"); Assert.Equal("Headers", actual.Header); Assert.Equal("Test", actual.Key); Assert.Empty(actual.CssClass); Assert.False(actual.Hidden); } } }
25.461538
119
0.584592
[ "MIT" ]
aynur-safin/AspNetCore.Lookup
test/Mvc.Lookup.Tests/Unit/LookupColumnTests.cs
664
C#
//----------------------------------------------------------------------- // <copyright file="NetworkIdentityCreated.cs" company="Lost Signal LLC"> // Copyright (c) Lost Signal LLC. All rights reserved. // </copyright> //----------------------------------------------------------------------- #if UNITY_2018_3_OR_NEWER using UnityEngine; namespace Lost.Networking { public class NetworkIdentityCreated : Message { public const short Id = 205; public long NetworkId { get; set; } public long OwnerId { get; set; } public string ResourceName { get; set; } public Vector3 Position { get; set; } public override short GetId() { return Id; } public override void Deserialize(NetworkReader reader) { base.Deserialize(reader); this.NetworkId = reader.ReadInt64(); this.OwnerId = reader.ReadInt64(); this.ResourceName = reader.ReadString(); this.Position = reader.ReadVector3(); } public override void Serialize(NetworkWriter writer) { base.Serialize(writer); writer.Write(this.NetworkId); writer.Write(this.OwnerId); writer.Write(this.ResourceName); writer.Write(this.Position); } } } #endif
27.12
74
0.528024
[ "Unlicense", "MIT" ]
LostSignal/Lost-Library
Lost/Lost.Networking/Runtime/Unity/Messages/NetworkIdentityCreated.cs
1,358
C#
using System; using System.Collections.Generic; using System.Linq; using QuranX.Persistence.Models; namespace QuranX.Web.Views.RootAnalysis { public class VerseViewModel { public readonly int ChapterNumber; public readonly int VerseNumber; public readonly VerseAnalysisWord SelectedWord; public readonly VerseAnalysisWordPart SelectedWordPart; public readonly IReadOnlyList<VerseAnalysisWord> Words; public VerseViewModel( int chapterNumber, int verseNumber, VerseAnalysisWord selectedWord, VerseAnalysisWordPart selectedWordPart, IEnumerable<VerseAnalysisWord> words) { if (words == null) throw new ArgumentNullException(nameof(words)); ChapterNumber = chapterNumber; VerseNumber = verseNumber; SelectedWord = selectedWord; SelectedWordPart = selectedWordPart; Words = words.ToList().AsReadOnly(); } } }
26.181818
57
0.780093
[ "MIT" ]
QuranX/QuranX
src/QuranX.Web/Views/RootAnalysis/VerseViewModel.cs
866
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("2.Salary_Increase")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Release")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("2.Salary_Increase")] [assembly: System.Reflection.AssemblyTitleAttribute("2.Salary_Increase")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
41.791667
80
0.652044
[ "MIT" ]
NeSh74/CSharp-OOP-June-2021
02.Encapsulation/02. CSharp-OOP-Encapsulation-Lab/2.Salary_Increase/obj/Release/netcoreapp3.1/2.Salary_Increase.AssemblyInfo.cs
1,003
C#
// Copyright (c) Peter Vrenken. All rights reserved. See the license on https://github.com/vrenken/EtAlii.Ubigia namespace EtAlii.Ubigia.Api.Functional.Context { internal static class AnnotationPrefix { public const string NodeAdd = "node-add"; public const string NodesAdd = "nodes-add"; public const string NodeLink = "node-link"; public const string NodesLink = "nodes-link"; public const string NodeRemove = "node-remove"; public const string NodesRemove = "nodes-remove"; public const string Node = "node"; public const string Nodes = "nodes"; public const string NodeUnlink = "node-unlink"; public const string NodesUnlink = "nodes-unlink"; public const string ValueSet = "node-set"; public const string ValueClear = "node-clear"; public const string Value = "node"; } }
32.178571
113
0.658158
[ "MIT" ]
vrenken/EtAlii.Ubigia
Source/Api/EtAlii.Ubigia.Api.Functional/Context/0. _Model/AnnotationPrefix.cs
903
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Testing; using Test.Utilities; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.NetCore.Analyzers.Runtime.SerializationRulesDiagnosticAnalyzer, Microsoft.NetCore.CSharp.Analyzers.Runtime.CSharpMarkAllNonSerializableFieldsFixer>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Microsoft.NetCore.Analyzers.Runtime.SerializationRulesDiagnosticAnalyzer, Microsoft.NetCore.VisualBasic.Analyzers.Runtime.BasicMarkAllNonSerializableFieldsFixer>; namespace Microsoft.NetCore.Analyzers.Runtime.UnitTests { public class MarkAllNonSerializableFieldsTests { [Fact] [WorkItem(858655, "DevDiv")] public async Task CA2235WithOnlyPrimitiveFieldsAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; [Serializable] public class CA2235WithOnlyPrimitiveFields { public string s1; internal string s2; private string s3; public int i1; internal int i2; private int i3; public bool b1; internal bool b2; private bool b3; }"); await VerifyVB.VerifyAnalyzerAsync(@" Imports System <Serializable> Public Class CA2235WithOnlyPrimitiveFields Public s1 As String Friend s2 As String Private s3 As String Public i1 As Integer Friend i2 As Integer Private i3 As Integer Public b1 As Boolean Friend b2 As Boolean Private b3 As Boolean End Class"); } [Fact] public async Task CA2235WithConstPrimitiveFieldsAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; [Serializable] public class CA2235WithConstPrimitiveFields { public const int i1 = 42; internal const int i2 = 54; private const int i3 = 96; }"); await VerifyVB.VerifyAnalyzerAsync(@" Imports System <Serializable> Public Class CA2235WithConstPrimitiveFields Public Const i1 As Integer = 42 Friend Const i2 As Integer = 54 Private Const i3 As Integer = 96 End Class"); } [Fact] public async Task CA2235WithPrimitiveGetOnlyPropertiesAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; [Serializable] public class CA2235WithPrimitiveGetOnlyProperties { public int I1 { get; } = 42; internal int I2 { get; } = 54; private int I3 { get; } = 96; }"); await VerifyVB.VerifyAnalyzerAsync(@" Imports System <Serializable> Public Class CA2235WithPrimitiveGetOnlyProperties Public ReadOnly Property I1 As Integer Get Return 42 End Get End Property Friend ReadOnly Property I2 As Integer Get Return 54 End Get End Property Private ReadOnly Property I3 As Integer Get Return 96 End Get End Property ' Using auto-implemented property syntax Public Property AI1 As Integer = 42 Friend Property AI2 As Integer = 54 Private Property AI3 As Integer = 96 End Class"); } [Fact] public async Task CA2235WithSerializableLibraryTypesAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Text.RegularExpressions; [Serializable] public class CA2235WithSerializableLibraryTypes { public Regex R = new Regex(@""\w+""); public Nullable<int> NI = new Nullable<int>(42); public bool? NB = true; public Version V = new Version(1, 1, 12, 2); }"); await VerifyVB.VerifyAnalyzerAsync(@" Imports System Imports System.Text.RegularExpressions <Serializable> Public Class CA2235WithSerializableLibraryTypes Public R As Regex = New Regex(""\w+"") Public NI As Nullable(Of Integer) = new Nullable(Of Integer)(42) Public NB As Boolean? = true Public V As Version = New Version(1, 1, 12, 2) End Class"); } [Fact] [WorkItem(279, "https://github.com/dotnet/roslyn-analyzers/issues/279")] public async Task CA2235WithNonSerializedAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; [Serializable] public class CA2235WithOnlyPrimitiveFields { [NonSerialized] public Action<string> SomeAction; }"); await VerifyVB.VerifyAnalyzerAsync(@" Imports System <Serializable> Public Class CA2235WithOnlyPrimitiveFields <NonSerialized> Public SomeAction As Action(Of String) End Class"); } [Fact] public async Task CA2235WithOnlySerializableFieldsAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; [Serializable] public class SerializableType { } [Serializable] public class CA2235WithOnlySerializableFields { public SerializableType s1; internal SerializableType s2; private SerializableType s3; }"); await VerifyVB.VerifyAnalyzerAsync(@" Imports System <Serializable> Public Class SerializableType End Class <Serializable> Public Class CA2235WithOnlySerializableFields Public s1 As SerializableType Friend s2 As SerializableType Private s3 As SerializableType End Class"); } [Fact] public async Task CA2235WithNonPublicNonSerializableFieldsAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public class NonSerializableType { } [Serializable] public class SerializableType { } [Serializable] public class CA2235WithNonPublicNonSerializableFields { public SerializableType s1; internal NonSerializableType s2; private NonSerializableType s3; }", GetCA2235CSharpResultAt(12, 50, "s2", "CA2235WithNonPublicNonSerializableFields", "NonSerializableType"), GetCA2235CSharpResultAt(13, 49, "s3", "CA2235WithNonPublicNonSerializableFields", "NonSerializableType")); await VerifyVB.VerifyAnalyzerAsync(@" Imports System Public Class NonSerializableType End Class <Serializable> Public Class SerializableType End Class <Serializable> Public Class CA2235WithNonPublicNonSerializableFields Public s1 As SerializableType Friend s2 As NonSerializableType Private s3 As NonSerializableType End Class", GetCA2235BasicResultAt(12, 28, "s2", "CA2235WithNonPublicNonSerializableFields", "NonSerializableType"), GetCA2235BasicResultAt(13, 29, "s3", "CA2235WithNonPublicNonSerializableFields", "NonSerializableType")); } [Fact] public async Task CA2235WithNonPublicNonSerializableFieldsWithScopeAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public class NonSerializableType { } [Serializable] public class SerializableType { } [Serializable] public class CA2235WithNonPublicNonSerializableFields { public SerializableType s1; internal NonSerializableType s2; private NonSerializableType s3; } [Serializable] public class Sample { public SerializableType s1; internal NonSerializableType {|CA2235:s2|}; private NonSerializableType {|CA2235:s3|}; }", GetCA2235CSharpResultAt(12, 50, "s2", "CA2235WithNonPublicNonSerializableFields", "NonSerializableType"), GetCA2235CSharpResultAt(13, 49, "s3", "CA2235WithNonPublicNonSerializableFields", "NonSerializableType")); await VerifyVB.VerifyAnalyzerAsync(@" Imports System Public Class NonSerializableType End Class <Serializable> Public Class SerializableType End Class <Serializable> Public Class CA2235WithNonPublicNonSerializableFields Public s1 As SerializableType Friend s2 As NonSerializableType Private s3 As NonSerializableType End Class <Serializable> Public Class Sample Public s1 As SerializableType Friend {|CA2235:s2|} As NonSerializableType Private {|CA2235:s3|} As NonSerializableType End Class", GetCA2235BasicResultAt(12, 28, "s2", "CA2235WithNonPublicNonSerializableFields", "NonSerializableType"), GetCA2235BasicResultAt(13, 29, "s3", "CA2235WithNonPublicNonSerializableFields", "NonSerializableType")); } [Fact] public async Task CA2235InternalWithNonPublicNonSerializableFieldsAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public class NonSerializableType { } [Serializable] public class SerializableType { } [Serializable] internal class CA2235InternalWithNonPublicNonSerializableFields { public NonSerializableType s1; internal SerializableType s2; private NonSerializableType s3; }", GetCA2235CSharpResultAt(11, 48, "s1", "CA2235InternalWithNonPublicNonSerializableFields", "NonSerializableType"), GetCA2235CSharpResultAt(13, 49, "s3", "CA2235InternalWithNonPublicNonSerializableFields", "NonSerializableType")); await VerifyVB.VerifyAnalyzerAsync(@" Imports System Public Class NonSerializableType End Class <Serializable> Public Class SerializableType End Class <Serializable> Friend Class CA2235InternalWithNonPublicNonSerializableFields Public s1 As NonSerializableType Friend s2 As SerializableType Private s3 As NonSerializableType End Class", GetCA2235BasicResultAt(11, 28, "s1", "CA2235InternalWithNonPublicNonSerializableFields", "NonSerializableType"), GetCA2235BasicResultAt(13, 29, "s3", "CA2235InternalWithNonPublicNonSerializableFields", "NonSerializableType")); } [Fact] public async Task CA2235WithNonSerializableAutoPropertiesAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public class NonSerializableType { } [Serializable] public class SerializableType { } [Serializable] internal class CA2235WithNonSerializableAutoProperties { public SerializableType s1; internal NonSerializableType s2 {get; set; } }", GetCA2235CSharpResultAt(12, 50, "s2", "CA2235WithNonSerializableAutoProperties", "NonSerializableType")); await VerifyVB.VerifyAnalyzerAsync(@" Imports System Public Class NonSerializableType End Class <Serializable> Public Class SerializableType End Class <Serializable> Friend Class CA2235WithNonSerializableAutoProperties Public s1 As SerializableType Friend Property s2 As NonSerializableType End Class", GetCA2235BasicResultAt(12, 37, "s2", "CA2235WithNonSerializableAutoProperties", "NonSerializableType")); } [Fact] public async Task CA2235WithArrayTypeAsync() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetFramework.Net472.Default, TestCode = @" using System; public class NonSerializableType { } [Serializable] public class SerializableType { } [Serializable] internal class CA2235WithNonSerializableArray { public SerializableType[] s1; internal NonSerializableType[] s2; }", ExpectedDiagnostics = { // Test0.cs(12,52): warning CA2235: Field s2 is a member of type CA2235WithNonSerializableArray which is serializable but is of type NonSerializableType[] which is not serializable GetCA2235CSharpResultAt(12, 52, "s2", "CA2235WithNonSerializableArray", "NonSerializableType[]"), }, }.RunAsync(); await new VerifyVB.Test { ReferenceAssemblies = ReferenceAssemblies.NetFramework.Net472.Default, TestCode = @" Imports System Public Class NonSerializableType End Class <Serializable> Public Class SerializableType End Class <Serializable> Friend Class CA2235WithNonSerializableArray Public s1 As SerializableType() Friend Property s2 As NonSerializableType() End Class", ExpectedDiagnostics = { // Test0.vb(12,37): warning CA2235: Field s2 is a member of type CA2235WithNonSerializableArray which is serializable but is of type NonSerializableType() which is not serializable GetCA2235BasicResultAt(12, 37, "s2", "CA2235WithNonSerializableArray", "NonSerializableType()"), }, }.RunAsync(); } [Fact] public async Task CA2235WithEnumTypeAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; internal enum E1 { F1 = 0 } internal enum E2 : long { F1 = 0 } [Serializable] internal class CA2235WithEnumFields { public E1 s1; internal E2 s2; }"); await VerifyVB.VerifyAnalyzerAsync(@" Imports System Friend Enum E1 F1 = 0 End Enum Friend Enum E2 As Long F1 = 0 End Enum <Serializable> Friend Class CA2235WithEnumFields Public s1 As E1 Friend Property s2 As E2 End Class"); } [Fact, WorkItem(1510, "https://github.com/dotnet/roslyn-analyzers/issues/1510")] public async Task CA2235WithDateTimeTypeAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; [Serializable] internal class CA2235WithDateTimeField { public DateTime s1; }"); await VerifyVB.VerifyAnalyzerAsync(@" Imports System <Serializable> Friend Class CA2235WithDateTimeField Public s1 As DateTime End Class"); } [Fact, WorkItem(1510, "https://github.com/dotnet/roslyn-analyzers/issues/1510")] public async Task CA2235WithNullableTypeAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; [Serializable] internal class CA2235WithNullableField { public long? s1; }"); await VerifyVB.VerifyAnalyzerAsync(@" Imports System <Serializable> Friend Class CA2235WithNullableField Public s1 As Long? End Class"); } [Fact] public async Task CA2235WithSpecialSerializableTypeFieldsAsync() { // Interface, type parameter and delegate fields are always considered serializable. await VerifyCS.VerifyAnalyzerAsync(@" using System; interface I { } [Serializable] internal class GenericType<T> { public I s1; internal T s2; private delegate void s3(); }"); await VerifyVB.VerifyAnalyzerAsync(@" Imports System Friend Interface I End Interface <Serializable> Friend Class GenericType(Of T) Public s1 As I Friend s2 As T Private Delegate Sub s3() End Class"); } [Fact, WorkItem(1883, "https://github.com/dotnet/roslyn-analyzers/issues/1883")] public async Task CA2235WithNonInstanceFieldsOfNonSerializableTypeAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public class NonSerializableType { } [Serializable] internal class CA2235WithNonInstanceFieldsOfNonSerializableType { public const NonSerializableType s1 = null; public static NonSerializableType s2; }"); await VerifyVB.VerifyAnalyzerAsync(@" Imports System Public Class NonSerializableType End Class <Serializable> Friend Class CA2235WithNonInstanceFieldsOfNonSerializableType Public Const s1 As Object = Nothing Public Shared s2 As NonSerializableType End Class"); } [Fact, WorkItem(1970, "https://github.com/dotnet/roslyn-analyzers/issues/1970")] public async Task CA2235WithISerializableImplementationAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Runtime.Serialization; public class NonSerializableType { } [Serializable] internal class CA2235WithISerializableImplementation : ISerializable { private NonSerializableType _nonSerializable; public CA2235WithISerializableImplementation(SerializationInfo info, StreamingContext context) { } public void GetObjectData(SerializationInfo info, StreamingContext context) { } }"); await VerifyVB.VerifyAnalyzerAsync(@" Imports System Imports System.Runtime.Serialization Public Class NonSerializableType End Class <Serializable> Friend Class CA2235WithISerializableImplementation Implements ISerializable Private _nonSerializable As NonSerializableType Private Sub New(Info As SerializationInfo, Context As StreamingContext) End Sub Private Sub GetObjectData(Info As SerializationInfo, Context As StreamingContext) Implements ISerializable.GetObjectData End Sub End Class"); } internal static readonly string CA2235Message = MicrosoftNetCoreAnalyzersResources.MarkAllNonSerializableFieldsMessage; private static DiagnosticResult GetCA2235CSharpResultAt(int line, int column, string fieldName, string containerName, string typeName) => #pragma warning disable RS0030 // Do not used banned APIs VerifyCS.Diagnostic(SerializationRulesDiagnosticAnalyzer.RuleCA2235) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(fieldName, containerName, typeName); private static DiagnosticResult GetCA2235BasicResultAt(int line, int column, string fieldName, string containerName, string typeName) => #pragma warning disable RS0030 // Do not used banned APIs VerifyVB.Diagnostic(SerializationRulesDiagnosticAnalyzer.RuleCA2235) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(fieldName, containerName, typeName); } }
37.65316
200
0.536717
[ "MIT" ]
JoeRobich/roslyn-analyzers
src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Runtime/MarkAllNonSerializableFieldsTests.cs
23,232
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Migrations; using Xunit; namespace Microsoft.EntityFrameworkCore.SqlServer.Tests { public class SqlServerMigrationBuilderTest { [Fact] public void IsSqlServer_when_using_SqlServer() { var migrationBuilder = new MigrationBuilder("Microsoft.EntityFrameworkCore.SqlServer"); Assert.True(migrationBuilder.IsSqlServer()); } [Fact] public void Not_IsSqlServer_when_using_different_provider() { var migrationBuilder = new MigrationBuilder("Microsoft.EntityFrameworkCore.InMemory"); Assert.False(migrationBuilder.IsSqlServer()); } } }
31.758621
111
0.712269
[ "Apache-2.0" ]
skalpin/EntityFrameworkCore
test/EFCore.SqlServer.Tests/SqlServerMigrationBuilderTest.cs
921
C#
using Microsoft.EntityFrameworkCore; namespace DocOpen.Data { public class DocOpenContext : DbContext { public DocOpenContext(DbContextOptions<DocOpenContext> options) : base(options){ } public DbSet<Submission> Submissions{get; set;} public DbSet<Project> Projects{get; set;} public DbSet<ProjectItem> ProjectItems {get; set;} public DbSet<User> Users{get; set;} } }
25.352941
88
0.675174
[ "MIT" ]
tonnyeremin/docopen
src/DocOpen/DataLayer/DocOpenContext.cs
431
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Actor { public int id; public string name; public string title; public string weapon; public float strength = 15.5f; public int level; public string Talk() { return "Hi, I am RL agent"; } public string HasWeapon() { return weapon; } public void LevelUp() { level = level + 1; } }
18.576923
36
0.573499
[ "Apache-2.0" ]
KevinJeon/Unity_Practice
New Unity Project (1)/Assets/Actor.cs
483
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ExplosiveEnemy : Enemy { [SerializeField] private GameObject explosion; [SerializeField] private float explosionDelay; [SerializeField] private float explosionRadius; [SerializeField] private int explosionDamage; [Space] [SerializeField] private bool drawGizmos; private bool hasPlayerBeenAffected; private void Awake() { rb = GetComponent<Rigidbody2D>(); spriteRenderer = GetComponent<SpriteRenderer>(); } private void Start() { enemyState = ENEMY_STATE.NEUTRAL; } private void Update() { CheckEnemyState(); if (health <= 0) { StartCoroutine(Attack()); } if (player != null) { if (enemyState == ENEMY_STATE.ATTACKING) { StartCoroutine(Attack()); } } } private void FixedUpdate() { if (player != null && enemyState == ENEMY_STATE.CHASING) { Chase(); } } private void Chase() { dir = transform.position - player.position; dir.Normalize(); rb.MovePosition((Vector2) transform.position + (dir * -speed * Time.deltaTime)); } private IEnumerator Attack() { spriteRenderer.color = Color.red; yield return new WaitForSeconds(explosionDelay); hasPlayerBeenAffected = Physics2D.OverlapCircle(transform.position, explosionRadius, whatIsPlayer); Explosion explosion_ = Instantiate(explosion, transform.position, transform.rotation).GetComponent<Explosion>(); explosion_.damage = explosionDamage; explosion_.radius = explosionRadius; explosion_.audioSource.Play(); if (hasPlayerBeenAffected) { Player.I.TakeDamage(explosionDamage); } Destroy(gameObject); } void OnDrawGizmosSelected() { if (drawGizmos) { Gizmos.color = Color.yellow; Gizmos.DrawSphere(transform.position, explosionRadius); } } }
24.8
120
0.619545
[ "MIT" ]
Gabriel-Spinola/Space-Hell-mini-jaaj
Space Jam Game Folder/Assets/Scripts/Enemies/ExplosiveEnemy.cs
2,110
C#
using System.Threading.Tasks; using EasyAbp.Abp.WeChat.MiniProgram.Services.Login; using Shouldly; using Xunit; namespace EasyAbp.Abp.WeChat.MiniProgram.Tests.Services { public class LoginServiceTests : AbpWeChatMiniProgramTestBase { private readonly LoginService _loginService; public LoginServiceTests() { _loginService = GetRequiredService<LoginService>(); } [Fact] public async Task Should_Get_OpenId_And_SessionKey() { var result = await _loginService.Code2SessionAsync( AbpWeChatMiniProgramTestsConsts.AppId, AbpWeChatMiniProgramTestsConsts.AppSecret, AbpWeChatMiniProgramTestsConsts.JsCode); result.ShouldNotBeNull(); result.ErrorCode.ShouldBe(0); result.ErrorMessage.ShouldBeNull(); result.OpenId.ShouldNotBeEmpty(); result.SessionKey.ShouldNotBeEmpty(); } } }
30.454545
65
0.643781
[ "MIT" ]
EasyAbp/Abp.WeChat
tests/EasyAbp.Abp.WeChat.MiniProgram.Tests/Services/LoginServiceTests.cs
1,005
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 ClientPluginEnv /// </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 ClientPluginEnvTests : IDisposable { // TODO uncomment below to declare an instance variable for ClientPluginEnv //private ClientPluginEnv instance; public ClientPluginEnvTests() { // TODO uncomment below to create an instance of ClientPluginEnv //instance = new ClientPluginEnv(); } public void Dispose() { // Cleanup when everything is done. } /// <summary> /// Test an instance of ClientPluginEnv /// </summary> [Fact] public void ClientPluginEnvInstanceTest() { // TODO uncomment below to test "IsType" ClientPluginEnv //Assert.IsType<ClientPluginEnv>(instance); } /// <summary> /// Test the property 'Description' /// </summary> [Fact] public void DescriptionTest() { // TODO unit test for the property 'Description' } /// <summary> /// Test the property 'Name' /// </summary> [Fact] public void NameTest() { // TODO unit test for the property 'Name' } /// <summary> /// Test the property 'Settable' /// </summary> [Fact] public void SettableTest() { // TODO unit test for the property 'Settable' } /// <summary> /// Test the property 'Value' /// </summary> [Fact] public void ValueTest() { // TODO unit test for the property 'Value' } } }
26.239583
179
0.583565
[ "Apache-2.0" ]
Stackwalkerllc/sdk
clients/client/dotnet/src/Ory.Client.Test/Model/ClientPluginEnvTests.cs
2,519
C#
// // TrackerTestRig.cs // // Authors: // Alan McGovern alan.mcgovern@gmail.com // // Copyright (C) 2006 Alan McGovern // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Net; using System.Threading; using MonoTorrent.BEncoding; using MonoTorrent.Connections.Tracker; namespace MonoTorrent.Trackers { public class CustomComparer : IPeerComparer { public new bool Equals (object left, object right) { return left.Equals (right); } public object GetKey (AnnounceRequest parameters) { return parameters.Uploaded; } public int GetHashCode (object obj) { return obj.GetHashCode (); } } class CustomListener : TrackerListener { public BEncodedValue Handle (PeerDetails d, TorrentEvent e, ITrackable trackable) { NameValueCollection c = new NameValueCollection (); c.Add ("info_hash", trackable.InfoHash.UrlEncode ()); c.Add ("peer_id", d.peerId.UrlEncode ()); c.Add ("port", d.Port.ToString ()); c.Add ("uploaded", d.Uploaded.ToString ()); c.Add ("downloaded", d.Downloaded.ToString ()); c.Add ("left", d.Remaining.ToString ()); c.Add ("compact", "0"); return base.Handle (c, d.ClientAddress, false); } public override void Start () { } public override void Stop () { } } public class Trackable : ITrackable { public Trackable (InfoHash infoHash, string name) { this.InfoHash = infoHash; this.Name = name; } public InfoHash InfoHash { get; } public string Name { get; } } public class PeerDetails { public int Port; public IPAddress ClientAddress; public long Downloaded; public long Uploaded; public long Remaining; public BEncodedString peerId; public ITrackable trackable; } class TrackerTestRig : IDisposable { private readonly Random r = new Random (1000); public CustomListener Listener; public TrackerServer Tracker; public List<PeerDetails> Peers; public List<Trackable> Trackables; public TrackerTestRig () { Tracker = new TrackerServer (); Listener = new CustomListener (); Tracker.RegisterListener (Listener); GenerateTrackables (); GeneratePeers (); } private void GenerateTrackables () { Trackables = new List<Trackable> (); for (int i = 0; i < 10; i++) { byte[] infoHash = new byte[20]; r.NextBytes (infoHash); Trackables.Add (new Trackable (new InfoHash (infoHash), i.ToString ())); } } private void GeneratePeers () { Peers = new List<PeerDetails> (); for (int i = 0; i < 100; i++) { PeerDetails d = new PeerDetails (); d.ClientAddress = IPAddress.Parse ($"127.0.{i}.2"); d.Downloaded = (int) (10000 * r.NextDouble ()); d.peerId = $"-----------------{i:0.000}"; d.Port = r.Next (65000); d.Remaining = r.Next (10000, 100000); d.Uploaded = r.Next (10000, 100000); Peers.Add (d); } } public void Dispose () { Tracker.Dispose (); Listener.Stop (); } } }
29.867925
89
0.587492
[ "MIT" ]
wizard872/monotorrent
src/Tests/Tests.MonoTorrent.Client/Tracker/TrackerTestRig.cs
4,749
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.IO; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { public sealed partial class DesktopAssemblyIdentityComparer : AssemblyIdentityComparer { // Portability: // If a reference or definition identity is strong, not retargetable, and portable (i.e. one of a few names hard-coded in Fusion) // and the portability for its PublicKeyToken is not disabled in App.config file then the identity is replaced by a different identity // before the match is performed. // // Portable identities: // - System, PKT=7cec85d7bea7798e, Version=2.0.0.0-5.9.0.0 -> System, PKT=b77a5c561934e089, Version=<current framework version> // - System.Core, PKT=7cec85d7bea7798e, Version=2.0.0.0-5.9.0.0 -> System.Core, PKT=b77a5c561934e089, Version=<current framework version> // - System.ComponentModel.Composition, PKT=31bf3856ad364e35, Version=2.0.0.0-5.9.0.0 -> System.ComponentModel.Composition, PKT=b77a5c561934e089, Version=<current framework version> // - Microsoft.VisualBasic, PKT=31bf3856ad364e35, Version=2.0.0.0-5.9.0.0 -> Microsoft.VisualBasic, PKT=b03f5f7f11d50a3a, Version=10.0.0.0 // // Retargetability: // If the reference identity specifies property Retargetable=Yes the identity is looked up in a hard-coded Fusion table. // The table maps it to an identity that is used for identity matching. // Note: Retargeting may change name, version and public key token of the identity. // // Version unification: // FX identities (hard-coded list in Fusion): // FX references are unified regardless of the isUnified flags, returns EquivalentFxUnified. // Non-FX identities: // if (isUnified1 && version1 > version2 || isUnified2 && version1 < version2) return EquivalentUnified. public static new readonly DesktopAssemblyIdentityComparer Default = new DesktopAssemblyIdentityComparer(default(AssemblyPortabilityPolicy)); internal readonly AssemblyPortabilityPolicy policy; /// <param name="policy">Assembly portability policy, usually provided through an app.config file.</param> internal DesktopAssemblyIdentityComparer(AssemblyPortabilityPolicy policy) { this.policy = policy; } /// <summary> /// Loads <see cref="AssemblyPortabilityPolicy"/> information from XML with App.config schema. /// </summary> /// <exception cref="System.Xml.XmlException">The stream doesn't contain a well formed XML.</exception> /// <exception cref="ArgumentNullException"><paramref name="input"/> is null.</exception> /// <remarks> /// Tries to find supportPortability elements in the given XML: /// <![CDATA[ /// <configuration> /// <runtime> /// <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> /// <supportPortability PKT="7cec85d7bea7798e" enable="false"/> /// <supportPortability PKT="31bf3856ad364e35" enable="false"/> /// </assemblyBinding> /// </runtime> /// </configuration> /// ]]> /// /// Keeps the stream open. /// </remarks> public static DesktopAssemblyIdentityComparer LoadFromXml(Stream input) { return new DesktopAssemblyIdentityComparer(AssemblyPortabilityPolicy.LoadFromXml(input)); } internal AssemblyPortabilityPolicy PortabilityPolicy { get { return this.policy; } } internal override bool ApplyUnificationPolicies( ref AssemblyIdentity reference, ref AssemblyIdentity definition, AssemblyIdentityParts referenceParts, out bool isFxAssembly) { if (reference.ContentType == AssemblyContentType.Default && SimpleNameComparer.Equals(reference.Name, definition.Name) && SimpleNameComparer.Equals(reference.Name, "mscorlib")) { isFxAssembly = true; reference = definition; return true; } if (!reference.IsRetargetable && definition.IsRetargetable) { // Reference is not retargetable, but definition is retargetable. // Non-equivalent. isFxAssembly = false; return false; } // Notes: // an assembly might be both retargetable and portable // in that case retargeatable table acts as an override. // Apply portability policy transforms first (e.g. rewrites references to SL assemblies to their desktop equivalents) // If the reference is partial and is missing version or PKT it is not ported. reference = Port(reference); definition = Port(definition); if (reference.IsRetargetable && !definition.IsRetargetable) { if (!AssemblyIdentity.IsFullName(referenceParts)) { isFxAssembly = false; return false; } // Reference needs to be retargeted before comparison, // unless it's optionally retargetable and we already match the PK bool skipRetargeting = IsOptionallyRetargetableAssembly(reference) && AssemblyIdentity.KeysEqual(reference, definition); if (!skipRetargeting) { reference = Retarget(reference); } } // At this point we are in one of the following states: // // 1) Both ref/def are not retargetable // 2) Both ref/def are retargetable // 3) Ref is retargetable (and has been retargeted) // // We can do a straight compare of ref/def at this point using the // regular rules if (reference.IsRetargetable && definition.IsRetargetable) { isFxAssembly = IsRetargetableAssembly(definition); } else { isFxAssembly = IsFrameworkAssembly(definition); } return true; } /// <summary> /// Returns true if the identity is a Framework 4.5 or lower assembly. /// </summary> private static bool IsFrameworkAssembly(AssemblyIdentity identity) { // Note: // FrameworkAssemblyTable::IsFrameworkAssembly returns false if culture is not neutral. // However its caller doesn't initialize the culture and hence the culture is ignored. // PrepQueryMatchData(pName, wzName, &dwSizeName, wzVersion, &dwSizeVer, wzPublicKeyToken, &dwSizePKT, NULL, NULL, NULL);. if (identity.ContentType != AssemblyContentType.Default) { return false; } FrameworkAssemblyDictionary.Value value; if (!g_arFxPolicy.TryGetValue(identity.Name, out value) || !value.PublicKeyToken.SequenceEqual(identity.PublicKeyToken)) { return false; } // build and revision numbers are ignored uint thisVersion = ((uint)identity.Version.Major << 16) | (uint)identity.Version.Minor; uint fxVersion = ((uint)value.Version.Major << 16) | (uint)value.Version.Minor; return thisVersion <= fxVersion; } private static bool IsRetargetableAssembly(AssemblyIdentity identity) { bool retargetable, portable; IsRetargetableAssembly(identity, out retargetable, out portable); return retargetable; } private static bool IsOptionallyRetargetableAssembly(AssemblyIdentity identity) { if (!identity.IsRetargetable) { return false; } bool retargetable, portable; IsRetargetableAssembly(identity, out retargetable, out portable); return retargetable && portable; } private static bool IsTriviallyNonRetargetable(AssemblyIdentity identity) { // Short-circuit zero-version/non-neutral culture/weak name, // which will never match retargeted identities. return identity.CultureName.Length != 0 || identity.ContentType != AssemblyContentType.Default || !identity.IsStrongName; } private static void IsRetargetableAssembly(AssemblyIdentity identity, out bool retargetable, out bool portable) { retargetable = portable = false; if (IsTriviallyNonRetargetable(identity)) { return; } FrameworkRetargetingDictionary.Value value; retargetable = g_arRetargetPolicy.TryGetValue(identity, out value); portable = value.IsPortable; } private static AssemblyIdentity Retarget(AssemblyIdentity identity) { if (IsTriviallyNonRetargetable(identity)) { return identity; } FrameworkRetargetingDictionary.Value value; if (g_arRetargetPolicy.TryGetValue(identity, out value)) { return new AssemblyIdentity( value.NewName ?? identity.Name, (Version)value.NewVersion, identity.CultureName, value.NewPublicKeyToken, hasPublicKey: false, isRetargetable: identity.IsRetargetable, contentType: AssemblyContentType.Default); } return identity; } private AssemblyIdentity Port(AssemblyIdentity identity) { if (identity.IsRetargetable || !identity.IsStrongName || identity.ContentType != AssemblyContentType.Default) { return identity; } Version newVersion = null; ImmutableArray<byte> newPublicKeyToken = default(ImmutableArray<byte>); var version = (AssemblyVersion)identity.Version; if (version >= new AssemblyVersion(2, 0, 0, 0) && version <= new AssemblyVersion(5, 9, 0, 0)) { if (identity.PublicKeyToken.SequenceEqual(SILVERLIGHT_PLATFORM_PUBLICKEY_STR_L)) { if (!policy.SuppressSilverlightPlatformAssembliesPortability) { if (SimpleNameComparer.Equals(identity.Name, "System") || SimpleNameComparer.Equals(identity.Name, "System.Core")) { newVersion = (Version)VER_ASSEMBLYVERSION_STR_L; newPublicKeyToken = ECMA_PUBLICKEY_STR_L; } } } else if (identity.PublicKeyToken.SequenceEqual(SILVERLIGHT_PUBLICKEY_STR_L)) { if (!policy.SuppressSilverlightLibraryAssembliesPortability) { if (SimpleNameComparer.Equals(identity.Name, "Microsoft.VisualBasic")) { newVersion = new Version(10, 0, 0, 0); newPublicKeyToken = MICROSOFT_PUBLICKEY_STR_L; } if (SimpleNameComparer.Equals(identity.Name, "System.ComponentModel.Composition")) { newVersion = (Version)VER_ASSEMBLYVERSION_STR_L; newPublicKeyToken = ECMA_PUBLICKEY_STR_L; } } } } if (newVersion == null) { return identity; } return new AssemblyIdentity( identity.Name, newVersion, identity.CultureName, newPublicKeyToken, hasPublicKey: false, isRetargetable: identity.IsRetargetable, contentType: AssemblyContentType.Default); } } }
42.160656
193
0.576328
[ "Apache-2.0" ]
pottereric/roslyn
src/Compilers/Core/Desktop/DesktopAssemblyIdentityComparer.cs
12,861
C#
// Copyright (c) Daniel Crenna. 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; using System.Collections.Generic; using System.Reactive.Disposables; namespace reactive.pipes { public class CompositeSubscription<T> : IObservableWithOutcomes<T>, IDisposable, IEnumerable<IObservableWithOutcomes<T>> { private readonly List<IObservableWithOutcomes<T>> _subscriptions; public CompositeSubscription() { _subscriptions = new List<IObservableWithOutcomes<T>>(); } public void Add(IObservableWithOutcomes<T> subscription) { _subscriptions.Add(subscription); } public void Dispose() { foreach(var subject in _subscriptions) (subject as IDisposable)?.Dispose(); } public bool Handled { get { var handled = true; foreach (var subscription in _subscriptions) handled &= subscription.Handled; return handled; } } public ICollection<ObservableOutcome> Outcomes => new List<ObservableOutcome>(); public void Clear() { foreach (var subscription in _subscriptions) subscription.Outcomes.Clear(); } public void OnNext(T value) { foreach (var subject in _subscriptions) { subject.OnNext(value); } } public void OnError(Exception error) { foreach (var subject in _subscriptions) { subject.OnError(error); } } public void OnCompleted() { foreach (var subject in _subscriptions) { subject.OnCompleted(); } } public IDisposable Subscribe(IObserver<T> observer) { var composite = new CompositeDisposable(); foreach (var subject in _subscriptions) { composite.Add(subject.Subscribe(observer)); } return composite; } public IEnumerator<IObservableWithOutcomes<T>> GetEnumerator() { return _subscriptions.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
21.180851
121
0.710196
[ "Apache-2.0" ]
JTOne123/reactive-pipes
src/reactive.pipes/CompositeSubscription.cs
1,993
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace ExperimentWithControls { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void numberTextBox_TextChanged(object sender, TextChangedEventArgs e) { number.Text = numberTextBox.Text; } private void numberTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e) { e.Handled = !int.TryParse(e.Text, out int result); } private void smallSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) { number.Text = smallSlider.Value.ToString("0"); } private void bigSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) { number.Text = bigSlider.Value.ToString("000-000-0000"); } private void RadioButton_Checked(object sender, RoutedEventArgs e) { if (sender is RadioButton radioButton) { number.Text = radioButton.Content.ToString(); } } private void readOnlyComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { if(readOnlyComboBox.SelectedItem is ListBoxItem listBoxItem) { number.Text = listBoxItem.Content.ToString(); } } private void editableComboBox_TextChanged(object sender, TextChangedEventArgs e) { if (sender is ComboBox comboBox) { number.Text = comboBox.Text; } } } }
28.726027
102
0.636147
[ "MIT" ]
JoyfulReaper/HeadFirstCSharp
ExperimentWithControls/ExperimentWithControls/MainWindow.xaml.cs
2,099
C#
/* Copyright 2019 - 2021 Inetum 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 inetum.unityUtils; using System; using System.Collections.Generic; using System.Linq; using umi3d.common; using UnityEngine; using UnityEngine.Rendering; namespace umi3d.edk { public class UMI3DEnvironment : Singleton<UMI3DEnvironment> { private const DebugScope scope = DebugScope.EDK | DebugScope.Collaboration; [EditorReadOnly] public bool useDto = false; #region initialization ///<inheritdoc/> protected override void Awake() { base.Awake(); } #endregion #region environment description /// <summary> /// Environment's name. /// </summary> [EditorReadOnly] public string environmentName = "Environment Name"; [HideInInspector] public List<UMI3DScene> scenes; [SerializeField, EditorReadOnly] public List<AssetLibrary> globalLibraries; [SerializeField, EditorReadOnly] private Vector3 defaultStartPosition = new Vector3(0, 0, 0); [SerializeField, EditorReadOnly] private Vector3 defaultStartOrientation = new Vector3(0, 0, 0); public static UMI3DAsyncProperty<Vector3> objectStartPosition { get; protected set; } public static UMI3DAsyncProperty<Quaternion> objectStartOrientation { get; protected set; } private void Start() { foreach (UMI3DAbstractNode node in GetComponentsInChildren<UMI3DAbstractNode>(true)) node.Register(); scenes = new List<UMI3DScene>(GetComponentsInChildren<UMI3DScene>(true)); InitDefinition(); } /// <summary> /// Get scene's information required for client connection. /// </summary> public MediaDto ToDto() { var res = new MediaDto { name = environmentName, connection = UMI3DServer.Instance.ToDto(), versionMajor = UMI3DVersion.major, versionMinor = UMI3DVersion.minor, versionStatus = UMI3DVersion.status, versionDate = UMI3DVersion.date }; return res; } public virtual GlTFEnvironmentDto ToDto(UMI3DUser user) { var env = new GlTFEnvironmentDto { id = UMI3DGlobalID.EnvironementId }; env.scenes.AddRange(scenes.Where(s => s.LoadOnConnection(user)).Select(s => s.ToGlTFNodeDto(user))); env.extensions.umi3d = CreateDto(); WriteProperties(env.extensions.umi3d, user); return env; } /// <summary> /// Write Properties on a UMI3DEnvironmentDto. /// </summary> /// <param name="dto"></param> /// <param name="user"></param> protected virtual void WriteProperties(UMI3DEnvironmentDto dto, UMI3DUser user) { dto.LibrariesId = globalLibraries.Select(l => l.id).ToList(); dto.preloadedScenes = objectPreloadedScenes.GetValue(user).Select(r => new PreloadedSceneDto() { scene = r.ToDto() }).ToList(); dto.ambientType = (AmbientType)objectAmbientType.GetValue(user); dto.skyColor = objectSkyColor.GetValue(user); dto.horizontalColor = objectHorizonColor.GetValue(user); dto.groundColor = objectGroundColor.GetValue(user); dto.ambientIntensity = objectAmbientIntensity.GetValue(user); dto.skybox = objectAmbientSkyboxImage.GetValue(user)?.ToDto(); dto.defaultMaterial = defaultMaterial?.ToDto(); } /// <summary> /// Create a UMI3DEnvironmentDto. /// </summary> /// <returns></returns> protected virtual UMI3DEnvironmentDto CreateDto() { return new UMI3DEnvironmentDto(); } public static EnterDto ToEnterDto(UMI3DUser user) { return new EnterDto() { userPosition = objectStartPosition.GetValue(user), userRotation = objectStartOrientation.GetValue(user), usedDto = Instance.useDto }; } public LibrariesDto ToLibrariesDto(UMI3DUser user) { List<AssetLibraryDto> libraries = globalLibraries?.Select(l => l.ToDto())?.ToList() ?? new List<AssetLibraryDto>(); IEnumerable<AssetLibraryDto> sceneLib = scenes?.SelectMany(s => s.libraries)?.GroupBy(l => l.id)?.Where(l => !libraries.Any(l2 => l2.libraryId == l.Key))?.Select(l => l.First().ToDto()); if (sceneLib != null) libraries.AddRange(sceneLib); return new LibrariesDto() { libraries = libraries }; } public static bool UseLibrary() { return Exists ? Instance.globalLibraries.Any() || Instance.scenes.Any(s => s.libraries.Any()) : false; } #endregion #region AsyncProperties private void InitDefinition() { ulong id = UMI3DGlobalID.EnvironementId; objectStartPosition = new UMI3DAsyncProperty<Vector3>(id, 0, defaultStartPosition); objectStartOrientation = new UMI3DAsyncProperty<Quaternion>(id, 0, Quaternion.Euler(defaultStartOrientation)); objectPreloadedScenes = new UMI3DAsyncListProperty<UMI3DResource>(id, UMI3DPropertyKeys.PreloadedScenes, preloadedScenes, (UMI3DResource r, UMI3DUser user) => new PreloadedSceneDto() { scene = r.ToDto() }); objectAmbientType = new UMI3DAsyncProperty<AmbientMode>(id, UMI3DPropertyKeys.AmbientType, mode, (mode, user) => (AmbientType)mode); objectSkyColor = new UMI3DAsyncProperty<Color>(id, UMI3DPropertyKeys.AmbientSkyColor, skyColor, (c, u) => (SerializableColor)c); objectHorizonColor = new UMI3DAsyncProperty<Color>(id, UMI3DPropertyKeys.AmbientHorizontalColor, horizontalColor, (c, u) => (SerializableColor)c); objectGroundColor = new UMI3DAsyncProperty<Color>(id, UMI3DPropertyKeys.AmbientGroundColor, groundColor, (c, u) => (SerializableColor)c); objectAmbientIntensity = new UMI3DAsyncProperty<float>(id, UMI3DPropertyKeys.AmbientIntensity, ambientIntensity); objectAmbientSkyboxImage = new UMI3DAsyncProperty<UMI3DResource>(id, UMI3DPropertyKeys.AmbientSkyboxImage, skyboxImage, (r, u) => r.ToDto()); } [SerializeField, EditorReadOnly] private List<UMI3DResource> preloadedScenes = new List<UMI3DResource>(); public UMI3DAsyncListProperty<UMI3DResource> objectPreloadedScenes; /// <summary> /// AsyncProperties of the ambient Type. /// </summary> private AmbientMode mode => RenderSettings.ambientMode; public UMI3DAsyncProperty<AmbientMode> objectAmbientType; /// <summary> /// AsyncProperties of the ambient color. /// </summary> private Color skyColor => RenderSettings.ambientSkyColor; public UMI3DAsyncProperty<Color> objectSkyColor; /// <summary> /// AsyncProperties of the ambient color. /// </summary> private Color horizontalColor => RenderSettings.ambientEquatorColor; public UMI3DAsyncProperty<Color> objectHorizonColor; /// <summary> /// AsyncProperties of the ambient color. /// </summary> private Color groundColor => RenderSettings.ambientGroundColor; public UMI3DAsyncProperty<Color> objectGroundColor; /// <summary> /// AsyncProperties of the ambient Intensity. /// </summary> private float ambientIntensity => RenderSettings.ambientIntensity; public UMI3DAsyncProperty<float> objectAmbientIntensity; /// <summary> /// AsyncProperties of the Skybox Image /// </summary> [SerializeField, EditorReadOnly] private UMI3DResource skyboxImage = null; public UMI3DAsyncProperty<UMI3DResource> objectAmbientSkyboxImage; /// <summary> /// Properties of the default Material, it is used to initialise loaded materials in clients. /// </summary> [SerializeField] private UMI3DResource defaultMaterial = null; #endregion #region entities /// <summary> /// Contains the objects stored in the scene. /// </summary> private readonly DictionaryGenerator<UMI3DEntity> entities = new DictionaryGenerator<UMI3DEntity>(); /// <summary> /// Access to all entities of a given type. /// </summary> public static IEnumerable<E> GetEntities<E>() where E : class, UMI3DEntity { if (Exists) return Instance.entities?.Values?.ToList()?.Where(entities => entities is E)?.Select(e => e as E); else if (QuittingManager.ApplicationIsQuitting) return new List<E>(); else throw new System.NullReferenceException("UMI3DEnvironment doesn't exists !"); } /// <summary> /// Return all id that have been registered and remove. /// </summary> /// <returns></returns> public static IEnumerable<ulong> GetUnregisteredEntitiesId() { if (Exists) return Instance.entities?.old.ToList(); else if (QuittingManager.ApplicationIsQuitting) return new List<ulong>(); else throw new System.NullReferenceException("UMI3DEnvironment doesn't exists !"); } /// <summary> /// Access to all entities of a given type that validate a predicate. /// </summary> /// <param name="predicate">Your selection condition</param> public static IEnumerable<E> GetEntitiesWhere<E>(System.Func<E, bool> predicate) where E : class, UMI3DEntity { if (Exists) return Instance.entities.Values.ToList().Where(entities => entities is E).Select(e => e as E).Where(predicate); else if (QuittingManager.ApplicationIsQuitting) return new List<E>(); else throw new System.NullReferenceException("UMI3DEnvironment doesn't exists !"); } /// <summary> /// Get entity by id. /// </summary> /// <param name="id">Entity to get id</param> public static E GetEntity<E>(ulong id) where E : class, UMI3DEntity { if (Exists) return Instance.entities[id] as E; else if (QuittingManager.ApplicationIsQuitting) return null; else throw new System.NullReferenceException("UMI3DEnvironment doesn't exists !"); } /// <summary> /// Get entity by id. /// </summary> /// <param name="id">Entity to get id</param> public static (E entity, bool exist, bool found) GetEntityIfExist<E>(ulong id) where E : class, UMI3DEntity { if (Exists) { if (Instance.entities.IsOldId(id)) return (null, false, true); else { UMI3DEntity e = Instance.entities[id]; if (e is E entity) return (entity, true, true); else return (null, true, true); } } else if (QuittingManager.ApplicationIsQuitting) return (null, false, false); else throw new System.NullReferenceException("UMI3DEnvironment doesn't exists !"); } /// <summary> /// Register an entity to the environment, and return it's id. /// </summary> /// <param name="entity">Entity to register</param> /// <returns>Registered object's id.</returns> public static ulong Register(UMI3DEntity entity) { if (Exists) { if (entity != null) return Instance.entities.Register(entity); else throw new System.NullReferenceException("Trying to register null entity !"); } else if (QuittingManager.ApplicationIsQuitting) { return 0; } else { throw new System.NullReferenceException("UMI3DEnvironment doesn't exists !"); } } /// <summary> /// Register an entity to the environment with an id, and return it's id. /// </summary> /// <param name="entity">Entity to register</param> /// <param name="id">id to use</param> /// <returns>Registered object's id (same as id field if the id wasn't already used).</returns> public static ulong Register(UMI3DEntity entity, ulong id) { if (Exists) { if (entity != null) return Instance.entities.Register(entity, id); else throw new System.NullReferenceException("Trying to register null entity !"); } else if (QuittingManager.ApplicationIsQuitting) { return 0; } else { throw new System.NullReferenceException("UMI3DEnvironment doesn't exists !"); } } /// <summary> /// Remove an object from the scene. /// Supported Types: AbstractObject3D, GenericInteraction, Tool, Toolbox /// </summary> /// <param name="obj">Object to remove</param> public static void Remove(UMI3DEntity obj) { if (obj != null && Exists) Instance?.entities?.Remove(obj.Id()); } public static void Remove(ulong id) { if (id != 0 && Exists) { Instance.entities?.Remove(id); } } public class DictionaryGenerator<A> { private readonly HashSet<ulong> unRegisteredIds = new HashSet<ulong>(); /// <summary> /// Contains the stored objects. /// </summary> private readonly Dictionary<ulong, A> objects = new Dictionary<ulong, A>(); public Dictionary<ulong, A>.ValueCollection Values => objects.Values; public IEnumerable<ulong> old => unRegisteredIds; public A this[ulong key] { get { if (key == 0) return default; else if (objects.ContainsKey(key)) return objects[key]; else return default; } } public bool IsOldId(ulong guid) { return unRegisteredIds.Contains(guid); } private readonly System.Random random = new System.Random(); private ulong NewID() { ulong value = LongRandom(100010); while (objects.ContainsKey(value)) value = LongRandom(100010); return value; } /// <summary> /// return a random ulong with a min value; /// </summary> /// <param name="min">min value for this ulong. this should be inferior to 4,294,967,295/2</param> /// <returns></returns> private ulong LongRandom(ulong min) { byte[] buf = new byte[64]; random.NextBytes(buf); ulong longRand = (ulong)Mathf.Abs(BitConverter.ToInt64(buf, 0)); if (longRand < min) return longRand + min; return longRand; } public ulong Register(A obj) { byte[] key = Guid.NewGuid().ToByteArray(); ulong guid = NewID(); objects.Add(guid, obj); if (unRegisteredIds.Contains(guid)) unRegisteredIds.Remove(guid); return guid; } public ulong Register(A obj, ulong guid) { if (objects.ContainsKey(guid)) { ulong old = guid; guid = NewID(); UMI3DLogger.LogWarning($"Guid [{old}] was already used node register with another id [{guid}]", scope); } objects.Add(guid, obj); if (unRegisteredIds.Contains(guid)) unRegisteredIds.Remove(guid); return guid; } public void Remove(ulong guid) { objects.Remove(guid); unRegisteredIds.Add(guid); } } #endregion } }
37.984716
218
0.574409
[ "Apache-2.0" ]
Gfi-Innovation/UMI3D-SDK
UMI3D-SDK/Assets/UMI3D SDK/EnvironmentDevelopmentKit/Core/Runtime/UMI3DEnvironment.cs
17,399
C#
using System.Runtime.CompilerServices; using LibSvnSharp.Interop.Apr; // ReSharper disable once CheckNamespace namespace LibSvnSharp.Interop.Svn { // ReSharper disable once InconsistentNaming partial class svn_pools { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static apr_pool_t svn_pool_create(apr_pool_t parent) => svn_pool_create_ex(parent, null); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void svn_pool_clear(apr_pool_t pool) => apr_pools.apr_pool_clear(pool); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void svn_pool_destroy(apr_pool_t pool) => apr_pools.apr_pool_destroy(pool); } }
35.8
104
0.761173
[ "Apache-2.0" ]
mendix/LibSvnSharp
src/LibSvnSharp/Interop/UnmanagedApiExtensions.cs
718
C#
#if UNITY_EDITOR || FBXSDK_RUNTIME //------------------------------------------------------------------------------ // <auto-generated /> // // This file was automatically generated by SWIG (http://www.swig.org). // Version 3.0.12 // // Do not make changes to this file unless you know what you are doing--modify // the SWIG interface file instead. //------------------------------------------------------------------------------ namespace Autodesk.Fbx { public class FbxPropertyString : FbxProperty { private global::System.Runtime.InteropServices.HandleRef swigCPtr; internal FbxPropertyString(global::System.IntPtr cPtr, bool cMemoryOwn) : base(NativeMethods.FbxPropertyString_SWIGUpcast(cPtr), cMemoryOwn) { swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); } internal static global::System.Runtime.InteropServices.HandleRef getCPtr(FbxPropertyString obj) { return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; } public override void Dispose() { lock(this) { if (swigCPtr.Handle != global::System.IntPtr.Zero) { if (swigCMemOwn) { swigCMemOwn = false; throw new global::System.MethodAccessException("C++ destructor does not have public access"); } swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); } global::System.GC.SuppressFinalize(this); base.Dispose(); } } public FbxPropertyString Set(string pValue) { FbxPropertyString ret = new FbxPropertyString(NativeMethods.FbxPropertyString_Set(swigCPtr, pValue), false); if (NativeMethods.SWIGPendingException.Pending) throw NativeMethods.SWIGPendingException.Retrieve(); return ret; } public string Get() { string ret = NativeMethods.FbxPropertyString_Get(swigCPtr); if (NativeMethods.SWIGPendingException.Pending) throw NativeMethods.SWIGPendingException.Retrieve(); return ret; } public string EvaluateValue(FbxTime pTime, bool pForceEval) { string ret = NativeMethods.FbxPropertyString_EvaluateValue__SWIG_0(swigCPtr, FbxTime.getCPtr(pTime), pForceEval); if (NativeMethods.SWIGPendingException.Pending) throw NativeMethods.SWIGPendingException.Retrieve(); return ret; } public string EvaluateValue(FbxTime pTime) { string ret = NativeMethods.FbxPropertyString_EvaluateValue__SWIG_1(swigCPtr, FbxTime.getCPtr(pTime)); if (NativeMethods.SWIGPendingException.Pending) throw NativeMethods.SWIGPendingException.Retrieve(); return ret; } public string EvaluateValue() { string ret = NativeMethods.FbxPropertyString_EvaluateValue__SWIG_2(swigCPtr); if (NativeMethods.SWIGPendingException.Pending) throw NativeMethods.SWIGPendingException.Retrieve(); return ret; } } } #endif // UNITY_EDITOR || FBXSDK_RUNTIME
39.657534
144
0.708808
[ "CC0-1.0" ]
ewanreis/fmp-v1
fmp/Library/PackageCache/com.autodesk.fbx@4.0.1/Runtime/Scripts/FbxPropertyString.cs
2,895
C#
using SUS.MvcFramework; using System.Threading.Tasks; namespace CarShop { public static class Program { public static async Task Main(string[] args) { await Host.CreateHostAsync(new Startup()); } } }
16.733333
54
0.613546
[ "MIT" ]
GeorgiGradev/C-Web
01. C# Web Basics/11. Exams/02. Car Shop/MySolution/Apps/CarShop/Program.cs
253
C#
//****************************************************************************************************** // SubFileStream_IoSession.cs - Gbtc // // Copyright © 2014, Grid Protection Alliance. All Rights Reserved. // // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See // the NOTICE file distributed with this work for additional information regarding copyright ownership. // The GPA licenses this file to you under the MIT License (MIT), the "License"; you may // not use this file except in compliance with the License. You may obtain a copy of the License at: // // http://opensource.org/licenses/MIT // // Unless agreed to in writing, the subject software distributed under the License is distributed on an // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the // License for the specific language governing permissions and limitations. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 6/15/2012 - Steven E. Chisholm // Generated original version of source code. // //****************************************************************************************************** using System; using GSF.IO.FileStructure.Media; using GSF.IO.Unmanaged; namespace GSF.IO.FileStructure { public partial class SubFileStream { /// <summary> /// An IoSession for the sub file stream. /// </summary> private unsafe class IoSession : BinaryStreamIoSessionBase { #region [ Members ] /// <summary> /// The address parser /// </summary> private IndexParser m_parser; /// <summary> /// The shadow copier if the address translation allows for editing. /// </summary> private ShadowCopyAllocator m_pager; private readonly SubFileStream m_stream; /// <summary> /// Contains the read/write buffer. /// </summary> private SubFileDiskIoSessionPool m_ioSessions; private bool m_disposed; private readonly bool m_isReadOnly; private readonly int m_blockDataLength; private readonly uint m_lastEditedBlock; #endregion #region [ Constructors ] public IoSession(SubFileStream stream) { m_stream = stream; m_lastEditedBlock = stream.m_dataReader.LastCommittedHeader.LastAllocatedBlock; m_isReadOnly = stream.m_isReadOnly; m_blockDataLength = m_stream.m_blockSize - FileStructureConstants.BlockFooterLength; m_ioSessions = new SubFileDiskIoSessionPool(stream.m_dataReader, stream.m_fileHeaderBlock, stream.m_subFile, stream.m_isReadOnly); if (m_isReadOnly) { m_parser = new IndexParser(m_ioSessions); } else { m_pager = new ShadowCopyAllocator(m_ioSessions); m_parser = m_pager; } } #endregion #region [ Properties ] private DiskIoSession DataIoSession => m_ioSessions.SourceData; #endregion #region [ Methods ] /// <summary> /// Releases the unmanaged resources used by the <see cref="IoSession"/> object and optionally releases the managed resources. /// </summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { if (!m_disposed) { try { // This will be done regardless of whether the object is finalized or disposed. if (disposing) { if (m_ioSessions != null) { m_ioSessions.Dispose(); m_ioSessions = null; } // This will be done only when the object is disposed by calling Dispose(). } } finally { m_parser = null; m_pager = null; m_disposed = true; // Prevent duplicate dispose. base.Dispose(disposing); // Call base class Dispose(). } } } /// <summary> /// Sets the current usage of the <see cref="BinaryStreamIoSessionBase"/> to null. /// </summary> public override void Clear() { if (IsDisposed || m_ioSessions.IsDisposed) throw new ObjectDisposedException(GetType().FullName); m_ioSessions.Clear(); } public void ClearIndexCache(IndexParser mostRecentParser) { if (IsDisposed || m_ioSessions.IsDisposed) throw new ObjectDisposedException(GetType().FullName); m_parser.ClearIndexCache(mostRecentParser); } public override void GetBlock(BlockArguments args) { int blockDataLength = m_blockDataLength; long pos = args.Position; if (IsDisposed || m_ioSessions.IsDisposed) throw new ObjectDisposedException(GetType().FullName); if (pos < 0) throw new ArgumentOutOfRangeException("position", "cannot be negative"); if (pos >= blockDataLength * (uint.MaxValue - 1)) throw new ArgumentOutOfRangeException("position", "position reaches past the end of the file."); uint physicalBlockIndex; uint indexPosition; if (pos <= uint.MaxValue) //64-bit divide is 2 times slower indexPosition = (uint)pos / (uint)blockDataLength; else indexPosition = (uint)((ulong)pos / (ulong)blockDataLength); //64-bit signed divide is twice as slow as 64-bit unsigned. args.FirstPosition = indexPosition * blockDataLength; args.Length = blockDataLength; if (args.IsWriting) { //Writing if (m_isReadOnly) throw new Exception("File is read only"); physicalBlockIndex = m_pager.VirtualToShadowPagePhysical(indexPosition, out bool wasShadowPaged); if (wasShadowPaged) m_stream.ClearIndexNodeCache(this, m_parser); if (physicalBlockIndex == 0) throw new Exception("Failure to shadow copy the page."); DataIoSession.WriteToExistingBlock(physicalBlockIndex, BlockType.DataBlock, indexPosition); args.FirstPointer = (IntPtr)DataIoSession.Pointer; args.SupportsWriting = true; } else { //Reading physicalBlockIndex = m_parser.VirtualToPhysical(indexPosition); if (physicalBlockIndex <= 0) throw new Exception("Page does not exist"); DataIoSession.Read(physicalBlockIndex, BlockType.DataBlock, indexPosition); args.FirstPointer = (IntPtr)DataIoSession.Pointer; args.SupportsWriting = !m_isReadOnly && physicalBlockIndex > m_lastEditedBlock; } } #endregion } } }
40.315
146
0.52313
[ "MIT" ]
GridProtectionAlliance/openHistorian
Source/Libraries/GSF.SortedTreeStore/IO/FileStructure/SubFileStream_IoSession.cs
8,066
C#
namespace Monochrome.GUI.Controls { public class CheckButton : Button { } }
12.571429
37
0.659091
[ "MIT" ]
Zumorica/Monochrome.GUI
Controls/CheckButton.cs
88
C#
namespace ACR_SyncTool.DockerClient.OAuth; internal class OAuthToken { [JsonPropertyName("token")] public string Token { get; set; } = string.Empty; //[JsonPropertyName("access_token")] //public string AccessToken { get; set; } //[JsonPropertyName("expires_in")] //public int ExpiresIn { get; set; } //[JsonPropertyName("issued_at")] //public DateTime IssuedAt { get; set; } }
25.8125
53
0.668281
[ "MIT" ]
IvanJosipovic/ACR-SyncTool
src/DockerClient/OAuth/OAuthToken.cs
415
C#
using System; using System.Threading.Tasks; using AspNetRateLimit.Common.Models; using AspNetRateLimit.Common.Store; using Microsoft.Extensions.Caching.Distributed; using Newtonsoft.Json; namespace AspNetCoreRateLimit.Store { public class DistributedCacheRateLimitCounterStore : IRateLimitCounterStore { private readonly IDistributedCache _memoryCache; public DistributedCacheRateLimitCounterStore(IDistributedCache memoryCache) { _memoryCache = memoryCache; } public async Task<RateLimitResult> AddRequestAsync(string id, RateLimitRule rule) { // TODO: REQUIRES REVIEW // RateLimitCounter should not be serialised to distributed cache. // Directly store underlying data to facilitate atomic distributed updates. // REDIS example: http://tech.domain.com.au/2017/11/protect-your-api-resources-with-rate-limiting/ var counter = await GetAsync(id); if (counter == null) { counter = new RateLimitCounter(rule.UseSlidingExpiration, rule.PeriodTimeSpan); await SetAsync(id, counter, rule.PeriodTimeSpan, rule.UseSlidingExpiration); return new RateLimitResult { Success = true, Remaining = rule.Limit - 1, Expiry = DateTime.UtcNow.Add(rule.PeriodTimeSpan) }; } return counter.AddRequest(rule.Limit); } private async Task<RateLimitCounter> GetAsync(string id) { var stored = await _memoryCache.GetStringAsync(id); return !string.IsNullOrEmpty(stored) ? JsonConvert.DeserializeObject<RateLimitCounter>(stored) : null; } private async Task SetAsync(string id, RateLimitCounter counter, TimeSpan expirationPeriod, bool slidingExpiration) { var options = new DistributedCacheEntryOptions(); if (slidingExpiration) { options.SetSlidingExpiration(expirationPeriod); } else { options.SetAbsoluteExpiration(expirationPeriod); } await _memoryCache.SetStringAsync(id, JsonConvert.SerializeObject(counter), options); } } }
36
123
0.622475
[ "MIT" ]
stuarthunter/AspNetCoreRateLimit
src/AspNetCoreRateLimit/Store/DistributedCacheRateLimitCounterStore.cs
2,378
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using UFO.Server.Domain; namespace UFO.Commander.ViewModels { public class CategoryViewModel { private Category category; public string Id => category?.CategoryId; public string Name => category?.Name; public CategoryViewModel(Category c) { category = c; } public override string ToString() { return Name; } } }
18.1
49
0.618785
[ "Apache-2.0" ]
untitled-no1/ufo
ufo/UFO.Server/UFO.Commander/ViewModels/CategoryViewModel.cs
545
C#
using System.Linq; using UnhollowerRuntimeLib.XrefScans; namespace ml_lme { static class MethodsResolver { static System.Reflection.MethodInfo ms_isInVR = null; static System.Reflection.MethodInfo ms_setAvatarIntParam = null; static System.Reflection.MethodInfo ms_setAvatarFloatParam = null; static System.Reflection.MethodInfo ms_setAvatarBoolParam = null; public static void ResolveMethods() { // static bool VRCTrackingManager.IsInVR() if(ms_isInVR == null) { var l_methodsList = typeof(VRCTrackingManager).GetMethods().Where(m => m.Name.StartsWith("Method_Public_Static_Boolean_") && (m.ReturnType == typeof(bool)) && !m.GetParameters().Any() && (XrefScanner.UsedBy(m).Where(x => (x.Type == XrefType.Method) && (x.TryResolve()?.DeclaringType == typeof(AvatarDebugConsole))).Count() > 1) && XrefScanner.UsedBy(m).Where(x => (x.Type == XrefType.Method) && (x.TryResolve()?.DeclaringType == typeof(VRCFlowManager))).Any() && XrefScanner.UsedBy(m).Where(x => (x.Type == XrefType.Method) && (x.TryResolve()?.DeclaringType == typeof(SpawnManager))).Any() ); if(l_methodsList.Any()) { ms_isInVR = l_methodsList.First(); Logger.DebugMessage("VRCTrackingManager.IsInVR -> VRCTrackingManager." + ms_isInVR.Name); } else Logger.Warning("Can't resolve VRCTrackingManager.IsInVR"); } // void AvatarPlayableController.SetAvatarIntParam(int paramHash, int val) if(ms_setAvatarIntParam == null) { var l_methodsList = typeof(AvatarPlayableController).GetMethods().Where(m => m.Name.StartsWith("Method_Public_Void_Int32_Int32_") && (m.ReturnType == typeof(void)) && (m.GetParameters().Count() == 2) && XrefScanner.XrefScan(m).Where(x => (x.Type == XrefType.Method) && (x.TryResolve()?.DeclaringType == typeof(VRC.Playables.AvatarParameter))).Any() && XrefScanner.UsedBy(m).Where(x => (x.Type == XrefType.Method) && (x.TryResolve()?.DeclaringType == typeof(AvatarAnimParamController))).Any() && XrefScanner.UsedBy(m).Where(x => (x.Type == XrefType.Method) && (x.TryResolve()?.DeclaringType == typeof(AvatarPlayableController))).Any() && XrefScanner.UsedBy(m).Where(x => (x.Type == XrefType.Method) && (x.TryResolve()?.DeclaringType == typeof(JawController))).Any() && XrefScanner.UsedBy(m).Where(x => (x.Type == XrefType.Method) && (x.TryResolve()?.DeclaringType == typeof(OVRLipSyncContextPlayableParam))).Any() ); if(l_methodsList.Any()) { ms_setAvatarIntParam = l_methodsList.First(); Logger.DebugMessage("AvatarPlayableController.SetAvatarIntParam -> AvatarPlayableController." + ms_setAvatarIntParam.Name); } else Logger.Warning("Can't resolve AvatarPlayableController.SetAvatarIntParam"); } // void AvatarPlayableController.SetAvatarFloatParam(int paramHash, float val, bool debug = false) if(ms_setAvatarFloatParam == null) { var l_methodsList = typeof(AvatarPlayableController).GetMethods().Where(m => m.Name.StartsWith("Method_Public_Void_Int32_Single_Boolean_") && (m.ReturnType == typeof(void)) && (m.GetParameters().Count() == 3) && XrefScanner.XrefScan(m).Where(x => (x.Type == XrefType.Method) && (x.TryResolve()?.DeclaringType == typeof(VRC.Playables.AvatarParameter))).Any() && XrefScanner.UsedBy(m).Where(x => (x.Type == XrefType.Method) && (x.TryResolve()?.DeclaringType == typeof(AvatarAnimParamController))).Any() && XrefScanner.UsedBy(m).Where(x => (x.Type == XrefType.Method) && (x.TryResolve()?.DeclaringType == typeof(AvatarPlayableController))).Any() ); if(l_methodsList.Any()) { ms_setAvatarFloatParam = l_methodsList.First(); Logger.DebugMessage("AvatarPlayableController.SetAvatarFloatParam -> AvatarPlayableController." + ms_setAvatarFloatParam.Name); } else Logger.Warning("Can't resolve AvatarPlayableController.SetAvatarFloatParam"); } // void AvatarPlayableController.SetAvatarBoolParam(int paramHash, bool val) if(ms_setAvatarBoolParam == null) { var l_methodsList = typeof(AvatarPlayableController).GetMethods().Where(m => m.Name.StartsWith("Method_Public_Void_Int32_Boolean_") && (m.ReturnType == typeof(void)) && (m.GetParameters().Count() == 2) && !XrefScanner.XrefScan(m).Where(x => (x.Type == XrefType.Method) && (x.TryResolve()?.DeclaringType == typeof(UnityEngine.Playables.PlayableExtensions))).Any() && XrefScanner.XrefScan(m).Where(x => (x.Type == XrefType.Method) && (x.TryResolve()?.DeclaringType == typeof(VRC.Playables.AvatarParameter))).Any() && XrefScanner.UsedBy(m).Where(x => (x.Type == XrefType.Method) && (x.TryResolve()?.DeclaringType == typeof(AvatarAnimParamController))).Any() && XrefScanner.UsedBy(m).Where(x => (x.Type == XrefType.Method) && (x.TryResolve()?.DeclaringType == typeof(AvatarPlayableController))).Any() ); if(l_methodsList.Any()) { ms_setAvatarBoolParam = l_methodsList.First(); Logger.DebugMessage("AvatarPlayableController.SetAvatarBoolParam -> AvatarPlayableController." + ms_setAvatarBoolParam.Name); } else Logger.Warning("Can't resolve AvatarPlayableController.SetAvatarBoolParam"); } } public static System.Reflection.MethodInfo IsInVR { get => ms_isInVR; } public static System.Reflection.MethodInfo SetAvatarIntParam { get => ms_setAvatarIntParam; } public static System.Reflection.MethodInfo SetAvatarFloatParam { get => ms_setAvatarFloatParam; } public static System.Reflection.MethodInfo SetAvatarBoolParam { get => ms_setAvatarBoolParam; } } }
57.241379
180
0.594729
[ "MIT" ]
nonce-twice/ml_mods
ml_lme/MethodsResolver.cs
6,642
C#
namespace Bio.Algorithms.Alignment { /// <summary> /// Implements the pair-wise overlap alignment algorithm described in Chapter 2 of /// Biological Sequence Analysis; Durbin, Eddy, Krogh and Mitchison; Cambridge Press; 1998. /// </summary> public class PairwiseOverlapAligner : DynamicProgrammingPairwiseAligner { /// <summary> /// Gets the name of the current Alignment algorithm used. /// This is a overridden property from the abstract parent. /// This property returns the Name of our algorithm i.e /// pair-wise-Overlap algorithm. /// </summary> public override string Name { get { return Properties.Resource.PAIRWISE_NAME; } } /// <summary> /// Gets the description of the pair-wise-Overlap algorithm used. /// This is a overridden property from the abstract parent. /// This property returns a simple description of what /// PairwiseOverlapAligner class implements. /// </summary> public override string Description { get { return Properties.Resource.PAIRWISE_DESCRIPTION; } } /// <summary> /// Creates the Simple aligner job /// </summary> /// <param name="sequenceA">First aligned sequence</param> /// <param name="sequenceB">Second aligned sequence</param> /// <returns></returns> protected override DynamicProgrammingPairwiseAlignerJob CreateSimpleAlignmentJob(ISequence sequenceA, ISequence sequenceB) { return new PairwiseOverlapSimpleAlignmentJob(this.SimilarityMatrix, this.GapOpenCost, sequenceA, sequenceB); } /// <summary> /// Creates the Affine aligner job /// </summary> /// <param name="sequenceA">First aligned sequence</param> /// <param name="sequenceB">Second aligned sequence</param> /// <returns></returns> protected override DynamicProgrammingPairwiseAlignerJob CreateAffineAlignmentJob(ISequence sequenceA, ISequence sequenceB) { return new PairwiseOverlapAffineAlignmentJob(this.SimilarityMatrix, this.GapOpenCost, this.GapExtensionCost, sequenceA, sequenceB); } } }
42
143
0.648589
[ "Apache-2.0" ]
dotnetbio/bio
Source/Bio.Core/Algorithms/Alignment/PairwiseOverlapAligner.cs
2,270
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="TableToJsonTableMapper.cs" company="PicklesDoc"> // Copyright 2011 Jeffrey Cameron // Copyright 2012-present PicklesDoc team and community contributors // // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using PicklesDoc.Pickles.ObjectModel; namespace PicklesDoc.Pickles.DocumentationBuilders.Json.Mapper { public class TableToJsonTableMapper { private readonly TableRowToJsonTableRowMapper tableRowMapper; private readonly TableRowToJsonTableHeaderMapper tableHeaderMapper; public TableToJsonTableMapper() { this.tableRowMapper = new TableRowToJsonTableRowMapper(); this.tableHeaderMapper = new TableRowToJsonTableHeaderMapper(); } public JsonTable Map(Table table) { if (table == null) { return null; } return new JsonTable { HeaderRow = this.tableHeaderMapper.Map(table.HeaderRow), DataRows = (table.DataRows ?? new List<TableRow>()).Select(this.tableRowMapper.Map).ToList() }; } } }
36.666667
121
0.594444
[ "Apache-2.0" ]
Lordsauron/pickles
src/Pickles/Pickles.DocumentationBuilders.Json/Mapper/TableToJsonTableMapper.cs
1,982
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // La información general sobre un ensamblado se controla mediante el siguiente // conjunto de atributos. Cambie los valores de estos atributos para modificar la información // asociada a un ensamblado. [assembly: AssemblyTitle("QuieroPizza.Web")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("QuieroPizza.Web")] [assembly: AssemblyCopyright("Copyright © 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Si ComVisible se establece en false, los componentes COM no verán los // tipos de este ensamblado. Si necesita obtener acceso a un tipo de este ensamblado desde // COM, establezca el atributo ComVisible en true en este tipo. [assembly: ComVisible(false)] // El siguiente GUID es para el Id. typelib cuando este proyecto esté expuesto a COM [assembly: Guid("c8c59cfe-bdf3-47c8-8dcd-fc390b0151e8")] // La información de versión de un ensamblado consta de los siguientes cuatro valores: // // Versión principal // Versión secundaria // Número de compilación // Revisión // // Puede especificar todos los valores o usar los valores predeterminados de número de compilación y de revisión // mediante el carácter '*', como se muestra a continuación: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
42.055556
114
0.743065
[ "MIT" ]
Dannygarcia7/quieropizza
QuieroPizza/QuieroPizza.Web/Properties/AssemblyInfo.cs
1,533
C#
// #[license] // SmartsheetClient SDK for C# // %% // Copyright (C) 2014 SmartsheetClient // %% // 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. // %[license] using System; namespace Smartsheet.Api.Models { /// <summary> /// Represents the Workspace object which is an area in which Sheets, reports, Templates and sub-Folders can be /// organized, similar to a folder. </summary> /// <seealso href="http://help.Smartsheet.com/customer/portal/articles/506687-creating-a-workspace">Help Creating a /// Workspace</seealso> public class Workspace : Folder { /// <summary> /// Represents the user's permissions on a workspace. </summary> private AccessLevel? accessLevel; /// <summary> /// Gets the user's permissions on a workspace. /// </summary> /// <returns> the access level </returns> public AccessLevel? AccessLevel { get { return accessLevel; } set { accessLevel = value; } } /// <summary> /// A convenience class for creating a <seealso cref="Workspace"/> object with the appropriate fields for updating a workspace. /// </summary> public class UpdateWorkspaceBuilder { private long? id; private string workspaceName; /// <summary> /// Build workspace with required parameter name. /// </summary> /// <param name="id">the id of the workspace</param> /// <param name="name">the name of the workspace</param> public UpdateWorkspaceBuilder(long? id, string name) { this.id = id; this.workspaceName = name; } /// <summary> /// Builds the <seealso cref="Workspace"/>. /// </summary> /// <returns> the workspace </returns> public Workspace Build() { Workspace workspace = new Workspace(); workspace.Id = id; workspace.Name = workspaceName; return workspace; } } /// <summary> /// A convenience class for creating a <seealso cref="Workspace"/> object with the appropriate fields for creating a workspace. /// </summary> public class CreateWorkspaceBuilder { private string workspaceName; /// <summary> /// Sets the required parameters to create a Workspace. /// </summary> /// <param name="name">the name of the workspace</param> public CreateWorkspaceBuilder(string name) { this.workspaceName = name; } /// <summary> /// Builds the <seealso cref="Workspace"/>. /// </summary> /// <returns> the workspace </returns> public Workspace Build() { Workspace workspace = new Workspace(); workspace.Name = workspaceName; return workspace; } } } }
35.864078
135
0.556849
[ "Apache-2.0" ]
JTP3XP/smartsheet-csharp-sdk
main/Smartsheet/Api/Models/Workspace.cs
3,696
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Engine.Platform; using Engine; namespace MyGUIPlugin { public class DoubleNumericEdit { public event MyGUIEvent ValueChanged; private EditBox edit; private String lastCaption; private Double minValue; private Double maxValue; private Double keyFocusValue = 0; private bool hasKeyFocus = false; public DoubleNumericEdit(EditBox edit) { this.edit = edit; lastCaption = edit.Caption; edit.EventEditTextChange += new MyGUIEvent(edit_EventEditTextChange); edit.MouseWheel += new MyGUIEvent(edit_MouseWheel); edit.ClientWidget.MouseWheel += new MyGUIEvent(edit_MouseWheel); edit.KeyLostFocus += new MyGUIEvent(edit_KeyLostFocus); edit.KeySetFocus += new MyGUIEvent(edit_KeySetFocus); edit.EventEditSelectAccept += new MyGUIEvent(edit_EventEditSelectAccept); edit.AllowMouseScroll = false; Increment = 1; FireValueChangedOnType = false; //MinValue String userString = edit.getUserString("MinValue"); if (userString == null || !NumberParser.TryParse(userString, out minValue)) { minValue = Double.MinValue; } //MaxValue userString = edit.getUserString("MaxValue"); if (userString == null || !NumberParser.TryParse(userString, out maxValue)) { maxValue = Double.MaxValue; } } public DoubleNumericEdit(EditBox edit, Button upButton, Button downButton) :this(edit) { upButton.MouseButtonClick += new MyGUIEvent(upButton_MouseButtonClick); downButton.MouseButtonClick += new MyGUIEvent(downButton_MouseButtonClick); } void edit_EventEditTextChange(Widget source, EventArgs e) { String currentCaption = edit.Caption; Double value = 0; if (currentCaption != String.Empty && currentCaption != ".") { if (currentCaption == "-") { if (minValue >= 0) { edit.Caption = lastCaption; } } else if (NumberParser.TryParse(currentCaption, out value)) { if (value >= minValue && value <= maxValue) { if (FireValueChangedOnType) { fireValueChanged(); } } else { edit.Caption = lastCaption; } } else { edit.Caption = lastCaption; } } lastCaption = edit.Caption; } public Double Value { get { Double value = 0; NumberParser.TryParse(edit.Caption, out value); return value; } set { if (value >= minValue && value <= maxValue) { edit.Caption = value.ToString(); lastCaption = edit.Caption; } } } public Double MinValue { get { return minValue; } set { minValue = value; } } public Double MaxValue { get { return maxValue; } set { maxValue = value; } } public Double Increment { get; set; } public EditBox Edit { get { return edit; } } /// <summary> /// Determines if the ValueChanged event is fired as the user types. Default: false. /// </summary> public bool FireValueChangedOnType { get; set; } void downButton_MouseButtonClick(Widget source, EventArgs e) { Double newVal = Value - Increment; if (newVal < minValue) { newVal = minValue; } Value = newVal; fireValueChanged(); } void upButton_MouseButtonClick(Widget source, EventArgs e) { Double newVal = Value + Increment; if (newVal > maxValue) { newVal = maxValue; } Value = newVal; fireValueChanged(); } void edit_MouseWheel(Widget source, EventArgs e) { if (hasKeyFocus) { MouseEventArgs me = (MouseEventArgs)e; int wheelDelta = me.RelativeWheelPosition > 0 ? 1 : -1; Double newVal = Value + Increment * wheelDelta; if (newVal > maxValue) { newVal = maxValue; } else if (newVal < minValue) { newVal = minValue; } Value = newVal; fireValueChanged(); } } private void fireValueChanged() { if (ValueChanged != null) { ValueChanged.Invoke(edit, EventArgs.Empty); } } void edit_KeySetFocus(Widget source, EventArgs e) { keyFocusValue = Value; hasKeyFocus = true; } void edit_KeyLostFocus(Widget source, EventArgs e) { if (Value != keyFocusValue) { fireValueChanged(); } hasKeyFocus = false; } void edit_EventEditSelectAccept(Widget source, EventArgs e) { if (Value != keyFocusValue) { fireValueChanged(); keyFocusValue = Value; } } } }
29.183036
93
0.443476
[ "MIT" ]
AnomalousMedical/Engine
MyGUIPlugin/Plugin/Widgets/NumericEdits/DoubleNumericEdit.cs
6,539
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Threading.Tasks; using RockLibVerifier = RockLib.Logging.AspNetCore.Analyzers.Test.CSharpCodeFixVerifier< RockLib.Logging.AspNetCore.Analyzers.AddInfoLogAttributeAnalyzer, RockLib.Logging.AspNetCore.Analyzers.AddInfoLogAttributeCodeFixProvider>; namespace RockLib.Logging.AspNetCore.Analyzers.Test { [TestClass] public class AddInfoLogAttributeCodeFixProviderTests { [TestMethod] public async Task CodeFix1() { await RockLibVerifier.VerifyCodeFixAsync(@" using Microsoft.AspNetCore.Mvc; namespace UnitTestingNamespace { [ApiController] [Route(""[controller]"")] public class [|TestController|] : ControllerBase { } } ", @" using Microsoft.AspNetCore.Mvc; using RockLib.Logging.AspNetCore; namespace UnitTestingNamespace { [ApiController] [Route(""[controller]"")] [InfoLog] public class TestController : ControllerBase { } } "); } [TestMethod] public async Task CodeFix2() { await RockLibVerifier.VerifyCodeFixAsync(@" using Microsoft.AspNetCore.Mvc; using RockLib.Logging.AspNetCore; namespace UnitTestingNamespace { [ApiController] [Route(""[controller]"")] public class TestController : ControllerBase { [HttpGet] [InfoLog] public string Get() { return ""Get""; } [HttpPut] public string [|Put|]() { return ""Put""; } [HttpPost] public string [|Post|]() { return ""Post""; } } } ", @" using Microsoft.AspNetCore.Mvc; using RockLib.Logging.AspNetCore; namespace UnitTestingNamespace { [ApiController] [Route(""[controller]"")] public class TestController : ControllerBase { [HttpGet] [InfoLog] public string Get() { return ""Get""; } [HttpPut] [InfoLog] public string Put() { return ""Put""; } [HttpPost] [InfoLog] public string Post() { return ""Post""; } } } "); } } }
20.189189
88
0.593039
[ "MIT" ]
RockLib/RockLib.Analyzers
Logging.AspNetCore/RockLib.Logging.AspNetCore.Analyzers.Test/AddInfoLogAttributeCodeFixProviderTests.cs
2,243
C#