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 |
|---|---|---|---|---|---|---|---|---|
// 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.CloudService.Models.Api20210301
{
using static Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Extensions;
/// <summary>An IP Configuration of the private endpoint.</summary>
public partial class PrivateEndpointIPConfiguration
{
/// <summary>
/// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonObject json);
/// <summary>
/// <c>AfterToJson</c> will be called after the json erialization has finished, allowing customization of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonObject"
/// /> before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonObject container);
/// <summary>
/// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of
/// the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
/// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonObject json, ref bool returnNow);
/// <summary>
/// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the
/// object before it is serialized.
/// If you wish to disable the default serialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonObject container, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.IPrivateEndpointIPConfiguration.
/// </summary>
/// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonNode" /> to deserialize from.</param>
/// <returns>
/// an instance of Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.IPrivateEndpointIPConfiguration.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.IPrivateEndpointIPConfiguration FromJson(Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonNode node)
{
return node is Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonObject json ? new PrivateEndpointIPConfiguration(json) : null;
}
/// <summary>
/// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonObject into a new instance of <see cref="PrivateEndpointIPConfiguration" />.
/// </summary>
/// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonObject instance to deserialize from.</param>
internal PrivateEndpointIPConfiguration(Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonObject json)
{
bool returnNow = false;
BeforeFromJson(json, ref returnNow);
if (returnNow)
{
return;
}
{_property = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonObject>("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.PrivateEndpointIPConfigurationProperties.FromJson(__jsonProperties) : Property;}
{_name = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonString>("name"), out var __jsonName) ? (string)__jsonName : (string)Name;}
{_type = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonString>("type"), out var __jsonType) ? (string)__jsonType : (string)Type;}
{_etag = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonString>("etag"), out var __jsonEtag) ? (string)__jsonEtag : (string)Etag;}
AfterFromJson(json);
}
/// <summary>
/// Serializes this instance of <see cref="PrivateEndpointIPConfiguration" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonNode" />.
/// </summary>
/// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonObject"/> container to serialize this object into. If the caller
/// passes in <c>null</c>, a new instance will be created and returned to the caller.</param>
/// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.SerializationMode"/>.</param>
/// <returns>
/// a serialized instance of <see cref="PrivateEndpointIPConfiguration" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonNode" />.
/// </returns>
public Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.SerializationMode serializationMode)
{
container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonObject();
bool returnNow = false;
BeforeToJson(ref container, ref returnNow);
if (returnNow)
{
return container;
}
AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add );
AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add );
if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.SerializationMode.IncludeReadOnly))
{
AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add );
}
if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.SerializationMode.IncludeReadOnly))
{
AddIf( null != (((object)this._etag)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonString(this._etag.ToString()) : null, "etag" ,container.Add );
}
AfterToJson(ref container);
return container;
}
}
} | 75.830508 | 309 | 0.699933 | [
"MIT"
] | Agazoth/azure-powershell | src/CloudService/generated/api/Models/Api20210301/PrivateEndpointIPConfiguration.json.cs | 8,831 | C# |
// <auto-generated />
using System;
using BankruptcyLaw.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace BankruptcyLaw.Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20201112224434_RemovedExtraPhonePropertyFromUsers")]
partial class RemovedExtraPhonePropertyFromUsers
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.1.9")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("BankruptcyLaw.Data.Models.ApplicationRole", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("Name")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("IsDeleted");
b.HasIndex("NormalizedName")
.IsUnique()
.HasName("RoleNameIndex")
.HasFilter("[NormalizedName] IS NOT NULL");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("BankruptcyLaw.Data.Models.ApplicationUser", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<int>("AccessFailedCount")
.HasColumnType("int");
b.Property<int>("AddressId")
.HasColumnType("int");
b.Property<string>("AttorneyUserId")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClientUserId")
.HasColumnType("nvarchar(max)");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<string>("Email")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<bool>("EmailConfirmed")
.HasColumnType("bit");
b.Property<string>("FirstName")
.IsRequired()
.HasColumnType("nvarchar(50)")
.HasMaxLength(50);
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<string>("LastName")
.IsRequired()
.HasColumnType("nvarchar(50)")
.HasMaxLength(50);
b.Property<bool>("LockoutEnabled")
.HasColumnType("bit");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("datetimeoffset");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("NormalizedEmail")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(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")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("AddressId");
b.HasIndex("IsDeleted");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex")
.HasFilter("[NormalizedUserName] IS NOT NULL");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("BankruptcyLaw.Data.Models.Judge", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("CourtRoom")
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<string>("Email")
.HasColumnType("nvarchar(max)");
b.Property<string>("FirstName")
.IsRequired()
.HasColumnType("nvarchar(50)")
.HasMaxLength(50);
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<string>("LastName")
.IsRequired()
.HasColumnType("nvarchar(50)")
.HasMaxLength(50);
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("Phone")
.IsRequired()
.HasColumnType("nvarchar(30)")
.HasMaxLength(30);
b.HasKey("Id");
b.HasIndex("IsDeleted");
b.ToTable("Judges");
});
modelBuilder.Entity("BankruptcyLaw.Data.Models.MyDbModels.Address", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("City")
.IsRequired()
.HasColumnType("nvarchar(50)")
.HasMaxLength(50);
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("State")
.IsRequired()
.HasColumnType("nvarchar(30)")
.HasMaxLength(30);
b.Property<string>("StreetAddress")
.IsRequired()
.HasColumnType("nvarchar(100)")
.HasMaxLength(100);
b.Property<int>("ZipCode")
.HasColumnType("int")
.HasMaxLength(30);
b.HasKey("Id");
b.HasIndex("IsDeleted");
b.ToTable("Addresses");
});
modelBuilder.Entity("BankruptcyLaw.Data.Models.MyDbModels.Attorney", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<string>("AplicationUserId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.HasKey("Id");
b.HasIndex("AplicationUserId")
.IsUnique();
b.HasIndex("IsDeleted");
b.ToTable("Attorneys");
});
modelBuilder.Entity("BankruptcyLaw.Data.Models.MyDbModels.Case", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<string>("AttorneyId")
.HasColumnType("nvarchar(450)");
b.Property<string>("CaseNumber")
.HasColumnType("nvarchar(max)");
b.Property<int>("CaseStatus")
.HasColumnType("int");
b.Property<string>("ClientId")
.HasColumnType("nvarchar(450)");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime>("DateFiled")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<int>("JudgeId")
.HasColumnType("int");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<int>("TrusteeId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("AttorneyId");
b.HasIndex("ClientId");
b.HasIndex("IsDeleted");
b.HasIndex("JudgeId");
b.HasIndex("TrusteeId");
b.ToTable("Cases");
});
modelBuilder.Entity("BankruptcyLaw.Data.Models.MyDbModels.Client", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<string>("AplicationUserId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("SSN")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("AplicationUserId")
.IsUnique();
b.HasIndex("IsDeleted");
b.ToTable("Clients");
});
modelBuilder.Entity("BankruptcyLaw.Data.Models.MyDbModels.ClientDocument", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<string>("CaseId")
.HasColumnType("nvarchar(450)");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<string>("Extension")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(200)")
.HasMaxLength(200);
b.HasKey("Id");
b.HasIndex("CaseId");
b.HasIndex("IsDeleted");
b.ToTable("ClientDocuments");
});
modelBuilder.Entity("BankruptcyLaw.Data.Models.MyDbModels.CourtDocument", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<string>("AddedByUserId")
.HasColumnType("nvarchar(450)");
b.Property<string>("CaseId")
.HasColumnType("nvarchar(450)");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime>("DateIssued")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<string>("Extension")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(200)")
.HasMaxLength(200);
b.HasKey("Id");
b.HasIndex("AddedByUserId");
b.HasIndex("CaseId");
b.HasIndex("IsDeleted");
b.ToTable("CourtDocuments");
});
modelBuilder.Entity("BankruptcyLaw.Data.Models.MyDbModels.Creditor", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("AddressId")
.HasColumnType("int");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<string>("Email")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Phone")
.HasColumnType("nvarchar(30)")
.HasMaxLength(30);
b.HasKey("Id");
b.HasIndex("AddressId");
b.HasIndex("IsDeleted");
b.ToTable("Creditors");
});
modelBuilder.Entity("BankruptcyLaw.Data.Models.MyDbModels.CreditorCase", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<int>("CaseId")
.HasColumnType("int");
b.Property<string>("CaseId1")
.HasColumnType("nvarchar(450)");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<int>("CreditorId")
.HasColumnType("int");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.HasKey("Id");
b.HasIndex("CaseId1");
b.HasIndex("CreditorId");
b.ToTable("CreditorCases");
});
modelBuilder.Entity("BankruptcyLaw.Data.Models.MyDbModels.Hearing", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("AddressId")
.HasColumnType("int");
b.Property<string>("AttorneyId")
.HasColumnType("nvarchar(450)");
b.Property<string>("CaseId")
.HasColumnType("nvarchar(450)");
b.Property<int?>("ContinuedHearingId")
.HasColumnType("int");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<DateTime>("HearingDateAndTime")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<int?>("Outcome")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("AddressId");
b.HasIndex("AttorneyId");
b.HasIndex("CaseId");
b.HasIndex("ContinuedHearingId");
b.HasIndex("IsDeleted");
b.ToTable("Hearings");
});
modelBuilder.Entity("BankruptcyLaw.Data.Models.MyDbModels.Note", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<string>("CaseId")
.HasColumnType("nvarchar(450)");
b.Property<string>("Content")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("OriginalPoster")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("RedactionPoster")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("CaseId");
b.HasIndex("IsDeleted");
b.ToTable("Notes");
});
modelBuilder.Entity("BankruptcyLaw.Data.Models.MyDbModels.Trustee", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int?>("AddressId")
.HasColumnType("int");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<string>("Email")
.HasColumnType("nvarchar(max)");
b.Property<string>("FirstName")
.IsRequired()
.HasColumnType("nvarchar(50)")
.HasMaxLength(50);
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<string>("LasttName")
.IsRequired()
.HasColumnType("nvarchar(50)")
.HasMaxLength(50);
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("Phone")
.IsRequired()
.HasColumnType("nvarchar(30)")
.HasMaxLength(30);
b.HasKey("Id");
b.HasIndex("AddressId");
b.HasIndex("IsDeleted");
b.ToTable("Trustees");
});
modelBuilder.Entity("BankruptcyLaw.Data.Models.Setting", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.Property<string>("Value")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("IsDeleted");
b.ToTable("Settings");
});
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")
.HasColumnType("nvarchar(450)");
b.Property<string>("ProviderKey")
.HasColumnType("nvarchar(450)");
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")
.HasColumnType("nvarchar(450)");
b.Property<string>("Name")
.HasColumnType("nvarchar(450)");
b.Property<string>("Value")
.HasColumnType("nvarchar(max)");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("BankruptcyLaw.Data.Models.ApplicationUser", b =>
{
b.HasOne("BankruptcyLaw.Data.Models.MyDbModels.Address", "Address")
.WithMany()
.HasForeignKey("AddressId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("BankruptcyLaw.Data.Models.MyDbModels.Attorney", b =>
{
b.HasOne("BankruptcyLaw.Data.Models.ApplicationUser", "AplicationUser")
.WithOne("AttorneyUser")
.HasForeignKey("BankruptcyLaw.Data.Models.MyDbModels.Attorney", "AplicationUserId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("BankruptcyLaw.Data.Models.MyDbModels.Case", b =>
{
b.HasOne("BankruptcyLaw.Data.Models.MyDbModels.Attorney", "Attorney")
.WithMany("Cases")
.HasForeignKey("AttorneyId");
b.HasOne("BankruptcyLaw.Data.Models.MyDbModels.Client", "Client")
.WithMany("Cases")
.HasForeignKey("ClientId");
b.HasOne("BankruptcyLaw.Data.Models.Judge", "Judge")
.WithMany("Cases")
.HasForeignKey("JudgeId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("BankruptcyLaw.Data.Models.MyDbModels.Trustee", "Trustee")
.WithMany("Cases")
.HasForeignKey("TrusteeId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("BankruptcyLaw.Data.Models.MyDbModels.Client", b =>
{
b.HasOne("BankruptcyLaw.Data.Models.ApplicationUser", "AplicationUser")
.WithOne("ClientUser")
.HasForeignKey("BankruptcyLaw.Data.Models.MyDbModels.Client", "AplicationUserId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("BankruptcyLaw.Data.Models.MyDbModels.ClientDocument", b =>
{
b.HasOne("BankruptcyLaw.Data.Models.MyDbModels.Case", "Case")
.WithMany("ClientDocuments")
.HasForeignKey("CaseId");
});
modelBuilder.Entity("BankruptcyLaw.Data.Models.MyDbModels.CourtDocument", b =>
{
b.HasOne("BankruptcyLaw.Data.Models.ApplicationUser", "AddedByUser")
.WithMany()
.HasForeignKey("AddedByUserId");
b.HasOne("BankruptcyLaw.Data.Models.MyDbModels.Case", "Case")
.WithMany("CourtDocuments")
.HasForeignKey("CaseId");
});
modelBuilder.Entity("BankruptcyLaw.Data.Models.MyDbModels.Creditor", b =>
{
b.HasOne("BankruptcyLaw.Data.Models.MyDbModels.Address", "Address")
.WithMany()
.HasForeignKey("AddressId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("BankruptcyLaw.Data.Models.MyDbModels.CreditorCase", b =>
{
b.HasOne("BankruptcyLaw.Data.Models.MyDbModels.Case", "Case")
.WithMany("CreditorCases")
.HasForeignKey("CaseId1");
b.HasOne("BankruptcyLaw.Data.Models.MyDbModels.Creditor", "Creditor")
.WithMany("CreditorCases")
.HasForeignKey("CreditorId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("BankruptcyLaw.Data.Models.MyDbModels.Hearing", b =>
{
b.HasOne("BankruptcyLaw.Data.Models.MyDbModels.Address", "Address")
.WithMany()
.HasForeignKey("AddressId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("BankruptcyLaw.Data.Models.MyDbModels.Attorney", null)
.WithMany("Hearings")
.HasForeignKey("AttorneyId");
b.HasOne("BankruptcyLaw.Data.Models.MyDbModels.Case", null)
.WithMany("Hearings")
.HasForeignKey("CaseId");
b.HasOne("BankruptcyLaw.Data.Models.MyDbModels.Hearing", "ContinuedHearing")
.WithMany()
.HasForeignKey("ContinuedHearingId");
});
modelBuilder.Entity("BankruptcyLaw.Data.Models.MyDbModels.Note", b =>
{
b.HasOne("BankruptcyLaw.Data.Models.MyDbModels.Case", null)
.WithMany("Notes")
.HasForeignKey("CaseId");
});
modelBuilder.Entity("BankruptcyLaw.Data.Models.MyDbModels.Trustee", b =>
{
b.HasOne("BankruptcyLaw.Data.Models.MyDbModels.Address", "Address")
.WithMany()
.HasForeignKey("AddressId");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("BankruptcyLaw.Data.Models.ApplicationRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("BankruptcyLaw.Data.Models.ApplicationUser", null)
.WithMany("Claims")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("BankruptcyLaw.Data.Models.ApplicationUser", null)
.WithMany("Logins")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("BankruptcyLaw.Data.Models.ApplicationRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("BankruptcyLaw.Data.Models.ApplicationUser", null)
.WithMany("Roles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("BankruptcyLaw.Data.Models.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
| 36.679878 | 125 | 0.446042 | [
"MIT"
] | Drakojan/BankruptcyLaw | Data/BankruptcyLaw.Data/Migrations/20201112224434_RemovedExtraPhonePropertyFromUsers.Designer.cs | 36,095 | C# |
using System;
using System.Windows.Input;
namespace Beata.Medrek
{
/// <summary>
/// Implementation of the ICommand Interface for
/// Commands to derive from
/// </summary>
public class RelayCommand : ICommand
{
public event EventHandler CanExecuteChanged = (sender, e) => { };
private Action _action;
/// <summary>
/// Default Constructors
/// </summary>
/// <param name="action"></param>
public RelayCommand(Action action)
{
_action = action;
}
/// <summary>
/// CanExecute Command to guide command execution
/// </summary>
/// <param name="parameter"></param>
/// <returns></returns>
public bool CanExecute(object parameter)
{
return true;
}
/// <summary>
/// Execute Command for running action
/// </summary>
/// <param name="parameter"></param>
public void Execute(object parameter)
{
_action();
}
}
}
| 23.8 | 73 | 0.525677 | [
"Unlicense"
] | Godspower99/Beata.Medrek | Beata.Medrek/Commands/RelayCommand.cs | 1,073 | C# |
using Game.Logic.Phy.Object;
namespace Game.Logic.PetEffects.ContinueElement
{
public class CE1206 : BasePetEffect
{
private int m_type = 0;
private int m_count = 0;
private int m_probability = 0;
private int m_delay = 0;
private int m_coldDown = 0;
private int m_added = 0;
private int m_currentId;
public CE1206(int count, int probability, int type, int skillId, int delay, string elementID)
: base(ePetEffectType.CE1206, elementID)
{
m_count = count;
m_coldDown = count;
m_probability = ((probability == -1) ? 10000 : probability);
m_type = type;
m_delay = delay;
m_currentId = skillId;
}
public override bool Start(Living living)
{
CE1206 cE = living.PetEffectList.GetOfType(ePetEffectType.CE1206) as CE1206;
if (cE == null)
{
return base.Start(living);
}
cE.m_probability = ((m_probability > cE.m_probability) ? m_probability : cE.m_probability);
return true;
}
protected override void OnAttachedToPlayer(Player player)
{
player.BeginNextTurn += Player_BeginNextTurn;
player.BeginSelfTurn += Player_BeginSelfTurn;
player.PlayerClearBuffSkillPet += Player_PlayerClearBuffSkillPet;
}
private void Player_PlayerClearBuffSkillPet(Player player)
{
Stop();
}
private void Player_BeginNextTurn(Living living)
{
if (m_added == 0)
{
m_added = 300;
if (living.Defence < (double)m_added)
{
m_added = (int)living.Defence - 1;
}
living.Defence -= m_added;
}
}
private void Player_BeginSelfTurn(Living living)
{
m_count--;
if (m_count < 0)
{
Stop();
}
}
protected override void OnRemovedFromPlayer(Player player)
{
player.Defence += m_added;
m_added = 0;
player.BeginNextTurn -= Player_BeginNextTurn;
player.BeginSelfTurn -= Player_BeginSelfTurn;
}
}
}
| 21.325581 | 95 | 0.686478 | [
"MIT"
] | HuyTruong19x/DDTank4.1 | Source Server/Game.Logic/Game.Logic.PetEffects.ContinueElement/CE1206.cs | 1,834 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("IT.BTS.PC.Base64Decoder")]
[assembly: AssemblyDescription("A BizTalk Pipeline Component designed to decode base64 streams")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Integration.Team")]
[assembly: AssemblyProduct("IT.BTS.PC.Base64Decoder")]
[assembly: AssemblyCopyright("Copyright © Integration.Team 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("4f8e7f7b-94a7-47c2-b500-1a6b71588d2d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 41.916667 | 98 | 0.733598 | [
"Apache-2.0"
] | Integration-Team/IT.BTS.PC.Base64Decoder | Properties/AssemblyInfo.cs | 1,512 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace TencentCloud.Tbaas.V20180416.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class GetTransListHandlerResponse : AbstractModel
{
/// <summary>
/// 总记录数
/// </summary>
[JsonProperty("TotalCount")]
public long? TotalCount{ get; set; }
/// <summary>
/// 当前群组编号
/// </summary>
[JsonProperty("GroupPk")]
public string GroupPk{ get; set; }
/// <summary>
/// 返回数据列表
/// </summary>
[JsonProperty("List")]
public BcosTransInfo[] List{ get; set; }
/// <summary>
/// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
/// </summary>
[JsonProperty("RequestId")]
public string RequestId{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
public override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "TotalCount", this.TotalCount);
this.SetParamSimple(map, prefix + "GroupPk", this.GroupPk);
this.SetParamArrayObj(map, prefix + "List.", this.List);
this.SetParamSimple(map, prefix + "RequestId", this.RequestId);
}
}
}
| 30.584615 | 81 | 0.614688 | [
"Apache-2.0"
] | TencentCloud/tencentcloud-sdk-dotnet | TencentCloud/Tbaas/V20180416/Models/GetTransListHandlerResponse.cs | 2,078 | C# |
using System.Text;
namespace SimplCommerce.Module.PaymentMomo.ViewModels
{
public class StatusRequest
{
private string _secretKey;
public StatusRequest(string secretKey, string partnerCode, string accessKey, long orderId)
{
_secretKey = secretKey;
PartnerCode = partnerCode;
AccessKey = accessKey;
OrderId = orderId.ToString();
RequestId = orderId.ToString();
}
public string PartnerCode { get; private set; }
public string AccessKey { get; private set; }
public string RequestId { get; private set; }
public string OrderId { get; private set; }
public string RequestType
{
get
{
return "transactionStatus";
}
}
public string Signature
{
get
{
var sb = new StringBuilder();
sb.Append($"partnerCode={PartnerCode}");
sb.Append($"&accessKey={AccessKey}");
sb.Append($"&requestId={RequestId}");
sb.Append($"&orderId={OrderId}");
sb.Append($"&requestType={RequestType}");
var message = sb.ToString();
return MomoSecurityHelper.HashSHA256(message, _secretKey);
}
}
}
}
| 27.44 | 98 | 0.530612 | [
"Apache-2.0"
] | 007FFFLearning/SimplDev | src/Modules/SimplCommerce.Module.PaymentMomo/ViewModels/StatusRequest.cs | 1,374 | C# |
namespace LaunchDarkly.Sdk.Server.Integrations
{
/// <summary>
/// Integration between the LaunchDarkly SDK and DynamoDB.
/// </summary>
public static class DynamoDB
{
/// <summary>
/// Name of the partition key that the data store's table must have. You must specify
/// this when you create the table. The key type must be String.
/// </summary>
public const string DataStorePartitionKey = "namespace";
/// <summary>
/// Name of the sort key that the data store's table must have. You must specify this
/// when you create the table. The key type must be String.
/// </summary>
public const string DataStoreSortKey = "key";
/// <summary>
/// Returns a builder object for creating a DynamoDB-backed data store.
/// </summary>
/// <remarks>
/// <para>
/// This can be used either for the main data store that holds feature flag data, or for the big
/// segment store, or both. If you are using both, they do not have to have the same parameters. For
/// instance, in this example the main data store uses a table called "table1" and the big segment
/// store uses a table called "table2":
/// </para>
/// <code>
/// var config = Configuration.Builder("sdk-key")
/// .DataStore(
/// Components.PersistentDataStore(
/// DynamoDB.DataStore("table1")
/// )
/// )
/// .BigSegments(
/// Components.BigSegments(
/// DynamoDB.DataStore("table2")
/// )
/// )
/// .Build();
/// </code>
/// <para>
/// Note that the builder is passed to one of two methods,
/// <see cref="Components.PersistentDataStore(LaunchDarkly.Sdk.Server.Interfaces.IPersistentDataStoreAsyncFactory)"/> or
/// <see cref="Components.BigSegments(LaunchDarkly.Sdk.Server.Interfaces.IBigSegmentStoreFactory)"/>, depending on the context in
/// which it is being used. This is because each of those contexts has its own additional
/// configuration options that are unrelated to the DynamoDB options. For instance, the
/// <see cref="Components.PersistentDataStore(LaunchDarkly.Sdk.Server.Interfaces.IPersistentDataStoreAsyncFactory)"/> builder
/// has options for caching:
/// </para>
/// <code>
/// var config = Configuration.Builder("sdk-key")
/// .DataStore(
/// Components.PersistentDataStore(
/// DynamoDB.DataStore("table1")
/// ).CacheSeconds(15)
/// )
/// .Build();
/// </code>
/// </remarks>
/// <param name="tableName">the DynamoDB table name; this table must already exist</param>
/// <returns>a data store configuration object</returns>
public static DynamoDBDataStoreBuilder DataStore(string tableName) =>
new DynamoDBDataStoreBuilder(tableName);
}
}
| 45.728571 | 137 | 0.56701 | [
"Apache-2.0"
] | launchdarkly/dotnet-server-sdk-dynamodb | src/LaunchDarkly.ServerSdk.DynamoDB/DynamoDB.cs | 3,203 | C# |
using Sort.Strategy;
using System;
using System.Collections.Generic;
namespace Sort.ConcreteStrategy
{
/// <summary>
/// A 'ConcreteStrategy' class
/// </summary>
public class QuickSort : SortStrategy
{
public override void Sort(List<string> list)
{
list.Sort(); // Default is QuickSort
Console.WriteLine("QuickSorted list ");
}
}
}
| 21.421053 | 52 | 0.60688 | [
"MIT"
] | emilia98/Design-Patterns-CSharp | Strategy/Real-World Examples/Strategy_RealWorldExamples/Sort/ConcreteStrategy/QuickSort.cs | 409 | C# |
namespace Photon.Voice.Unity.Demos
{
using UnityEngine;
using UnityEngine.UI;
public class BackgroundMusicController : MonoBehaviour
{
#pragma warning disable 649
[SerializeField]
private Text volumeText;
[SerializeField]
private Slider volumeSlider;
[SerializeField]
private AudioSource audioSource;
[SerializeField]
private float initialVolume = 0.125f;
#pragma warning restore 649
private void Awake()
{
this.volumeSlider.minValue = 0f;
this.volumeSlider.maxValue = 1f;
this.volumeSlider.SetSingleOnValueChangedCallback(this.OnVolumeChanged);
this.volumeSlider.value = this.initialVolume;
this.OnVolumeChanged(this.initialVolume);
}
private void OnVolumeChanged(float newValue)
{
this.volumeText.text = string.Format("BG Volume: {0:0.###}", newValue);
this.audioSource.volume = newValue;
}
}
} | 30.352941 | 84 | 0.624031 | [
"Unlicense"
] | 23SAMY23/Meet-and-Greet-MR | Meet & Greet MR (AR)/Assets/Photon/PhotonVoice/Demos/DemoVoiceUI/Scripts/BackgroundMusicController.cs | 1,034 | C# |
namespace ClassLib063
{
public class Class085
{
public static string Property => "ClassLib063";
}
}
| 15 | 55 | 0.633333 | [
"MIT"
] | 333fred/performance | src/scenarios/weblarge2.0/src/ClassLib063/Class085.cs | 120 | C# |
using System;
namespace CalculadoraLibrary
{
public class Class1
{
}
class Calculadora
{
public void somar(int x, int y)
{
Console.WriteLine($"A soma dos numeros {x} 3 {y} é = {x + y}");
}
public void multiplicar(int x, int y)
{
Console.WriteLine($"O produto dos numeros {x} 3 {y} é = {x + y}");
}
public void subtracao(int x, int y)
{
Console.WriteLine($"A subtraçaõ dos numeros {x} 3 {y} é = {x + y}");
}
public void divisao(int x, int y)
{
if (y < 1)
{
Console.WriteLine("Não é possivel dividir por Zero");
return;
}
Console.WriteLine($"A divisão dos numeros {x} 3 {y} é = {x + y}");
}
}
}
| 20.95 | 80 | 0.460621 | [
"MIT"
] | vilsonmoro/curso-csharp | Solution1/CalculadoraLibrary/Class1.cs | 849 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using UnrealBuildTool;
using System.IO;
public class AirSim : ModuleRules
{
private string ModulePath
{
get { return ModuleDirectory; }
}
private string AirLibPath
{
get { return Path.Combine(ModulePath, "AirLib"); }
}
private string AirSimPluginPath
{
get { return Directory.GetParent(ModulePath).FullName; }
}
private string ProjectBinariesPath
{
get { return Path.Combine(
Directory.GetParent(AirSimPluginPath).Parent.FullName, "Binaries");
}
}
private string AirSimPluginDependencyPath
{
get { return Path.Combine(AirSimPluginPath, "Dependencies"); }
}
private enum CompileMode
{
HeaderOnlyNoRpc,
HeaderOnlyWithRpc,
CppCompileNoRpc,
CppCompileWithRpc
}
private void SetupCompileMode(CompileMode mode, ReadOnlyTargetRules Target)
{
LoadAirSimDependency(Target, "MavLinkCom", "MavLinkCom");
switch (mode)
{
case CompileMode.HeaderOnlyNoRpc:
PublicDefinitions.Add("AIRLIB_HEADER_ONLY=1");
PublicDefinitions.Add("AIRLIB_NO_RPC=1");
AddLibDependency("AirLib", Path.Combine(AirLibPath, "lib"), "AirLib", Target, false);
break;
case CompileMode.HeaderOnlyWithRpc:
PublicDefinitions.Add("AIRLIB_HEADER_ONLY=1");
AddLibDependency("AirLib", Path.Combine(AirLibPath, "lib"), "AirLib", Target, false);
LoadAirSimDependency(Target, "rpclib", "rpc");
break;
case CompileMode.CppCompileNoRpc:
LoadAirSimDependency(Target, "MavLinkCom", "MavLinkCom");
PublicDefinitions.Add("AIRLIB_NO_RPC=1");
break;
case CompileMode.CppCompileWithRpc:
LoadAirSimDependency(Target, "rpclib", "rpc");
break;
default:
throw new System.Exception("CompileMode specified in plugin's Build.cs file is not recognized");
}
}
public AirSim(ReadOnlyTargetRules Target) : base(Target)
{
//bEnforceIWYU = true; //to support 4.16
PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;
bEnableExceptions = true;
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "ImageWrapper", "RenderCore", "RHI", "AssetRegistry","PhysXVehicles", "PhysXVehicleLib", "PhysX", "APEX", "Landscape" });
PrivateDependencyModuleNames.AddRange(new string[] { "UMG", "Slate", "SlateCore" });
//suppress VC++ proprietary warnings
PublicDefinitions.Add("_SCL_SECURE_NO_WARNINGS=1");
PublicDefinitions.Add("_CRT_SECURE_NO_WARNINGS=1");
PublicDefinitions.Add("HMD_MODULE_INCLUDED=0");
PublicIncludePaths.Add(Path.Combine(AirLibPath, "include"));
PublicIncludePaths.Add(Path.Combine(AirLibPath, "deps", "eigen3"));
AddOSLibDependencies(Target);
SetupCompileMode(CompileMode.HeaderOnlyWithRpc, Target);
}
private void AddOSLibDependencies(ReadOnlyTargetRules Target)
{
if (Target.Platform == UnrealTargetPlatform.Win64)
{
// for SHGetFolderPath.
PublicAdditionalLibraries.Add("Shell32.lib");
//for joystick support
PublicAdditionalLibraries.Add("dinput8.lib");
PublicAdditionalLibraries.Add("dxguid.lib");
}
if (Target.Platform == UnrealTargetPlatform.Linux)
{
// needed when packaging
PublicAdditionalLibraries.Add("stdc++");
PublicAdditionalLibraries.Add("supc++");
}
}
static void CopyFileIfNewer(string srcFilePath, string destFolder)
{
FileInfo srcFile = new FileInfo(srcFilePath);
FileInfo destFile = new FileInfo(Path.Combine(destFolder, srcFile.Name));
if (!destFile.Exists || srcFile.LastWriteTime > destFile.LastWriteTime)
{
srcFile.CopyTo(destFile.FullName, true);
}
//else skip
}
private bool LoadAirSimDependency(ReadOnlyTargetRules Target, string LibName, string LibFileName)
{
string LibrariesPath = Path.Combine(AirLibPath, "deps", LibName, "lib");
return AddLibDependency(LibName, LibrariesPath, LibFileName, Target, true);
}
private bool AddLibDependency(string LibName, string LibPath, string LibFileName, ReadOnlyTargetRules Target, bool IsAddLibInclude)
{
string PlatformString = (Target.Platform == UnrealTargetPlatform.Win64 || Target.Platform == UnrealTargetPlatform.Mac) ? "x64" : "x86";
string ConfigurationString = (Target.Configuration == UnrealTargetConfiguration.Debug) ? "Debug" : "Release";
bool isLibrarySupported = false;
if (Target.Platform == UnrealTargetPlatform.Win64)
{
isLibrarySupported = true;
PublicAdditionalLibraries.Add(Path.Combine(LibPath, PlatformString, ConfigurationString, LibFileName + ".lib"));
} else if (Target.Platform == UnrealTargetPlatform.Linux || Target.Platform == UnrealTargetPlatform.Mac) {
isLibrarySupported = true;
PublicAdditionalLibraries.Add(Path.Combine(LibPath, "lib" + LibFileName + ".a"));
}
if (isLibrarySupported && IsAddLibInclude)
{
// Include path
PublicIncludePaths.Add(Path.Combine(AirLibPath, "deps", LibName, "include"));
}
PublicDefinitions.Add(string.Format("WITH_" + LibName.ToUpper() + "_BINDING={0}", isLibrarySupported ? 1 : 0));
return isLibrarySupported;
}
}
| 35.93125 | 227 | 0.645851 | [
"MIT"
] | AOS55/AirSim-1 | Unreal/Plugins/AirSim/Source/AirSim.Build.cs | 5,749 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _8.Sunglasses
{
class Program
{
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine());
Console.Write(new string('*', 2 * n));
Console.Write(new string(' ', n));
Console.WriteLine(new string('*', 2 * n));
for (int i = 0; i < n - 2; i++)
{
Console.Write("*");
for (int r = 0; r < (n * 2) - 2; r++)
{
Console.Write("/");
}
Console.Write("*");
if (i == (n - 1) / 2 - 1)
{
Console.Write(new string('|', n));
}
else
{
Console.Write(new string(' ', n));
}
Console.Write("*");
for (int r = 0; r < (n * 2) - 2; r++)
{
Console.Write("/");
}
Console.Write("*");
Console.WriteLine();
}
Console.Write(new string('*', 2 * n));
Console.Write(new string(' ', n));
Console.WriteLine(new string('*', 2 * n));
}
}
}
| 24.709091 | 54 | 0.370861 | [
"MIT"
] | DanailIordanov/SoftUni-CSharp-Fundamentals | 1.C# Fundamentals I - Programming Basics Course - August 2016/6.Drawing Figures with Loops/8.Sunglasses/Program.cs | 1,361 | C# |
/*
* UiPath.WebApi
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: V2
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using PropertyChanged;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = UiPathEJC.Service.Rest.Client.SwaggerDateConverter;
namespace UiPathEJC.Service.Rest.Model
{
/// <summary>
/// UpdateBulkParameters
/// </summary>
[DataContract]
[ImplementPropertyChanged]
public partial class UpdateBulkParameters : IEquatable<UpdateBulkParameters>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="UpdateBulkParameters" /> class.
/// </summary>
/// <param name="Settings">Settings.</param>
public UpdateBulkParameters(List<SettingsDto> Settings = default(List<SettingsDto>))
{
this.Settings = Settings;
}
/// <summary>
/// Gets or Sets Settings
/// </summary>
[DataMember(Name="settings", EmitDefaultValue=false)]
public List<SettingsDto> Settings { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class UpdateBulkParameters {\n");
sb.Append(" Settings: ").Append(Settings).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as UpdateBulkParameters);
}
/// <summary>
/// Returns true if UpdateBulkParameters instances are equal
/// </summary>
/// <param name="input">Instance of UpdateBulkParameters to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(UpdateBulkParameters input)
{
if (input == null)
return false;
return
(
this.Settings == input.Settings ||
this.Settings != null &&
this.Settings.SequenceEqual(input.Settings)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Settings != null)
hashCode = hashCode * 59 + this.Settings.GetHashCode();
return hashCode;
}
}
/// <summary>
/// Property changed event handler
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Trigger when a property changed
/// </summary>
/// <param name="propertyName">Property Name</param>
public virtual void OnPropertyChanged(string propertyName)
{
// NOTE: property changed is handled via "code weaving" using Fody.
// Properties with setters are modified at compile time to notify of changes.
var propertyChanged = PropertyChanged;
if (propertyChanged != null)
{
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 32.763514 | 140 | 0.590637 | [
"MIT"
] | Blackspo0n/UiPath-Easy-Job-Control | UiPathEJC.Service.Rest/Model/UpdateBulkParameters.cs | 4,849 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
namespace System.Data.Entity.WrappingProvider
{
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Entity.Migrations.Model;
using System.Data.Entity.Migrations.Sql;
using System.Text;
public class WrappingSqlGenerator<TAdoNetBase> : MigrationSqlGenerator
where TAdoNetBase : DbProviderFactory
{
private readonly MigrationSqlGenerator _baseGenerator;
public WrappingSqlGenerator(MigrationSqlGenerator baseGenerator)
{
_baseGenerator = baseGenerator;
}
public override IEnumerable<MigrationStatement> Generate(
IEnumerable<MigrationOperation> migrationOperations,
string providerManifestToken)
{
var items = new StringBuilder();
foreach (var operation in migrationOperations)
{
items.Append(operation.GetType().Name).Append(' ');
}
WrappingAdoNetProvider<TAdoNetBase>.Instance.Log.Add(
new LogItem("Generate", null, items.ToString()));
return _baseGenerator.Generate(migrationOperations, providerManifestToken);
}
}
}
| 35.684211 | 134 | 0.65708 | [
"Apache-2.0"
] | TerraVenil/entityframework | test/EntityFramework/FunctionalTests/WrappingProvider/WrappingSqlGenerator.cs | 1,358 | C# |
/* Solution par : Promit
* Date : 21 août 2007
* http://www.gamedev.net/topic/457783-xna-getting-text-from-keyboard/
*
* It picks up key up/down messages, and it's event based. It's also buffered, so you won't lose presses regardless of poll frequency.
* The CharEntered event does full textual translation. It understands keyboard layouts, it's aware of modifiers like shift, etc.
* If you type a capital letter, you get a capital letter.
* The whole thing is IME enabled. In other words, East Asian languages will function properly.
* Usage is about as simple as it gets. Call EventInput.Initialize from your Game class initialize, and pass this.Window.
* Hook the events from there and you're done. There's nothing to create or keep track of, since it's a single static class.
*
*
*
* Ne fonctionne pas en 64bit
*/
using System;
using System.Runtime.InteropServices;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
namespace EventInput
{
public class CharacterEventArgs : EventArgs
{
private readonly char character;
private readonly int lParam;
public CharacterEventArgs(char character, int lParam)
{
this.character = character;
this.lParam = lParam;
}
public char Character
{
get { return character; }
}
public int Param
{
get { return lParam; }
}
public int RepeatCount
{
get { return lParam & 0xffff; }
}
public bool ExtendedKey
{
get { return (lParam & (1 << 24)) > 0; }
}
public bool AltPressed
{
get { return (lParam & (1 << 29)) > 0; }
}
public bool PreviousState
{
get { return (lParam & (1 << 30)) > 0; }
}
public bool TransitionState
{
get { return (lParam & (1 << 31)) > 0; }
}
}
public class KeyEventArgs : EventArgs
{
private Keys keyCode;
public KeyEventArgs(Keys keyCode)
{
this.keyCode = keyCode;
}
public Keys KeyCode
{
get { return keyCode; }
}
}
public delegate void CharEnteredHandler(object sender, CharacterEventArgs e);
public delegate void KeyEventHandler(object sender, KeyEventArgs e);
public static class EventInput
{
/// <summary>
/// Event raised when a character has been entered.
/// </summary>
public static event CharEnteredHandler CharEntered;
/// <summary>
/// Event raised when a key has been pressed down. May fire multiple times due to keyboard repeat.
/// </summary>
public static event KeyEventHandler KeyDown;
/// <summary>
/// Event raised when a key has been released.
/// </summary>
public static event KeyEventHandler KeyUp;
delegate IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
static bool initialized;
static IntPtr prevWndProc;
static WndProc hookProcDelegate;
static IntPtr hIMC;
//various Win32 constants that we need
const int GWL_WNDPROC = -4;
const int WM_KEYDOWN = 0x100;
const int WM_KEYUP = 0x101;
const int WM_CHAR = 0x102;
const int WM_IME_SETCONTEXT = 0x0281;
const int WM_INPUTLANGCHANGE = 0x51;
const int WM_GETDLGCODE = 0x87;
const int WM_IME_COMPOSITION = 0x10f;
const int DLGC_WANTALLKEYS = 4;
//Win32 functions that we're using
[DllImport("Imm32.dll")]
static extern IntPtr ImmGetContext(IntPtr hWnd);
[DllImport("Imm32.dll")]
static extern IntPtr ImmAssociateContext(IntPtr hWnd, IntPtr hIMC);
[DllImport("user32.dll")]
static extern IntPtr CallWindowProc(IntPtr lpPrevWndFunc, IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
/// <summary>
/// Initialize the TextInput with the given GameWindow.
/// </summary>
/// <param name="window">The XNA window to which text input should be linked.</param>
public static void Initialize(GameWindow window)
{
if (initialized)
throw new InvalidOperationException("TextInput.Initialize can only be called once!");
hookProcDelegate = new WndProc(HookProc);
prevWndProc = (IntPtr)SetWindowLong(window.Handle, GWL_WNDPROC,
(int)Marshal.GetFunctionPointerForDelegate(hookProcDelegate));
hIMC = ImmGetContext(window.Handle);
initialized = true;
}
static IntPtr HookProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
{
IntPtr returnCode = CallWindowProc(prevWndProc, hWnd, msg, wParam, lParam);
switch (msg)
{
case WM_GETDLGCODE:
returnCode = (IntPtr)(returnCode.ToInt32() | DLGC_WANTALLKEYS);
break;
case WM_KEYDOWN:
if (KeyDown != null)
KeyDown(null, new KeyEventArgs((Keys)wParam));
break;
case WM_KEYUP:
if (KeyUp != null)
KeyUp(null, new KeyEventArgs((Keys)wParam));
break;
case WM_CHAR:
if (CharEntered != null)
CharEntered(null, new CharacterEventArgs((char)wParam, lParam.ToInt32()));
break;
case WM_IME_SETCONTEXT:
if (wParam.ToInt32() == 1)
ImmAssociateContext(hWnd, hIMC);
break;
case WM_INPUTLANGCHANGE:
ImmAssociateContext(hWnd, hIMC);
returnCode = (IntPtr)1;
break;
}
return returnCode;
}
}
} | 31.451282 | 134 | 0.578347 | [
"BSD-3-Clause"
] | Tri125/BBTA_MonoGame | BBTA_MonoGame/BBTA_MonoGame/Classe/Outils/EventInput.cs | 6,136 | C# |
//
// DownloadModeTests.cs
//
// Authors:
// Alan McGovern alan.mcgovern@gmail.com
//
// Copyright (C) 2019 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.Linq;
using System.Threading.Tasks;
using MonoTorrent.BEncoding;
using MonoTorrent.Client.Messages.Libtorrent;
using MonoTorrent.Client.Messages.Standard;
using NUnit.Framework;
namespace MonoTorrent.Client.Modes
{
[TestFixture]
public class DownloadModeTests
{
ConnectionPair conn;
ConnectionManager ConnectionManager { get; set; }
DiskManager DiskManager { get; set; }
TorrentManager Manager { get; set; }
PeerId Peer { get; set; }
TestWriter PieceWriter { get; set; }
EngineSettings Settings { get; set; }
ManualTrackerManager TrackerManager { get; set; }
[SetUp]
public void Setup ()
{
conn = new ConnectionPair ().WithTimeout ();
Settings = new EngineSettings ();
PieceWriter = new TestWriter ();
DiskManager = new DiskManager (Settings, PieceWriter);
ConnectionManager = new ConnectionManager ("LocalPeerId", Settings, DiskManager);
TrackerManager = new ManualTrackerManager ();
long[] fileSizes = {
Piece.BlockSize / 2,
Piece.BlockSize * 32,
Piece.BlockSize * 2,
Piece.BlockSize * 13,
};
Manager = TestRig.CreateMultiFileManager (fileSizes, Piece.BlockSize * 2);
Manager.SetTrackerManager (TrackerManager);
Peer = new PeerId (new Peer ("", new Uri ("ipv4://123.123.123.123:12345"), EncryptionTypes.All), conn.Outgoing, new MutableBitField (Manager.PieceCount ()));
}
[TearDown]
public void Teardown ()
{
conn.Dispose ();
DiskManager.Dispose ();
}
[Test]
public async Task AddPeers_TooMany ()
{
await Manager.UpdateSettingsAsync (new TorrentSettingsBuilder (Manager.Settings) { MaximumConnections = 100 }.ToSettings ());
var peers = new List<Peer> ();
for (int i = 0; i < Manager.Settings.MaximumPeerDetails + 100; i++)
peers.Add (new Peer ("", new Uri ($"ipv4://192.168.0.1:{i + 1000}")));
var added = await Manager.AddPeersAsync (peers);
Assert.AreEqual (added, Manager.Settings.MaximumPeerDetails, "#1");
Assert.AreEqual (added, Manager.Peers.AvailablePeers.Count, "#2");
}
[Test]
public async Task AddPeers_PeerExchangeMessage ()
{
var peer = new byte[] { 192, 168, 0, 1, 100, 0, 192, 168, 0, 2, 101, 0 };
var dotF = new byte[] { 0, 1 << 1 }; // 0x2 means is a seeder
var id = PeerId.CreateNull (40);
id.SupportsFastPeer = true;
id.SupportsLTMessages = true;
Mode[] modes = {
new DownloadMode (Manager, DiskManager, ConnectionManager, Settings),
new MetadataMode (Manager, DiskManager, ConnectionManager, Settings, "")
};
foreach (var mode in modes) {
var peersTask = new TaskCompletionSource<PeerExchangePeersAdded> ();
Manager.PeersFound += (o, e) => {
if (e is PeerExchangePeersAdded args)
peersTask.TrySetResult (args);
};
Manager.Peers.ClearAll ();
var exchangeMessage = new PeerExchangeMessage (13, peer, dotF, null);
Manager.Mode = mode;
Manager.Mode.HandleMessage (id, exchangeMessage);
var addedArgs = await peersTask.Task.WithTimeout ();
Assert.AreEqual (2, addedArgs.NewPeers, "#1");
Assert.IsFalse (Manager.Peers.AvailablePeers[0].IsSeeder, "#2");
Assert.IsTrue (Manager.Peers.AvailablePeers[1].IsSeeder, "#3");
}
}
[Test]
public async Task AddPeers_PeerExchangeMessage_Private ()
{
var peer = new byte[] { 192, 168, 0, 1, 100, 0 };
var dotF = new byte[] { 1 << 0 | 1 << 2 }; // 0x1 means supports encryption, 0x2 means is a seeder
var id = PeerId.CreateNull (40);
id.SupportsFastPeer = true;
id.SupportsLTMessages = true;
var torrent = TestRig.CreatePrivate ();
using var engine = new ClientEngine (EngineSettingsBuilder.CreateForTests ());
var manager = await engine.AddAsync (torrent, "");
manager.Mode = new DownloadMode (manager, DiskManager, ConnectionManager, Settings);
var peersTask = new TaskCompletionSource<PeerExchangePeersAdded> ();
manager.PeersFound += (o, e) => {
if (e is PeerExchangePeersAdded args)
peersTask.TrySetResult (args);
};
var exchangeMessage = new PeerExchangeMessage (13, peer, dotF, null);
manager.Mode.HandleMessage (id, exchangeMessage);
var addedArgs = await peersTask.Task.WithTimeout ();
Assert.AreEqual (0, addedArgs.NewPeers, "#1");
}
[Test]
public async Task AddPeers_Tracker_Private ()
{
var torrent = TestRig.CreatePrivate ();
using var engine = new ClientEngine (EngineSettingsBuilder.CreateForTests ());
var manager = await engine.AddAsync (torrent, "");
manager.SetTrackerManager (TrackerManager);
var peersTask = new TaskCompletionSource<TrackerPeersAdded> ();
manager.PeersFound += (o, e) => {
if (e is TrackerPeersAdded args)
peersTask.TrySetResult (args);
};
await TrackerManager.AddTrackerAsync (new Uri ("http://test.tracker"));
TrackerManager.RaiseAnnounceComplete (TrackerManager.Tiers.Single ().ActiveTracker, true, new[] { new Peer ("One", new Uri ("ipv4://1.1.1.1:1111")), new Peer ("Two", new Uri ("ipv4://2.2.2.2:2222")) });
var addedArgs = await peersTask.Task.WithTimeout ();
Assert.AreEqual (2, addedArgs.NewPeers, "#1");
Assert.AreEqual (2, manager.Peers.AvailablePeers.Count, "#2");
}
[Test]
public void AddConnection ()
{
Manager.Mode = new DownloadMode (Manager, DiskManager, ConnectionManager, Settings);
Assert.IsTrue (Peer.Connection.Connected, "#1");
Manager.HandlePeerConnected (Peer);
Assert.IsTrue (Peer.Connection.Connected, "#2");
// ConnectionManager should add the PeerId to the Connected list whenever
// an outgoing connection is made, or an incoming one is received.
Assert.IsFalse (Manager.Peers.ConnectedPeers.Contains (Peer), "#3");
}
[Test]
public async Task AnnounceWhenComplete ()
{
await TrackerManager.AddTrackerAsync (new Uri ("http://1.1.1.1"));
Manager.LoadFastResume (new FastResume (Manager.InfoHash, new MutableBitField (Manager.PieceCount ()).SetAll (true), new MutableBitField (Manager.PieceCount ())));
Manager.MutableBitField[0] = false;
var mode = new DownloadMode (Manager, DiskManager, ConnectionManager, Settings);
Manager.Mode = mode;
Assert.AreEqual (1, TrackerManager.Announces.Count, "#0");
Assert.AreEqual (TorrentState.Downloading, Manager.State, "#0b");
Assert.AreEqual (TorrentEvent.None, TrackerManager.Announces[0].Item2, "#0");
Manager.MutableBitField[0] = true;
TrackerManager.Announces.Clear ();
mode.Tick (0);
Assert.AreEqual (TorrentState.Seeding, Manager.State, "#0c");
Assert.AreEqual (2, TrackerManager.Announces.Count, "#1");
Assert.AreEqual (null, TrackerManager.Announces[0].Item1, "#2");
Assert.AreEqual (TorrentEvent.None, TrackerManager.Announces[0].Item2, "#3");
Assert.AreEqual (null, TrackerManager.Announces[1].Item1, "#2");
Assert.AreEqual (TorrentEvent.Completed, TrackerManager.Announces[1].Item2, "#4");
}
[Test]
public void MismatchedInfoHash ()
{
Manager.Mode = new DownloadMode (Manager, DiskManager, ConnectionManager, Settings);
var peer = PeerId.CreateNull (Manager.Bitfield.Length);
var handshake = new HandshakeMessage (new InfoHash (Enumerable.Repeat ((byte)15, 20).ToArray ()), "peerid", VersionInfo.ProtocolStringV100);
Assert.Throws<TorrentException> (() => Manager.Mode.HandleMessage (peer, handshake));
}
[Test]
public void MismatchedProtocolString ()
{
Manager.Mode = new DownloadMode (Manager, DiskManager, ConnectionManager, Settings);
var peerId = PeerId.CreateNull (Manager.Bitfield.Length);
var handshake = new HandshakeMessage (Manager.InfoHash, "peerid", "bleurgh");
Assert.Throws<ProtocolException> (() => Manager.Mode.HandleMessage (peerId, handshake));
}
[Test]
public async Task EmptyPeerId_PrivateTorrent ()
{
var torrent = TestRig.CreatePrivate ();
using var engine = new ClientEngine (EngineSettingsBuilder.CreateForTests ());
var manager = await engine.AddAsync (torrent, "");
manager.Mode = new DownloadMode (manager, DiskManager, ConnectionManager, Settings);
var peer = PeerId.CreateNull (manager.Bitfield.Length);
peer.Peer.PeerId = null;
var handshake = new HandshakeMessage (manager.InfoHash, new BEncodedString (Enumerable.Repeat ('c', 20).ToArray ()), VersionInfo.ProtocolStringV100, false);
manager.Mode.HandleMessage (peer, handshake);
Assert.AreEqual (handshake.PeerId, peer.PeerID);
}
[Test]
public void EmptyPeerId_PublicTorrent ()
{
Manager.Mode = new DownloadMode (Manager, DiskManager, ConnectionManager, Settings);
var peer = PeerId.CreateNull (Manager.Bitfield.Length);
peer.Peer.PeerId = null;
var handshake = new HandshakeMessage (Manager.InfoHash, new BEncodedString (Enumerable.Repeat ('c', 20).ToArray ()), VersionInfo.ProtocolStringV100, false);
Manager.Mode.HandleMessage (peer, handshake);
Assert.AreEqual (handshake.PeerId, peer.PeerID);
}
[Test]
public async Task MismatchedPeerId_PrivateTorrent ()
{
var torrent = TestRig.CreatePrivate ();
using var engine = new ClientEngine (EngineSettingsBuilder.CreateForTests ());
var manager = await engine.AddAsync (torrent, "");
manager.Mode = new DownloadMode (manager, DiskManager, ConnectionManager, Settings);
var peer = PeerId.CreateNull (manager.Bitfield.Length);
var handshake = new HandshakeMessage (manager.InfoHash, new BEncodedString (Enumerable.Repeat ('c', 20).ToArray ()), VersionInfo.ProtocolStringV100, false);
Assert.Throws<TorrentException> (() => manager.Mode.HandleMessage (peer, handshake));
}
[Test]
public void MismatchedPeerId_PublicTorrent ()
{
Manager.Mode = new DownloadMode (Manager, DiskManager, ConnectionManager, Settings);
var peer = PeerId.CreateNull (Manager.Bitfield.Length);
var handshake = new HandshakeMessage (Manager.InfoHash, new BEncodedString (Enumerable.Repeat ('c', 20).ToArray ()), VersionInfo.ProtocolStringV100, false);
Assert.DoesNotThrow (() => Manager.Mode.HandleMessage (peer, handshake));
Assert.AreEqual (peer.PeerID, handshake.PeerId);
}
[Test]
public async Task PauseDownloading ()
{
Manager.Mode = new DownloadMode (Manager, DiskManager, ConnectionManager, Settings);
Assert.AreEqual (TorrentState.Downloading, Manager.State);
await Manager.PauseAsync ();
Assert.AreEqual (TorrentState.Paused, Manager.State);
}
[Test]
public async Task PauseSeeding ()
{
Manager.LoadFastResume (new FastResume (Manager.InfoHash, new MutableBitField (Manager.PieceCount ()).SetAll (true), new MutableBitField (Manager.PieceCount ())));
Manager.Mode = new DownloadMode (Manager, DiskManager, ConnectionManager, Settings);
Assert.AreEqual (TorrentState.Seeding, Manager.State);
await Manager.PauseAsync ();
Assert.AreEqual (TorrentState.Paused, Manager.State);
}
[Test]
public async Task PartialProgress_AllDownloaded_AllDownloadable ()
{
for (int i = 0; i < Manager.Torrent.Pieces.Count; i++)
Manager.OnPieceHashed (i, true);
var mode = new DownloadMode (Manager, DiskManager, ConnectionManager, Settings);
Manager.Mode = mode;
await mode.UpdateSeedingDownloadingState ();
Assert.AreEqual (100.0, Manager.Progress, "#3");
Assert.AreEqual (100.0, Manager.PartialProgress, "#4");
Assert.AreEqual (TorrentState.Seeding, Manager.State, "#5");
}
[Test]
public async Task PartialProgress_AllDownloaded_SomeDownloadable ()
{
for (int i = 0; i < Manager.Torrent.Pieces.Count; i++)
Manager.OnPieceHashed (i, true);
foreach (var file in Manager.Files)
await Manager.SetFilePriorityAsync (file, Priority.DoNotDownload);
await Manager.SetFilePriorityAsync (Manager.Files.Last (), Priority.Normal);
var mode = new DownloadMode (Manager, DiskManager, ConnectionManager, Settings);
Manager.Mode = mode;
await mode.UpdateSeedingDownloadingState ();
Assert.AreNotEqual (0, Manager.Progress, "#3");
Assert.AreEqual (100.0, Manager.PartialProgress, "#4");
Assert.AreEqual (TorrentState.Seeding, Manager.State, "#5");
}
[Test]
public async Task PartialProgress_NoneDownloaded ()
{
var mode = new DownloadMode (Manager, DiskManager, ConnectionManager, Settings);
Manager.Mode = mode;
await mode.UpdateSeedingDownloadingState ();
Assert.AreEqual (0, Manager.Progress, "#1");
Assert.AreEqual (0, Manager.PartialProgress, "#2");
Assert.AreEqual (TorrentState.Downloading, Manager.State, "#3");
}
[Test]
public async Task PartialProgress_NoneDownloaded_AllDoNotDownload ()
{
foreach (var file in Manager.Files)
await Manager.SetFilePriorityAsync (file, Priority.DoNotDownload);
var mode = new DownloadMode (Manager, DiskManager, ConnectionManager, Settings);
Manager.Mode = mode;
await mode.UpdateSeedingDownloadingState ();
Assert.AreEqual (0, Manager.Progress, "#1");
Assert.AreEqual (0, Manager.PartialProgress, "#2");
Assert.AreEqual (TorrentState.Downloading, Manager.State, "#3");
}
[Test]
public async Task PartialProgress_RelatedDownloaded ()
{
Manager.OnPieceHashed (0, true);
foreach (var file in Manager.Files)
await Manager.SetFilePriorityAsync (file, Priority.DoNotDownload);
await Manager.SetFilePriorityAsync (Manager.Files.First (), Priority.Normal);
var mode = new DownloadMode (Manager, DiskManager, ConnectionManager, Settings);
Manager.Mode = mode;
await mode.UpdateSeedingDownloadingState ();
Assert.That (Manager.Progress, Is.GreaterThan (0.0), "#3a");
Assert.That (Manager.Progress, Is.LessThan (100.0), "#3b");
Assert.That (Manager.PartialProgress, Is.EqualTo (100.0), "#4");
Assert.AreEqual (TorrentState.Seeding, Manager.State, "#5");
}
[Test]
public async Task PartialProgress_RelatedDownloaded2 ()
{
var lastFile = Manager.Files.Last ();
Manager.OnPieceHashed (Manager.Torrent.Pieces.Count - 1, true);
foreach (var file in Manager.Files)
await Manager.SetFilePriorityAsync (file, Priority.DoNotDownload);
await Manager.SetFilePriorityAsync (lastFile, Priority.Normal);
var mode = new DownloadMode (Manager, DiskManager, ConnectionManager, Settings);
Manager.Mode = mode;
await mode.UpdateSeedingDownloadingState ();
var totalPieces = lastFile.EndPieceIndex - lastFile.StartPieceIndex + 1;
Assert.That (Manager.PartialProgress, Is.EqualTo (100.0 / totalPieces).Within (1).Percent, "#1");
Assert.AreEqual (TorrentState.Downloading, Manager.State, "#2");
}
[Test]
public async Task PartialProgress_RelatedDownloaded_FileAdded ()
{
Manager.OnPieceHashed (0, true);
foreach (var file in Manager.Files)
await Manager.SetFilePriorityAsync (file, Priority.DoNotDownload);
await Manager.SetFilePriorityAsync (Manager.Files.First (), Priority.Normal);
var mode = new DownloadMode (Manager, DiskManager, ConnectionManager, Settings);
Manager.Mode = mode;
await mode.UpdateSeedingDownloadingState ().WithTimeout ();
Assert.AreEqual (TorrentState.Seeding, Manager.State, "#1");
var oldStateTask = new TaskCompletionSource<TorrentState> ();
var newStateTask = new TaskCompletionSource<TorrentState> ();
Manager.TorrentStateChanged += (object sender, TorrentStateChangedEventArgs e) => {
oldStateTask.SetResult (e.OldState);
newStateTask.SetResult (e.NewState);
};
await Manager.SetFilePriorityAsync (Manager.Files.Skip (1).First (), Priority.Normal);
await mode.UpdateSeedingDownloadingState ().WithTimeout ();
var oldState = await oldStateTask.Task.WithTimeout ();
var newState = await newStateTask.Task.WithTimeout ();
Assert.That (Manager.Progress, Is.GreaterThan (0.0), "#3a");
Assert.That (Manager.Progress, Is.LessThan (100.0), "#3b");
Assert.That (Manager.PartialProgress, Is.LessThan (100.0), "#4");
Assert.AreEqual (TorrentState.Downloading, Manager.State, "#5");
Assert.AreEqual (TorrentState.Seeding, oldState, "#6");
Assert.AreEqual (TorrentState.Downloading, newState, "#7");
}
[Test]
public async Task PartialProgress_UnrelatedDownloaded_AllDoNotDownload ()
{
Manager.OnPieceHashed (0, true);
foreach (var file in Manager.Files)
await Manager.SetFilePriorityAsync (file, Priority.DoNotDownload);
var mode = new DownloadMode (Manager, DiskManager, ConnectionManager, Settings);
Manager.Mode = mode;
await mode.UpdateSeedingDownloadingState ();
Assert.AreNotEqual (0, Manager.Progress, "#3");
Assert.AreEqual (0, Manager.PartialProgress, "#4");
}
[Test]
public async Task PartialProgress_UnrelatedDownloaded_SomeDoNotDownload ()
{
Manager.OnPieceHashed (0, true);
foreach (var file in Manager.Files)
await Manager.SetFilePriorityAsync (file, Priority.DoNotDownload);
await Manager.SetFilePriorityAsync (Manager.Files.Last (), Priority.Normal);
var mode = new DownloadMode (Manager, DiskManager, ConnectionManager, Settings);
Manager.Mode = mode;
await mode.UpdateSeedingDownloadingState ();
Assert.AreNotEqual (0, Manager.Progress, "#3");
Assert.AreEqual (0, Manager.PartialProgress, "#4");
}
}
}
| 44.108108 | 214 | 0.619768 | [
"MIT"
] | OneFingerCodingWarrior/monotorrent | src/MonoTorrent.Tests/MonoTorrent.Client.Modes/DownloadModeTests.cs | 21,218 | C# |
using Common;
using AutoMapper;
using ConfigMgmt;
using EnterpriseContact.ViewModels;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Common.Services;
using Serilog;
namespace EnterpriseContact.Controllers
{
[Route("api/v1/employee")]
public class EmployeeController : TheBaseController
{
private readonly IEmployeeAppService _employeeAppService;
private readonly IGroupAppService _groupAppService;
private readonly Func<Guid, IUserFavoriteAppService> _userFavoriteAppServiceFactory;
private readonly Func<Guid, IUserSettingAppService> _userSettingAppServiceFactory;
private readonly ILogger _logger;
public EmployeeController(IMemoryCache cache, IMapper mapper,
IDepartmentAppService departmentAppService, IPositionAppService positionAppService,
IEmployeeAppService employeeAppService,
IGroupAppService groupAppService,
Func<Guid, IUserFavoriteAppService> userFavoriteAppServiceFactory,
Func<Guid, IUserSettingAppService> userSettingAppServiceFactory
)
: base(cache, mapper, departmentAppService, positionAppService)
{
_employeeAppService = employeeAppService;
_groupAppService = groupAppService;
_userFavoriteAppServiceFactory = userFavoriteAppServiceFactory;
_userSettingAppServiceFactory = userSettingAppServiceFactory;
_logger = Log.ForContext<EmployeeController>();
}
[HttpGet("my")]
public async Task<ActionResult<List<EmployeeListVm>>> GetMy()
{
try
{
var userId = GetUserId();
await EnsureDepartmentListCacheAsync();
await EnsurePositionListCacheAsync();
var favs = await _userFavoriteAppServiceFactory(userId).GetEmployeesAsync(userId);
var dto = await _employeeAppService.GetListByIdsAsync(favs);
return GenerateEmployeeList(dto);
}
catch (Exception ex)
{
return BadRequest(LogError(_logger, ex));
}
}
[HttpPost("fav/{employeeId}")]
public async Task<ActionResult<ResponseData>> AddFavorite(Guid employeeId)
{
try
{
var userId = GetUserId();
if (await _userFavoriteAppServiceFactory(userId).AddEmployeeAsync(userId, employeeId))
return BuildSuccess();
return BuildFaild();
}
catch (Exception ex)
{
return BadRequest(LogError(_logger, ex));
}
}
[HttpDelete("fav/{employeeId}")]
public async Task<ActionResult<ResponseData>> RemoveFavorite(Guid employeeId)
{
try
{
var userId = GetUserId();
if (await _userFavoriteAppServiceFactory(userId).RemoveEmployeeAsync(userId, employeeId))
return BuildSuccess();
return BuildFaild();
}
catch (Exception ex)
{
return BadRequest(LogError(_logger, ex));
}
}
[HttpGet("search")]
public async Task<ActionResult<List<EmployeeListVm>>> Search(string keyword)
{
try
{
await EnsureDepartmentListCacheAsync();
await EnsurePositionListCacheAsync();
var dto = await _employeeAppService.SearchByKeywordAsync(keyword);
return GenerateEmployeeList(dto);
}
catch (Exception ex)
{
return BadRequest(LogError(_logger, ex));
}
}
private ActionResult<List<EmployeeListVm>> GenerateEmployeeList(List<EmployeeListOutput> dto)
{
var data = new List<EmployeeListVm>();
foreach (var item in dto)
{
var vm = _mapper.Map<EmployeeListOutput, EmployeeListVm>(item, (opts) =>
{
opts.AfterMap((EmployeeListOutput s, EmployeeListVm d) =>
{
if (_positionListCache.ContainsKey(s.PrimaryPositionId))
d.PositionName = _positionListCache[s.PrimaryPositionId].Name;
SetDepartmentNames(s, d);
d.IsPrimary = true;
});
});
data.Add(vm);
}
return data;
}
//最多设置两级部门名称
private void SetDepartmentNames(EmployeeListOutput s, EmployeeListVm d)
{
d.DepartmentNames = new List<string>();
if (_departmentListCache.ContainsKey(s.PrimaryDepartmentId))
{
var item = _departmentListCache[s.PrimaryDepartmentId];
d.DepartmentNames.Add(item.Name);
if (item.ParentId.HasValue && _departmentListCache.ContainsKey(item.ParentId.Value))
{
d.DepartmentNames.Add(_departmentListCache[item.ParentId.Value].Name);
}
}
}
private async Task<ActionResult<EmployeeDetailVm>> ReturnByOutputAsync(Guid id, Func<Guid, Task<EmployeeOutput>> getOutput)
{
var dto = await getOutput(id);
if (dto == null) return NotFound(id);
await EnsureDepartmentListCacheAsync();
await EnsurePositionListCacheAsync();
var vm = _mapper.Map<EmployeeOutput, EmployeeDetailVm>(dto, (opts) =>
{
opts.AfterMap((EmployeeOutput s, EmployeeDetailVm d) =>
{
if (_positionListCache.ContainsKey(s.PrimaryPositionId))
d.PositionName = _positionListCache[s.PrimaryPositionId].Name;
SetDepartmentNames(s, d);
SetParttimeJobs(s, d);
});
});
var userId = GetUserId();
var employeeId = GetEmployeeId();
var task1 = _groupAppService.CheckSameWhiteListGroupAsync(employeeId, id);
var task2 = _userFavoriteAppServiceFactory(userId).IsFavoritedAsync(userId, id);
var task3 = dto.UserId.HasValue
? _userSettingAppServiceFactory(userId).GetInfoVisibilityAsync(dto.UserId.Value)
: Task.FromResult(new InfoVisibility());
await Task.WhenAll(task1, task2, task3);
vm.SameWhiteListGroup = task1.Result;
vm.IsFavorited = task2.Result;
if (!task3.Result.Mobile)
vm.Mobile = "***";
return vm;
}
[HttpGet("{id}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<EmployeeDetailVm>> GetById(Guid id)
{
try
{
return await ReturnByOutputAsync(id, (o) => _employeeAppService.GetByIdAsync(o));
}
catch (Exception ex)
{
return BadRequest(LogError(_logger, ex));
}
}
[HttpGet("userId/{id}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<EmployeeDetailVm>> GetByUserId(Guid id)
{
try
{
return await ReturnByOutputAsync(id, (o) => _employeeAppService.GetByUserIdAsync(o));
}
catch (Exception ex)
{
return BadRequest(LogError(_logger, ex));
}
}
private void SetParttimeJobs(EmployeeOutput s, EmployeeDetailVm d)
{
d.ParttimeJobs = new List<ParttimeJobListVm>();
foreach (var posId in s.ParttimePositionIds)
{
if (_positionListCache.ContainsKey(posId))
{
var pos = _positionListCache[posId];
var vm = new ParttimeJobListVm();
vm.PositionName = pos.Name;
vm.DepartmentNames = new List<string>();
//最多设置两级部门名称
if (_departmentListCache.ContainsKey(pos.DepartmentId))
{
var dep = _departmentListCache[pos.DepartmentId];
vm.DepartmentNames.Add(dep.Name);
if (dep.ParentId.HasValue && _departmentListCache.ContainsKey(dep.ParentId.Value))
{
vm.DepartmentNames.Add(_departmentListCache[dep.ParentId.Value].Name);
}
}
d.ParttimeJobs.Add(vm);
}
}
}
//返回完整层级
private void SetDepartmentNames(EmployeeOutput s, EmployeeDetailVm d)
{
d.DepartmentNames = new List<string>();
if (_departmentListCache.ContainsKey(s.PrimaryDepartmentId))
{
var item = _departmentListCache[s.PrimaryDepartmentId];
d.DepartmentNames.Add(item.Name);
while (item.ParentId.HasValue && _departmentListCache.ContainsKey(item.ParentId.Value))
{
var sub = _departmentListCache[item.ParentId.Value];
d.DepartmentNames.Add(sub.Name);
item = sub;
}
}
}
[HttpGet("checkSameWhiteList")]
public async Task<ActionResult<bool>> CheckSameWhiteListGroup(Guid employeeId)
{
try
{
return await _groupAppService.CheckSameWhiteListGroupAsync(GetEmployeeId(), employeeId);
}
catch (Exception ex)
{
return BadRequest(LogError(_logger, ex));
}
}
}
}
| 37.205128 | 131 | 0.563257 | [
"MIT"
] | appsonsf/FabricEAP | src/EnterpriseContactApi/Controllers/EmployeeController.cs | 10,211 | C# |
namespace MySportsFeeds.NetCore.Leagues.MLB.v1_2.ConferenceTeamStandings.Response
{
public class GamesPlayed : Stat
{
}
}
| 19.285714 | 82 | 0.740741 | [
"MIT"
] | RobGibbens/mysportsfeeds-dotnet | MySportsFeeds.NetCore/MySportsFeeds.NetCore/Leagues/MLB/v1_2/ConferenceTeamStandings/Response/GamesPlayed.cs | 137 | C# |
/**
* Copyright (c) 2019-2021 LG Electronics, Inc.
*
* This software contains code licensed as described in LICENSE.
*
*/
using UnityEngine;
using System;
using Unity.Mathematics;
namespace Simulator.Map
{
public struct GpsLocation
{
public double Latitude;
public double Longitude;
public double Altitude;
public double Northing;
public double Easting;
}
public enum NPCSizeType
{
Compact = 1 << 0,
MidSize = 1 << 1,
Luxury = 1 << 2,
Sport = 1 << 3,
LightTruck = 1 << 4,
SUV = 1 << 5,
MiniVan = 1 << 6,
Large = 1 << 7,
Emergency = 1 << 8,
Bus = 1 << 9,
Trailer = 1 << 10,
Motorcycle = 1 << 11,
Bicycle = 1 << 12,
};
public partial class MapOrigin : MonoBehaviour
{
public double OriginEasting;
public double OriginNorthing;
public int UTMZoneId;
public float AltitudeOffset = 0f;
[HideInInspector]
public string TimeZoneSerialized;
[HideInInspector]
public string TimeZoneString;
public TimeZoneInfo TimeZone => string.IsNullOrEmpty(TimeZoneSerialized) ? TimeZoneInfo.Local : TimeZoneInfo.FromSerializedString(TimeZoneSerialized);
[HideInInspector]
public bool IgnoreNPCVisible = false; // TODO fix this disabled for now in SpawnManager
public bool IgnoreNPCSpawnable = false;
public bool IgnoreNPCBounds = false;
public bool IgnorePedBounds = false;
[HideInInspector]
public bool IgnorePedVisible = false; // TODO fix this disabled for now in SpawnManager
public int NPCSizeMask = 1<<0 | 1<<1 | 1<<2 | 1<<3| 1<<4 | 1<<5 | 1<<6 | 1<<7 | 1<<8 | 1<<9 | 1<<11 | 1<<12;
public int NPCMaxCount = 10;
public int NPCSpawnBoundSize = 200;
public int PedMaxCount = 10;
public int PedSpawnBoundSize = 200;
public string Description;
public static MapOrigin Find()
{
var origin = FindObjectOfType<MapOrigin>();
if (origin == null)
{
Debug.LogWarning("Map is missing MapOrigin component! Adding temporary MapOrigin. Please add to scene and set origin");
origin = new GameObject("MapOrigin").AddComponent<MapOrigin>();
origin.transform.SetPositionAndRotation(Vector3.zero, Quaternion.identity);
origin.OriginEasting = 592720;
origin.OriginNorthing = 4134479;
origin.UTMZoneId = 10;
}
return origin;
}
public GpsLocation GetGpsLocation(Vector3 position, bool ignoreMapOrigin = false)
{
return GetGpsLocation((double3)(float3)position, ignoreMapOrigin);
}
public GpsLocation GetGpsLocation(double3 position, bool ignoreMapOrigin = false)
{
var location = new GpsLocation();
GetNorthingEasting(position, out location.Northing, out location.Easting, ignoreMapOrigin);
GetLatitudeLongitude(location.Northing, location.Easting, out location.Latitude, out location.Longitude, ignoreMapOrigin);
location.Altitude = position.y + AltitudeOffset;
return location;
}
public Vector3 FromGpsLocation(double latitude, double longitude)
{
FromLatitudeLongitude(latitude, longitude, out var northing, out var easting);
var x = FromNorthingEasting(northing, easting);
return x;
}
public void GetNorthingEasting(double3 position, out double northing, out double easting, bool ignoreMapOrigin = false)
{
var mapOriginRelative = transform.InverseTransformPoint(new Vector3((float)position.x, (float)position.y, (float)position.z));
northing = mapOriginRelative.z;
easting = mapOriginRelative.x;
if (!ignoreMapOrigin)
{
northing += OriginNorthing;
easting += OriginEasting;
}
}
public Vector3 FromNorthingEasting(double northing, double easting, bool ignoreMapOrigin = false)
{
if (!ignoreMapOrigin)
{
northing -= OriginNorthing;
easting -= OriginEasting;
}
var worldPosition = transform.TransformPoint(new Vector3((float)easting, 0, (float)northing));
return new Vector3(worldPosition.x, 0, worldPosition.z);
}
public static int GetZoneNumberFromLatLon(double latitude, double longitude)
{
int zoneNumber = (int)(Math.Floor((longitude + 180) / 6) + 1);
if (latitude >= 56.0 && latitude < 64.0 && longitude >= 3.0 && longitude < 12.0)
{
zoneNumber = 32;
}
// Special Zones for Svalbard
if (latitude >= 72.0 && latitude < 84.0)
{
if (longitude >= 0.0 && longitude < 9.0)
{
zoneNumber = 31;
}
else if (longitude >= 9.0 && longitude < 21.0)
{
zoneNumber = 33;
}
else if (longitude >= 21.0 && longitude < 33.0)
{
zoneNumber = 35;
}
else if (longitude >= 33.0 && longitude < 42.0)
{
zoneNumber = 37;
}
}
return zoneNumber;
}
}
}
| 32.947059 | 158 | 0.562578 | [
"Apache-2.0",
"BSD-3-Clause"
] | carolina68/simulator | Assets/Scripts/Map/MapOrigin.cs | 5,601 | 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 WinCast.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WinCast.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
| 43.390625 | 173 | 0.612171 | [
"MIT"
] | Jay-Rad/WinCast | WinCast/Properties/Resources.Designer.cs | 2,779 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Cci.Extensions;
using Microsoft.Cci.Extensions.CSharp;
using Microsoft.Cci.Filters;
using Microsoft.Cci.Traversers;
using Microsoft.Cci.Writers.CSharp;
using Microsoft.Cci.Writers.Syntax;
namespace Microsoft.Cci.Writers
{
public class CSharpWriter : SimpleTypeMemberTraverser, ICciWriter
{
private readonly ISyntaxWriter _syntaxWriter;
private readonly IStyleSyntaxWriter _styleWriter;
private readonly CSDeclarationWriter _declarationWriter;
private readonly bool _writeAssemblyAttributes;
private readonly bool _apiOnly;
private readonly ICciFilter _cciFilter;
private bool _firstMemberGroup;
public CSharpWriter(ISyntaxWriter writer, ICciFilter filter, bool apiOnly, bool writeAssemblyAttributes = false)
: base(filter)
{
_syntaxWriter = writer;
_styleWriter = writer as IStyleSyntaxWriter;
_apiOnly = apiOnly;
_cciFilter = filter;
_declarationWriter = new CSDeclarationWriter(_syntaxWriter, filter, !apiOnly);
_writeAssemblyAttributes = writeAssemblyAttributes;
}
public ISyntaxWriter SyntaxWriter { get { return _syntaxWriter; } }
public ICciDeclarationWriter DeclarationWriter { get { return _declarationWriter; } }
public bool IncludeSpaceBetweenMemberGroups { get; set; }
public bool IncludeMemberGroupHeadings { get; set; }
public bool HighlightBaseMembers { get; set; }
public bool HighlightInterfaceMembers { get; set; }
public bool PutBraceOnNewLine { get; set; }
public bool IncludeGlobalPrefixForCompilation
{
get { return _declarationWriter.ForCompilationIncludeGlobalPrefix; }
set { _declarationWriter.ForCompilationIncludeGlobalPrefix = value; }
}
public string PlatformNotSupportedExceptionMessage
{
get { return _declarationWriter.PlatformNotSupportedExceptionMessage; }
set { _declarationWriter.PlatformNotSupportedExceptionMessage = value; }
}
public bool AlwaysIncludeBase
{
get { return _declarationWriter.AlwaysIncludeBase; }
set { _declarationWriter.AlwaysIncludeBase = value; }
}
public Version LangVersion
{
get { return _declarationWriter.LangVersion; }
set { _declarationWriter.LangVersion = value; }
}
public void WriteAssemblies(IEnumerable<IAssembly> assemblies)
{
foreach (var assembly in assemblies)
Visit(assembly);
}
public override void Visit(IAssembly assembly)
{
if (_writeAssemblyAttributes)
{
_declarationWriter.WriteDeclaration(assembly);
}
base.Visit(assembly);
}
public override void Visit(INamespaceDefinition ns)
{
if (ns != null && string.IsNullOrEmpty(ns.Name.Value))
{
base.Visit(ns);
}
else
{
_declarationWriter.WriteDeclaration(ns);
using (_syntaxWriter.StartBraceBlock(PutBraceOnNewLine))
{
base.Visit(ns);
}
}
_syntaxWriter.WriteLine();
}
public override void Visit(IEnumerable<ITypeDefinition> types)
{
WriteMemberGroupHeader(types.FirstOrDefault(Filter.Include) as ITypeDefinitionMember);
base.Visit(types);
}
public override void Visit(ITypeDefinition type)
{
_declarationWriter.WriteDeclaration(type);
if (!type.IsDelegate)
{
using (_syntaxWriter.StartBraceBlock(PutBraceOnNewLine))
{
// If we have no constructors then output a private one this
// prevents the C# compiler from creating a default public one.
var constructors = type.Methods.Where(m => m.IsConstructor && Filter.Include(m));
if (!type.IsStatic && !constructors.Any())
{
// HACK... this will likely not work for any thing other than CSDeclarationWriter
_declarationWriter.WriteDeclaration(CSDeclarationWriter.GetDummyConstructor(type));
_syntaxWriter.WriteLine();
}
_firstMemberGroup = true;
base.Visit(type);
}
}
_syntaxWriter.WriteLine();
}
public override void Visit(IEnumerable<ITypeDefinitionMember> members)
{
WriteMemberGroupHeader(members.FirstOrDefault(Filter.Include));
base.Visit(members);
}
public override void Visit(ITypeDefinition parentType, IEnumerable<IFieldDefinition> fields)
{
if (parentType.IsStruct && !_apiOnly)
{
// For compile-time compat, the following rules should work for producing a reference assembly. We drop all private fields, but add back certain synthesized private fields for a value type (struct) as follows:
// - If there are any private fields that are or contain any value type members, add a single private field of type int.
// - And, if there are any private fields that are or contain any reference type members, add a single private field of type object.
// - And, if the type is generic, then for every type parameter of the type, if there are any private fields that are or contain any members whose type is that type parameter, we add a direct private field of that type.
// Note: By "private", we mean not visible outside the assembly.
// For more details see issue https://github.com/dotnet/corefx/issues/6185
// this blog is helpful as well http://blog.paranoidcoding.com/2016/02/15/are-private-members-api-surface.html
List<IFieldDefinition> newFields = new List<IFieldDefinition>();
var includedVisibleFields = fields.Where(f => f.IsVisibleOutsideAssembly()).Where(_cciFilter.Include);
includedVisibleFields = includedVisibleFields.OrderBy(GetMemberKey, StringComparer.OrdinalIgnoreCase);
var excludedFields = fields.Except(includedVisibleFields).Where(f => !f.IsStatic);
if (excludedFields.Any())
{
var genericTypedFields = excludedFields.Where(f => f.Type.UnWrap().IsGenericParameter());
// Compiler needs to see any fields, even private, that have generic arguments to be able
// to validate there aren't any struct layout cycles
foreach (var genericField in genericTypedFields)
newFields.Add(genericField);
// For definiteassignment checks the compiler needs to know there is a private field
// that has not been initialized so if there are any we need to add a dummy private
// field to help the compiler do its job and error about uninitialized structs
bool hasRefPrivateField = excludedFields.Any(f => f.Type.IsOrContainsReferenceType());
// If at least one of the private fields contains a reference type then we need to
// set this field type to object or reference field to inform the compiler to block
// taking pointers to this struct because the GC will not track updating those references
if (hasRefPrivateField)
{
IFieldDefinition fieldType = DummyFieldWriterHelper(parentType, excludedFields, parentType.PlatformType.SystemObject);
newFields.Add(fieldType);
}
bool hasValueTypePrivateField = excludedFields.Any(f => !f.Type.IsOrContainsReferenceType());
if (hasValueTypePrivateField)
{
IFieldDefinition fieldType = DummyFieldWriterHelper(parentType, excludedFields, parentType.PlatformType.SystemInt32, "_dummyPrimitive");
newFields.Add(fieldType);
}
}
foreach (var visibleField in includedVisibleFields)
newFields.Add(visibleField);
foreach (var field in newFields)
Visit(field);
}
else
{
base.Visit(parentType, fields);
}
}
private IFieldDefinition DummyFieldWriterHelper(ITypeDefinition parentType, IEnumerable<IFieldDefinition> excludedFields, ITypeReference fieldType, string fieldName = "_dummy")
{
// For primitive types that have a field of their type set the dummy field to that type
if (excludedFields.Count() == 1)
{
var onlyField = excludedFields.First();
if (TypeHelper.TypesAreEquivalent(onlyField.Type, parentType))
{
fieldType = parentType;
}
}
return new DummyPrivateField(parentType, fieldType, fieldName);
}
public override void Visit(ITypeDefinitionMember member)
{
IDisposable style = null;
if (_styleWriter != null)
{
// Favor overrides over interface implementations (i.e. consider override Dispose() as an override and not an interface implementation)
if (this.HighlightBaseMembers && member.IsOverride())
style = _styleWriter.StartStyle(SyntaxStyle.InheritedMember);
else if (this.HighlightInterfaceMembers && member.IsInterfaceImplementation())
style = _styleWriter.StartStyle(SyntaxStyle.InterfaceMember);
}
_declarationWriter.WriteDeclaration(member);
if (style != null)
style.Dispose();
_syntaxWriter.WriteLine();
base.Visit(member);
}
private void WriteMemberGroupHeader(ITypeDefinitionMember member)
{
if (IncludeMemberGroupHeadings || IncludeSpaceBetweenMemberGroups)
{
string header = CSharpWriter.MemberGroupHeading(member);
if (header != null)
{
if (IncludeSpaceBetweenMemberGroups)
{
if (!_firstMemberGroup)
_syntaxWriter.WriteLine(true);
_firstMemberGroup = false;
}
if (IncludeMemberGroupHeadings)
{
IDisposable dispose = null;
if (_styleWriter != null)
dispose = _styleWriter.StartStyle(SyntaxStyle.Comment);
_syntaxWriter.Write("// {0}", header);
if (dispose != null)
dispose.Dispose();
_syntaxWriter.WriteLine();
}
}
}
}
public static string MemberGroupHeading(ITypeDefinitionMember member)
{
if (member == null)
return null;
IMethodDefinition method = member as IMethodDefinition;
if (method != null)
{
if (method.IsConstructor)
return "Constructors";
return "Methods";
}
IFieldDefinition field = member as IFieldDefinition;
if (field != null)
return "Fields";
IPropertyDefinition property = member as IPropertyDefinition;
if (property != null)
return "Properties";
IEventDefinition evnt = member as IEventDefinition;
if (evnt != null)
return "Events";
INestedTypeDefinition nType = member as INestedTypeDefinition;
if (nType != null)
return "Nested Types";
return null;
}
}
}
| 40.164557 | 235 | 0.587457 | [
"MIT"
] | AaronRobinsonMSFT/arcade | src/Microsoft.Cci.Extensions/Writers/CSharp/CSharpWriter.cs | 12,692 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
namespace NLU.DevOps.Lex
{
using Newtonsoft.Json.Linq;
/// <summary>
/// Entity types class.
/// </summary>
public class EntityType
{
/// <summary>
/// Initializes a new instance of the <see cref="EntityType"/> class.
/// </summary>
/// <param name="name">Entity type name.</param>
/// <param name="kind">Entity type kind.</param>
/// <param name="data">Entity type data.</param>
public EntityType(string name, string kind, JToken data)
{
this.Name = name;
this.Kind = kind;
this.Data = data;
}
/// <summary>
/// Gets the entity type name.
/// </summary>
public string Name { get; }
/// <summary>
/// Gets the entity type kind.
/// </summary>
public string Kind { get; }
/// <summary>
/// Gets the entity type data.
/// </summary>
public JToken Data { get; }
}
}
| 26.119048 | 77 | 0.521422 | [
"MIT"
] | omusavi/NLU.DevOps | src/NLU.DevOps.Lex/EntityType.cs | 1,099 | C# |
// *********************************************************************
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License
// *********************************************************************
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using DataX.Contract.Settings;
using DataX.ServiceHost.AspNetCore.Authorization.Extensions;
using DataX.ServiceHost.ServiceFabric.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
namespace DataX.ServiceHost.AspNetCore.Startup
{
/// <summary>
/// A basic abstract implementation of DataX startup to take care of common configuration.
/// </summary>
public abstract class DataXServiceStartup : IDataXServiceStartup
{
protected DataXSettings Settings { get; private set; }
public DataXServiceStartup() { }
public DataXServiceStartup(DataXSettings settings)
{
Settings = settings;
}
/// <inheritdoc />
public virtual void ConfigureServices(IServiceCollection services)
{
if (Settings == null)
{
var provider = services.BuildServiceProvider();
Settings = provider.GetService<DataXSettings>();
// Let's look for the default settings
if (Settings == null)
{
Settings = provider.GetService<IConfiguration>()?.GetSection(DataXSettingsConstants.ServiceEnvironment).Get<DataXSettings>();
if (Settings != null)
{
services.TryAddSingleton(Settings);
}
}
}
else
{
services.TryAddSingleton(Settings);
}
services
.AddDataXAuthorization(DataXDefaultGatewayPolicy.ConfigurePolicy)
.AddMvc(options => options.EnableEndpointRouting = false).AddNewtonsoftJson();
}
/// <inheritdoc />
public void Configure(IApplicationBuilder app)
{
var hostingEnvironment = app.ApplicationServices.GetService<IWebHostEnvironment>();
var loggerFactory = app.ApplicationServices.GetService<ILoggerFactory>();
Configure(app, hostingEnvironment, loggerFactory);
}
/// <inheritdoc cref="DataXServiceStartup.Configure(IApplicationBuilder)" />
protected virtual void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
app.Use(async (context, next) =>
{
context.Response.Headers.Add("X-Content-Type-Options", new string[] { "nosniff" });
await next();
});
app.UseRouting();
app.UseAuthentication();
app.UseMvc();
}
public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next)
{
return app =>
{
Configure(app);
next(app);
};
}
}
}
| 34.969072 | 145 | 0.589033 | [
"MIT"
] | Microsoft/data-accelerator | Services/DataX.ServiceHost/DataX.ServiceHost.AspNetCore/Startup/DataXServiceStartup.cs | 3,394 | C# |
#region License
// Copyright (c) 2007 James Newton-King
//
// 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.
#endregion
using System;
using System.Collections.Generic;
using System.Text;
#if DNXCORE50
using Xunit;
using Test = Xunit.FactAttribute;
using Assert = Newtonsoft.Json.Tests.XUnitAssert;
#else
using NUnit.Framework;
#endif
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
{
[TestFixture]
public class SerializeConditionalProperty : TestFixtureBase
{
#region Types
public class Employee
{
public string Name { get; set; }
public Employee Manager { get; set; }
public bool ShouldSerializeManager()
{
// don't serialize the Manager property if an employee is their own manager
return (Manager != this);
}
}
#endregion
[Test]
public void Example()
{
#region Usage
Employee joe = new Employee();
joe.Name = "Joe Employee";
Employee mike = new Employee();
mike.Name = "Mike Manager";
joe.Manager = mike;
// mike is his own manager
// ShouldSerialize will skip this property
mike.Manager = mike;
string json = JsonConvert.SerializeObject(new[] { joe, mike }, Formatting.Indented);
Console.WriteLine(json);
// [
// {
// "Name": "Joe Employee",
// "Manager": {
// "Name": "Mike Manager"
// }
// },
// {
// "Name": "Mike Manager"
// }
// ]
#endregion
Assert.AreEqual(@"[
{
""Name"": ""Joe Employee"",
""Manager"": {
""Name"": ""Mike Manager""
}
},
{
""Name"": ""Mike Manager""
}
]", json);
}
}
} | 29.81 | 96 | 0.597451 | [
"MIT"
] | jkorell/Newtonsoft.Json | Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeConditionalProperty.cs | 2,983 | C# |
// ***********************************************************************
// Assembly : Vip.Printer
// Author : Leandro Ferreira
// Created : 16-03-2019
//
// ***********************************************************************
// <copyright file="Printer.cs" company="VIP Soluções">
// The MIT License (MIT)
// Copyright (c) 2019 VIP Soluções
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
// </copyright>
// <summary></summary>
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Vip.Printer.Enums;
using Vip.Printer.EscBemaCommands;
using Vip.Printer.EscDarumaCommands;
using Vip.Printer.EscPosCommands;
using Vip.Printer.Helper;
using Vip.Printer.Interfaces.Command;
using Vip.Printer.Interfaces.Printer;
using Image = System.Drawing.Image;
namespace Vip.Printer
{
public class Printer : IPrinter
{
#region Properties
private byte[] _buffer;
private readonly string _printerName;
private readonly IPrintCommand _command;
private readonly PrinterType _printerType;
private readonly Encoding _encoding;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Printer" /> class.
/// </summary>
/// <param name="printerName">Printer name, shared name or port of printer install</param>
/// <param name="type">Command set of type printer</param>
/// <param name="colsNormal">Number of columns for normal mode print</param>
/// <param name="colsCondensed">Number of columns for condensed mode print</param>
/// <param name="colsExpanded">Number of columns for expanded mode print</param>
/// <param name="encoding">Custom encoding</param>
public Printer(string printerName, PrinterType type, int colsNormal, int colsCondensed, int colsExpanded, Encoding encoding)
{
_printerName = string.IsNullOrEmpty(printerName) ? "temp.prn" : printerName.Trim();
_printerType = type;
_encoding = encoding;
#region Select printer type
switch (type)
{
case PrinterType.Epson:
_command = new EscPos();
break;
case PrinterType.Bematech:
_command = new EscBema();
break;
case PrinterType.Daruma:
_command = new EscDaruma();
break;
}
#endregion
#region Configure number columns
ColsNomal = colsNormal == 0 ? _command.ColsNomal : colsNormal;
ColsCondensed = colsCondensed == 0 ? _command.ColsCondensed : colsCondensed;
ColsExpanded = colsExpanded == 0 ? _command.ColsExpanded : colsExpanded;
#endregion
}
/// <summary>
/// Initializes a new instance of the <see cref="Printer" /> class.
/// </summary>
/// <param name="printerName">Printer name, shared name or port of printer install</param>
/// <param name="type">Command set of type printer</param>
/// <param name="colsNormal">Number of columns for normal mode print</param>
/// <param name="colsCondensed">Number of columns for condensed mode print</param>
/// <param name="colsExpanded">Number of columns for expanded mode print</param>
public Printer(string printerName, PrinterType type, int colsNormal, int colsCondensed, int colsExpanded) : this(printerName, type, colsNormal, colsCondensed, colsExpanded, null) { }
/// <summary>
/// Initializes a new instance of the <see cref="Printer" /> class.
/// </summary>
/// <param name="printerName">Printer name, shared name or port of printer install</param>
/// <param name="type">Command set of type printer</param>
/// <param name="encoding">Custom encoding</param>
public Printer(string printerName, PrinterType type, Encoding encoding) : this(printerName, type, 0, 0, 0, encoding) { }
/// <summary>
/// Initializes a new instance of the <see cref="Printer" /> class.
/// </summary>
/// <param name="printerName">Printer name, shared name or port of printer install</param>
/// <param name="type">>Command set of type printer</param>
public Printer(string printerName, PrinterType type) : this(printerName, type, 0, 0, 0, null) { }
#endregion
#region Methods
public int ColsNomal { get; private set; }
public int ColsCondensed { get; private set; }
public int ColsExpanded { get; private set; }
public void PrintDocument(int copies = 1)
{
if (_buffer == null) return;
if (copies <= 0) copies = 1;
for (var i = 0; i < copies; i++)
if (!RawPrinterHelper.SendBytesToPrinter(_printerName, _buffer))
throw new ArgumentException("Não foi possível acessar a impressora: " + _printerName);
}
public void Write(string value)
{
WriteString(value, false);
}
public void Write(byte[] value)
{
if (value == null)
return;
var list = new List<byte>();
if (_buffer != null) list.AddRange(_buffer);
list.AddRange(value);
_buffer = list.ToArray();
}
public void WriteLine(string value)
{
WriteString(value, true);
}
private void WriteString(string value, bool useLf)
{
if (string.IsNullOrEmpty(value))
return;
if (useLf) value += "\n";
var list = new List<byte>();
if (_buffer != null) list.AddRange(_buffer);
var bytes = _encoding != null
? _encoding.GetBytes(value)
: _printerType == PrinterType.Bematech
? Encoding.GetEncoding(850).GetBytes(value)
: Encoding.GetEncoding("IBM860").GetBytes(value);
list.AddRange(bytes);
_buffer = list.ToArray();
}
public void NewLine()
{
Write("\n");
}
public void NewLines(int lines)
{
for (var i = 1; i < lines; i++)
NewLine();
}
public void Clear()
{
_buffer = null;
}
#region Obsolete Methods
[Obsolete("This method changed to WriteLine")]
public void Append(string value)
{
WriteLine(value);
}
[Obsolete("This method changed to Write")]
public void AppendWithoutLf(string value)
{
Write(value);
}
[Obsolete("This method changed to Write")]
public void Append(byte[] value)
{
Write(value);
}
#endregion
#endregion
#region Commands
public void Separator()
{
Write(_command.Separator());
}
public void AutoTest()
{
Write(_command.AutoTest());
}
public void TestPrinter()
{
AlignLeft();
WriteLine("TESTE DE IMPRESSÃO NORMAL - 48 COLUNAS");
WriteLine("....+....1....+....2....+....3....+....4....+...");
Separator();
WriteLine("Texto Normal");
ItalicMode("Texto Itálico");
BoldMode("Texto Negrito");
UnderlineMode("Texto Sublinhado");
ExpandedMode(PrinterModeState.On);
WriteLine("Texto Expandido");
WriteLine("....+....1....+....2....");
ExpandedMode(PrinterModeState.Off);
CondensedMode(PrinterModeState.On);
WriteLine("Texto condensado");
CondensedMode(PrinterModeState.Off);
Separator();
DoubleWidth2();
WriteLine("Largura Fonte 2");
DoubleWidth3();
WriteLine("Largura Fonte 3");
NormalWidth();
WriteLine("Largura normal");
Separator();
AlignRight();
WriteLine("Texto alinhado à direita");
AlignCenter();
WriteLine("Texto alinhado ao centro");
AlignLeft();
WriteLine("Texto alinhado à esquerda");
NewLines(3);
WriteLine("Final de Teste :)");
Separator();
NewLine();
}
#region FontMode
public void ItalicMode(string value)
{
Write(_command.FontMode.Italic(value));
}
public void ItalicMode(PrinterModeState state)
{
Write(_command.FontMode.Italic(state));
}
public void BoldMode(string value)
{
Write(_command.FontMode.Bold(value));
}
public void BoldMode(PrinterModeState state)
{
Write(_command.FontMode.Bold(state));
}
public void UnderlineMode(string value)
{
Write(_command.FontMode.Underline(value));
}
public void UnderlineMode(PrinterModeState state)
{
Write(_command.FontMode.Underline(state));
}
public void ExpandedMode(string value)
{
Write(_command.FontMode.Expanded(value));
}
public void ExpandedMode(PrinterModeState state)
{
Write(_command.FontMode.Expanded(state));
}
public void CondensedMode(string value)
{
Write(_command.FontMode.Condensed(value));
}
public void CondensedMode(PrinterModeState state)
{
Write(_command.FontMode.Condensed(state));
}
#endregion
#region FontWidth
public void NormalWidth()
{
Write(_command.FontWidth.Normal());
}
public void DoubleWidth2()
{
Write(_command.FontWidth.DoubleWidth2());
}
public void DoubleWidth3()
{
Write(_command.FontWidth.DoubleWidth3());
}
#endregion
#region Alignment
public void AlignLeft()
{
Write(_command.Alignment.Left());
}
public void AlignRight()
{
Write(_command.Alignment.Right());
}
public void AlignCenter()
{
Write(_command.Alignment.Center());
}
#endregion
#region PaperCut
public void FullPaperCut()
{
Write(_command.PaperCut.Full());
}
public void FullPaperCut(bool predicate)
{
if (predicate)
FullPaperCut();
}
public void PartialPaperCut()
{
Write(_command.PaperCut.Partial());
}
public void PartialPaperCut(bool predicate)
{
if (predicate)
PartialPaperCut();
}
#endregion
#region Drawer
public void OpenDrawer()
{
Write(_command.Drawer.Open());
}
#endregion
#region QrCode
public void QrCode(string qrData)
{
Write(_command.QrCode.Print(qrData));
}
public void QrCode(string qrData, QrCodeSize qrCodeSize)
{
Write(_command.QrCode.Print(qrData, qrCodeSize));
}
#endregion
#region Image
public void Image(string path, bool highDensity = true)
{
if (!File.Exists(path))
throw new Exception("Image file not found");
using (var image = System.Drawing.Image.FromFile(path)) Write(_command.Image.Print(image, highDensity));
}
public void Image(Stream stream, bool highDensity = true)
{
using (var image = System.Drawing.Image.FromStream(stream)) Write(_command.Image.Print(image, highDensity));
}
public void Image(byte[] bytes, bool highDensity = true)
{
using (var ms = new MemoryStream(bytes))
Write(_command.Image.Print(System.Drawing.Image.FromStream(ms), highDensity));
}
public void Image(Image image, bool highDensity = true)
{
Write(_command.Image.Print(image, highDensity));
}
#endregion
#region BarCode
public void Code128(string code)
{
Write(_command.BarCode.Code128(code));
}
public void Code39(string code)
{
Write(_command.BarCode.Code39(code));
}
public void Ean13(string code)
{
Write(_command.BarCode.Ean13(code));
}
#endregion
#region InitializePrint
public void InitializePrint()
{
RawPrinterHelper.SendBytesToPrinter(_printerName, _command.InitializePrint.Initialize());
}
#endregion
#endregion
}
} | 29.957983 | 190 | 0.556241 | [
"MIT"
] | adrbarros/Vip.Printer | src/Vip.Printer/Printer.cs | 14,272 | C# |
using DataCloner.Core.Metadata;
using DataCloner.GUI.Framework;
using System.ComponentModel.DataAnnotations;
namespace DataCloner.GUI.Model
{
class ForeignKeyColumnModifierModel : ValidatableModelBase
{
internal string _nameFrom;
internal string _nameTo;
private bool _isDeleted;
[Required]
public string NameFrom
{
get { return _nameFrom; }
set { SetPropertyAndValidate(ref _nameFrom, value); }
}
[Required]
public string NameTo
{
get { return _nameTo; }
set { SetPropertyAndValidate(ref _nameTo, value); }
}
public bool IsDeleted
{
get { return _isDeleted; }
set { SetProperty(ref _isDeleted, value); }
}
public ForeignKeyColumnModifierModel()
{
//Pour que le binding puisse créer une nouvelle ligne
}
public ForeignKeyColumnModifierModel(ForeignKeyColumn column)
{
_nameFrom = column.NameFrom;
_nameTo = column.NameTo;
}
}
}
| 22.836735 | 69 | 0.587131 | [
"MIT"
] | naster01/DataCloner | archive/DataCloner.GUI/Model/ForeignKeyColumnModifierModel.cs | 1,122 | C# |
namespace IranPost.Net.Dto.RejectId
{
public class RejectIdResponseDto
{
}
} | 13.857143 | 36 | 0.628866 | [
"MIT"
] | amkherad/IranPost.Net | src/IranPost.Net/Dto/RejectId/RejectIdResponseDto.cs | 97 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Shop.Database;
namespace Shop.Database.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20200524181657_OrderStock")]
partial class OrderStock
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.1.4")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
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")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasName("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.IdentityUser", 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")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<bool>("EmailConfirmed")
.HasColumnType("bit");
b.Property<bool>("LockoutEnabled")
.HasColumnType("bit");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("datetimeoffset");
b.Property<string>("NormalizedEmail")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(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")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex")
.HasFilter("[NormalizedUserName] IS NOT NULL");
b.ToTable("AspNetUsers");
});
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")
.HasColumnType("nvarchar(450)");
b.Property<string>("ProviderKey")
.HasColumnType("nvarchar(450)");
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")
.HasColumnType("nvarchar(450)");
b.Property<string>("Name")
.HasColumnType("nvarchar(450)");
b.Property<string>("Value")
.HasColumnType("nvarchar(max)");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("Shop.Domain.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Address1")
.HasColumnType("nvarchar(max)");
b.Property<string>("Address2")
.HasColumnType("nvarchar(max)");
b.Property<string>("City")
.HasColumnType("nvarchar(max)");
b.Property<string>("Email")
.HasColumnType("nvarchar(max)");
b.Property<string>("FirstName")
.HasColumnType("nvarchar(max)");
b.Property<string>("LastName")
.HasColumnType("nvarchar(max)");
b.Property<string>("OrderRef")
.HasColumnType("nvarchar(max)");
b.Property<string>("PhoneNumber")
.HasColumnType("nvarchar(max)");
b.Property<string>("PostCode")
.HasColumnType("nvarchar(max)");
b.Property<string>("StripeReference")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Orders");
});
modelBuilder.Entity("Shop.Domain.Models.OrderStock", b =>
{
b.Property<int>("StockId")
.HasColumnType("int");
b.Property<int>("OrderId")
.HasColumnType("int");
b.Property<int>("Quantity")
.HasColumnType("int");
b.HasKey("StockId", "OrderId");
b.HasIndex("OrderId");
b.ToTable("OrderStocks");
});
modelBuilder.Entity("Shop.Domain.Models.Product", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Description")
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.Property<decimal>("Value")
.HasColumnType("decimal(18,2)");
b.HasKey("Id");
b.ToTable("Products");
});
modelBuilder.Entity("Shop.Domain.Models.Stock", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Description")
.HasColumnType("nvarchar(max)");
b.Property<int>("ProductId")
.HasColumnType("int");
b.Property<int>("Quantity")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ProductId");
b.ToTable("Stocks");
});
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("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", 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("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Shop.Domain.Models.OrderStock", b =>
{
b.HasOne("Shop.Domain.Models.Order", "Order")
.WithMany("OrderStocks")
.HasForeignKey("OrderId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Shop.Domain.Models.Stock", "Stock")
.WithMany()
.HasForeignKey("StockId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Shop.Domain.Models.Stock", b =>
{
b.HasOne("Shop.Domain.Models.Product", "Product")
.WithMany("Stocks")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
| 37.084577 | 125 | 0.458009 | [
"Apache-2.0"
] | 40443219/ASP.NET_Core_3_Shop | Shop.Database/Migrations/20200524181657_OrderStock.Designer.cs | 14,910 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.Messaging.EventHubs.Core;
using Azure.Messaging.EventHubs.Diagnostics;
namespace Azure.Messaging.EventHubs.Producer
{
/// <summary>
/// A client responsible for publishing <see cref="EventData" /> to a specific Event Hub,
/// grouped together in batches. Depending on the options specified when sending, events data
/// may be automatically routed to an available partition or sent to a specifically requested partition.
/// </summary>
///
/// <remarks>
/// Allowing automatic routing of partitions is recommended when:
/// <para>- The sending of events needs to be highly available.</para>
/// <para>- The event data should be evenly distributed among all available partitions.</para>
///
/// If no partition is specified, the following rules are used for automatically selecting one:
/// <para>1) Distribute the events equally amongst all available partitions using a round-robin approach.</para>
/// <para>2) If a partition becomes unavailable, the Event Hubs service will automatically detect it and forward the message to another available partition.</para>
/// </remarks>
///
public class EventHubProducerClient : IAsyncDisposable
{
/// <summary>The maximum number of attempts that may be made to get a <see cref="TransportProducer" /> from the pool.</summary>
internal const int MaximumCreateProducerAttempts = 3;
/// <summary>The minimum allowable size, in bytes, for a batch to be sent.</summary>
internal const int MinimumBatchSizeLimit = 24;
/// <summary>The set of default publishing options to use when no specific options are requested.</summary>
private static readonly SendEventOptions DefaultSendOptions = new SendEventOptions();
/// <summary>Sets how long a dedicated <see cref="TransportProducer" /> would sit in memory before its <see cref="TransportProducerPool" /> would remove and close it.</summary>
private static readonly TimeSpan PartitionProducerLifespan = TimeSpan.FromMinutes(5);
/// <summary>Indicates whether or not this instance has been closed.</summary>
private volatile bool _closed = false;
/// <summary>
/// The fully qualified Event Hubs namespace that the producer is associated with. This is likely
/// to be similar to <c>{yournamespace}.servicebus.windows.net</c>.
/// </summary>
///
public string FullyQualifiedNamespace => Connection.FullyQualifiedNamespace;
/// <summary>
/// The name of the Event Hub that the producer is connected to, specific to the
/// Event Hubs namespace that contains it.
/// </summary>
///
public string EventHubName => Connection.EventHubName;
/// <summary>
/// Indicates whether or not this <see cref="EventHubProducerClient" /> has been closed.
/// </summary>
///
/// <value>
/// <c>true</c> if the client is closed; otherwise, <c>false</c>.
/// </value>
///
public bool IsClosed
{
get => _closed;
protected set => _closed = value;
}
/// <summary>
/// Indicates whether the client has ownership of the associated <see cref="EventHubConnection" />
/// and should take responsibility for managing its lifespan.
/// </summary>
///
private bool OwnsConnection { get; } = true;
/// <summary>
/// The policy to use for determining retry behavior for when an operation fails.
/// </summary>
///
private EventHubsRetryPolicy RetryPolicy { get; }
/// <summary>
/// The set of options to use with the <see cref="EventHubProducerClient" /> instance.
/// </summary>
///
private EventHubProducerClientOptions Options { get; }
/// <summary>
/// The active connection to the Azure Event Hubs service, enabling client communications for metadata
/// about the associated Event Hub and access to a transport-aware producer.
/// </summary>
///
private EventHubConnection Connection { get; }
/// <summary>
/// A <see cref="TransportProducerPool" /> used to manage a set of partition specific <see cref="TransportProducer" />.
/// </summary>
///
private TransportProducerPool PartitionProducerPool { get; }
/// <summary>
/// The publishing-related state associated with partitions.
/// </summary>
///
/// <value>
/// Created if the producer has been configured with one or more features which requires
/// publishing to partitions in a stateful manner; otherwise, <c>null</c>.
/// </value>
///
private ConcurrentDictionary<string, PartitionPublishingState> PartitionState { get; }
/// <summary>
/// Initializes a new instance of the <see cref="EventHubProducerClient" /> class.
/// </summary>
///
/// <param name="connectionString">The connection string to use for connecting to the Event Hubs namespace; it is expected that the Event Hub name and the shared key properties are contained in this connection string.</param>
///
/// <remarks>
/// If the connection string is copied from the Event Hubs namespace, it will likely not contain the name of the desired Event Hub,
/// which is needed. In this case, the name can be added manually by adding ";EntityPath=[[ EVENT HUB NAME ]]" to the end of the
/// connection string. For example, ";EntityPath=telemetry-hub".
///
/// If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string from that
/// Event Hub will result in a connection string that contains the name.
/// </remarks>
///
/// <seealso href="https://docs.microsoft.com/en-us/azure/event-hubs/event-hubs-get-connection-string"/>
///
public EventHubProducerClient(string connectionString) : this(connectionString, null, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="EventHubProducerClient" /> class.
/// </summary>
///
/// <param name="connectionString">The connection string to use for connecting to the Event Hubs namespace; it is expected that the Event Hub name and the shared key properties are contained in this connection string.</param>
/// <param name="clientOptions">The set of options to use for this consumer.</param>
///
/// <remarks>
/// If the connection string is copied from the Event Hubs namespace, it will likely not contain the name of the desired Event Hub,
/// which is needed. In this case, the name can be added manually by adding ";EntityPath=[[ EVENT HUB NAME ]]" to the end of the
/// connection string. For example, ";EntityPath=telemetry-hub".
///
/// If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string from that
/// Event Hub will result in a connection string that contains the name.
/// </remarks>
///
/// <seealso href="https://docs.microsoft.com/en-us/azure/event-hubs/event-hubs-get-connection-string"/>
///
public EventHubProducerClient(string connectionString,
EventHubProducerClientOptions clientOptions) : this(connectionString, null, clientOptions)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="EventHubProducerClient" /> class.
/// </summary>
///
/// <param name="connectionString">The connection string to use for connecting to the Event Hubs namespace; it is expected that the shared key properties are contained in this connection string, but not the Event Hub name.</param>
/// <param name="eventHubName">The name of the specific Event Hub to associate the producer with.</param>
///
/// <remarks>
/// If the connection string is copied from the Event Hub itself, it will contain the name of the desired Event Hub,
/// and can be used directly without passing the <paramref name="eventHubName" />. The name of the Event Hub should be
/// passed only once, either as part of the connection string or separately.
/// </remarks>
///
/// <seealso href="https://docs.microsoft.com/en-us/azure/event-hubs/event-hubs-get-connection-string"/>
///
public EventHubProducerClient(string connectionString,
string eventHubName) : this(connectionString, eventHubName, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="EventHubProducerClient" /> class.
/// </summary>
///
/// <param name="connectionString">The connection string to use for connecting to the Event Hubs namespace; it is expected that the shared key properties are contained in this connection string, but not the Event Hub name.</param>
/// <param name="eventHubName">The name of the specific Event Hub to associate the producer with.</param>
/// <param name="clientOptions">A set of options to apply when configuring the producer.</param>
///
/// <remarks>
/// If the connection string is copied from the Event Hub itself, it will contain the name of the desired Event Hub,
/// and can be used directly without passing the <paramref name="eventHubName" />. The name of the Event Hub should be
/// passed only once, either as part of the connection string or separately.
/// </remarks>
///
/// <seealso href="https://docs.microsoft.com/en-us/azure/event-hubs/event-hubs-get-connection-string"/>
///
public EventHubProducerClient(string connectionString,
string eventHubName,
EventHubProducerClientOptions clientOptions)
{
Argument.AssertNotNullOrEmpty(connectionString, nameof(connectionString));
clientOptions = clientOptions?.Clone() ?? new EventHubProducerClientOptions();
OwnsConnection = true;
Connection = new EventHubConnection(connectionString, eventHubName, clientOptions.ConnectionOptions);
RetryPolicy = clientOptions.RetryOptions.ToRetryPolicy();
Options = clientOptions;
PartitionProducerPool = new TransportProducerPool(partitionId =>
Connection.CreateTransportProducer(
partitionId,
clientOptions.CreateFeatureFlags(),
Options.GetPublishingOptionsOrDefaultForPartition(partitionId),
RetryPolicy));
if (RequiresStatefulPartitions(clientOptions))
{
PartitionState = new ConcurrentDictionary<string, PartitionPublishingState>();
}
}
/// <summary>
/// Initializes a new instance of the <see cref="EventHubProducerClient" /> class.
/// </summary>
///
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace to connect to. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub to associate the producer with.</param>
/// <param name="credential">The Azure managed identity credential to use for authorization. Access controls may be specified by the Event Hubs namespace or the requested Event Hub, depending on Azure configuration.</param>
/// <param name="clientOptions">A set of options to apply when configuring the producer.</param>
///
public EventHubProducerClient(string fullyQualifiedNamespace,
string eventHubName,
TokenCredential credential,
EventHubProducerClientOptions clientOptions = default)
{
Argument.AssertWellFormedEventHubsNamespace(fullyQualifiedNamespace, nameof(fullyQualifiedNamespace));
Argument.AssertNotNullOrEmpty(eventHubName, nameof(eventHubName));
Argument.AssertNotNull(credential, nameof(credential));
clientOptions = clientOptions?.Clone() ?? new EventHubProducerClientOptions();
OwnsConnection = true;
Connection = new EventHubConnection(fullyQualifiedNamespace, eventHubName, credential, clientOptions.ConnectionOptions);
Options = clientOptions;
RetryPolicy = clientOptions.RetryOptions.ToRetryPolicy();
PartitionProducerPool = new TransportProducerPool(partitionId =>
Connection.CreateTransportProducer(
partitionId,
clientOptions.CreateFeatureFlags(),
Options.GetPublishingOptionsOrDefaultForPartition(partitionId),
RetryPolicy));
if (RequiresStatefulPartitions(clientOptions))
{
PartitionState = new ConcurrentDictionary<string, PartitionPublishingState>();
}
}
/// <summary>
/// Initializes a new instance of the <see cref="EventHubProducerClient" /> class.
/// </summary>
///
/// <param name="connection">The <see cref="EventHubConnection" /> connection to use for communication with the Event Hubs service.</param>
/// <param name="clientOptions">A set of options to apply when configuring the producer.</param>
///
public EventHubProducerClient(EventHubConnection connection,
EventHubProducerClientOptions clientOptions = default)
{
Argument.AssertNotNull(connection, nameof(connection));
clientOptions = clientOptions?.Clone() ?? new EventHubProducerClientOptions();
OwnsConnection = false;
Connection = connection;
RetryPolicy = clientOptions.RetryOptions.ToRetryPolicy();
Options = clientOptions;
PartitionProducerPool = new TransportProducerPool(partitionId =>
Connection.CreateTransportProducer(
partitionId,
clientOptions.CreateFeatureFlags(),
Options.GetPublishingOptionsOrDefaultForPartition(partitionId),
RetryPolicy));
if (RequiresStatefulPartitions(clientOptions))
{
PartitionState = new ConcurrentDictionary<string, PartitionPublishingState>();
}
}
/// <summary>
/// Initializes a new instance of the <see cref="EventHubProducerClient" /> class.
/// </summary>
///
/// <param name="connection">The connection to use as the basis for delegation of client-type operations.</param>
/// <param name="transportProducer">The transport producer instance to use as the basis for service communication.</param>
/// <param name="partitionProducerPool">A <see cref="TransportProducerPool" /> used to manage a set of partition specific <see cref="TransportProducer" />.</param>
///
/// <remarks>
/// This constructor is intended to be used internally for functional
/// testing only.
/// </remarks>
///
internal EventHubProducerClient(EventHubConnection connection,
TransportProducer transportProducer,
TransportProducerPool partitionProducerPool = default)
{
Argument.AssertNotNull(connection, nameof(connection));
Argument.AssertNotNull(transportProducer, nameof(transportProducer));
OwnsConnection = false;
Connection = connection;
RetryPolicy = new EventHubsRetryOptions().ToRetryPolicy();
Options = new EventHubProducerClientOptions();
PartitionProducerPool = partitionProducerPool ?? new TransportProducerPool(partitionId => transportProducer);
if (RequiresStatefulPartitions(Options))
{
PartitionState = new ConcurrentDictionary<string, PartitionPublishingState>();
}
}
/// <summary>
/// Initializes a new instance of the <see cref="EventHubProducerClient" /> class.
/// </summary>
///
protected EventHubProducerClient()
{
OwnsConnection = false;
}
/// <summary>
/// Retrieves information about the Event Hub that the connection is associated with, including
/// the number of partitions present and their identifiers.
/// </summary>
///
/// <param name="cancellationToken">An optional <see cref="CancellationToken" /> instance to signal the request to cancel the operation.</param>
///
/// <returns>The set of information for the Event Hub that this client is associated with.</returns>
///
public virtual async Task<EventHubProperties> GetEventHubPropertiesAsync(CancellationToken cancellationToken = default)
{
Argument.AssertNotClosed(IsClosed, nameof(EventHubProducerClient));
return await Connection.GetPropertiesAsync(RetryPolicy, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Retrieves the set of identifiers for the partitions of an Event Hub.
/// </summary>
///
/// <param name="cancellationToken">An optional <see cref="CancellationToken" /> instance to signal the request to cancel the operation.</param>
///
/// <returns>The set of identifiers for the partitions within the Event Hub that this client is associated with.</returns>
///
/// <remarks>
/// This method is synonymous with invoking <see cref="GetEventHubPropertiesAsync(CancellationToken)" /> and reading the <see cref="EventHubProperties.PartitionIds" />
/// property that is returned. It is offered as a convenience for quick access to the set of partition identifiers for the associated Event Hub.
/// No new or extended information is presented.
/// </remarks>
///
public virtual async Task<string[]> GetPartitionIdsAsync(CancellationToken cancellationToken = default)
{
Argument.AssertNotClosed(IsClosed, nameof(EventHubProducerClient));
return await Connection.GetPartitionIdsAsync(RetryPolicy, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Retrieves information about a specific partition for an Event Hub, including elements that describe the available
/// events in the partition event stream.
/// </summary>
///
/// <param name="partitionId">The unique identifier of a partition associated with the Event Hub.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken" /> instance to signal the request to cancel the operation.</param>
///
/// <returns>The set of information for the requested partition under the Event Hub this client is associated with.</returns>
///
public virtual async Task<PartitionProperties> GetPartitionPropertiesAsync(string partitionId,
CancellationToken cancellationToken = default)
{
Argument.AssertNotClosed(IsClosed, nameof(EventHubProducerClient));
return await Connection.GetPartitionPropertiesAsync(partitionId, RetryPolicy, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// A set of information about the state of publishing for a partition, as observed by the <see cref="EventHubProducerClient" />. This
/// data can always be read, but will only be populated with information relevant to the features which are active for the producer client.
/// </summary>
///
/// <param name="partitionId">The unique identifier of a partition associated with the Event Hub.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken" /> instance to signal the request to cancel the operation.</param>
///
/// <returns>The set of information about the publishing state of the requested partition, within the context of this producer.</returns>
///
public virtual async Task<PartitionPublishingProperties> ReadPartitionPublishingPropertiesAsync(string partitionId,
CancellationToken cancellationToken = default)
{
Argument.AssertNotClosed(IsClosed, nameof(EventHubProducerClient));
Argument.AssertNotNullOrEmpty(partitionId, nameof(partitionId));
var partitionState = PartitionState.GetOrAdd(partitionId, new PartitionPublishingState(partitionId));
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
try
{
await partitionState.PublishingGuard.WaitAsync(cancellationToken).ConfigureAwait(false);
if (!partitionState.IsInitialized)
{
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
await InitializePartitionStateAsync(partitionState, cancellationToken).ConfigureAwait(false);
}
return CreatePublishingPropertiesFromPartitionState(Options, partitionState);
}
finally
{
partitionState.PublishingGuard.Release();
}
}
/// <summary>
/// Sends an event to the associated Event Hub using a batched approach. If the size of the event exceeds the
/// maximum size of a single batch, an exception will be triggered and the send will fail.
/// </summary>
///
/// <param name="eventData">The event data to send.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken" /> instance to signal the request to cancel the operation.</param>
///
/// <returns>A task to be resolved on when the operation has completed.</returns>
///
/// <seealso cref="SendAsync(EventData, SendEventOptions, CancellationToken)" />
/// <seealso cref="SendAsync(IEnumerable{EventData}, CancellationToken)" />
/// <seealso cref="SendAsync(IEnumerable{EventData}, SendEventOptions, CancellationToken)" />
/// <seealso cref="SendAsync(EventDataBatch, CancellationToken)" />
///
internal virtual async Task SendAsync(EventData eventData,
CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(eventData, nameof(eventData));
await SendAsync(new[] { eventData }, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Sends an event to the associated Event Hub using a batched approach. If the size of the event exceeds the
/// maximum size of a single batch, an exception will be triggered and the send will fail.
/// </summary>
///
/// <param name="eventData">The event data to send.</param>
/// <param name="options">The set of options to consider when sending this batch.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken" /> instance to signal the request to cancel the operation.</param>
///
/// <returns>A task to be resolved on when the operation has completed.</returns>
///
/// <seealso cref="SendAsync(EventData, CancellationToken)" />
/// <seealso cref="SendAsync(IEnumerable{EventData}, CancellationToken)" />
/// <seealso cref="SendAsync(IEnumerable{EventData}, SendEventOptions, CancellationToken)" />
/// <seealso cref="SendAsync(EventDataBatch, CancellationToken)" />
///
internal virtual async Task SendAsync(EventData eventData,
SendEventOptions options,
CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(eventData, nameof(eventData));
await SendAsync(new[] { eventData }, options, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Sends a set of events to the associated Event Hub using a batched approach. Because the batch is implicitly created, the size of the event set is not
/// validated until this method is invoked. The call will fail if the size of the specified set of events exceeds the maximum allowable size of a single batch.
/// </summary>
///
/// <param name="eventSet">The set of event data to send.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken" /> instance to signal the request to cancel the operation.</param>
///
/// <returns>A task to be resolved on when the operation has completed.</returns>
///
/// <exception cref="EventHubsException">
/// Occurs when the set of events exceeds the maximum size allowed in a single batch, as determined by the Event Hubs service. The <see cref="EventHubsException.Reason" /> will be set to
/// <see cref="EventHubsException.FailureReason.MessageSizeExceeded"/> in this case.
/// </exception>
///
/// <seealso cref="SendAsync(IEnumerable{EventData}, SendEventOptions, CancellationToken)" />
/// <seealso cref="SendAsync(EventDataBatch, CancellationToken)" />
/// <seealso cref="CreateBatchAsync(CancellationToken)" />
///
public virtual async Task SendAsync(IEnumerable<EventData> eventSet,
CancellationToken cancellationToken = default) => await SendAsync(eventSet, null, cancellationToken).ConfigureAwait(false);
/// <summary>
/// Sends a set of events to the associated Event Hub using a batched approach. Because the batch is implicitly created, the size of the event set is not
/// validated until this method is invoked. The call will fail if the size of the specified set of events exceeds the maximum allowable size of a single batch.
/// </summary>
///
/// <param name="eventSet">The set of event data to send.</param>
/// <param name="options">The set of options to consider when sending this batch.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken" /> instance to signal the request to cancel the operation.</param>
///
/// <returns>A task to be resolved on when the operation has completed.</returns>
///
/// <exception cref="EventHubsException">
/// Occurs when the set of events exceeds the maximum size allowed in a single batch, as determined by the Event Hubs service. The <see cref="EventHubsException.Reason" /> will be set to
/// <see cref="EventHubsException.FailureReason.MessageSizeExceeded"/> in this case.
/// </exception>
///
/// <seealso cref="SendAsync(IEnumerable{EventData}, CancellationToken)" />
/// <seealso cref="SendAsync(EventDataBatch, CancellationToken)" />
/// <seealso cref="CreateBatchAsync(CreateBatchOptions, CancellationToken)" />
///
public virtual async Task SendAsync(IEnumerable<EventData> eventSet,
SendEventOptions options,
CancellationToken cancellationToken = default)
{
options = options?.Clone() ?? DefaultSendOptions;
Argument.AssertNotNull(eventSet, nameof(eventSet));
AssertSinglePartitionReference(options.PartitionId, options.PartitionKey);
var events = eventSet switch
{
IReadOnlyList<EventData> eventList => eventList,
_ => eventSet.ToList()
};
if (events.Count == 0)
{
return;
}
var sendTask = (Options.EnableIdempotentPartitions)
? SendIdempotentAsync(events, options, cancellationToken)
: SendInternalAsync(events, options, cancellationToken);
await sendTask.ConfigureAwait(false);
}
/// <summary>
/// Sends a set of events to the associated Event Hub using a batched approach.
/// </summary>
///
/// <param name="eventBatch">The set of event data to send. A batch may be created using <see cref="CreateBatchAsync(CancellationToken)" />.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken" /> instance to signal the request to cancel the operation.</param>
///
/// <returns>A task to be resolved on when the operation has completed.</returns>
///
/// <seealso cref="CreateBatchAsync(CancellationToken)" />
///
public virtual async Task SendAsync(EventDataBatch eventBatch,
CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(eventBatch, nameof(eventBatch));
AssertSinglePartitionReference(eventBatch.SendOptions.PartitionId, eventBatch.SendOptions.PartitionKey);
if (eventBatch.Count == 0)
{
return;
}
var sendTask = (!Options.EnableIdempotentPartitions)
? SendInternalAsync(eventBatch, cancellationToken)
: SendIdempotentAsync(eventBatch, cancellationToken);
await sendTask.ConfigureAwait(false);
}
/// <summary>
/// Creates a size-constraint batch to which <see cref="EventData" /> may be added using a try-based pattern. If an event would
/// exceed the maximum allowable size of the batch, the batch will not allow adding the event and signal that scenario using its
/// return value.
///
/// Because events that would violate the size constraint cannot be added, publishing a batch will not trigger an exception when
/// attempting to send the events to the Event Hubs service.
/// </summary>
///
/// <param name="cancellationToken">An optional <see cref="CancellationToken" /> instance to signal the request to cancel the operation.</param>
///
/// <returns>An <see cref="EventDataBatch" /> with the default batch options.</returns>
///
/// <seealso cref="CreateBatchAsync(CreateBatchOptions, CancellationToken)" />
/// <seealso cref="SendAsync(EventDataBatch, CancellationToken)" />
///
public virtual async ValueTask<EventDataBatch> CreateBatchAsync(CancellationToken cancellationToken = default) => await CreateBatchAsync(null, cancellationToken).ConfigureAwait(false);
/// <summary>
/// Creates a size-constraint batch to which <see cref="EventData" /> may be added using a try-based pattern. If an event would
/// exceed the maximum allowable size of the batch, the batch will not allow adding the event and signal that scenario using its
/// return value.
///
/// Because events that would violate the size constraint cannot be added, publishing a batch will not trigger an exception when
/// attempting to send the events to the Event Hubs service.
/// </summary>
///
/// <param name="options">The set of options to consider when creating this batch.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken" /> instance to signal the request to cancel the operation.</param>
///
/// <returns>An <see cref="EventDataBatch" /> with the requested <paramref name="options"/>.</returns>
///
/// <seealso cref="CreateBatchAsync(CancellationToken)" />
/// <seealso cref="SendAsync(EventDataBatch, CancellationToken)" />
///
public virtual async ValueTask<EventDataBatch> CreateBatchAsync(CreateBatchOptions options,
CancellationToken cancellationToken = default)
{
options = options?.Clone() ?? new CreateBatchOptions();
AssertSinglePartitionReference(options.PartitionId, options.PartitionKey);
TransportEventBatch transportBatch = await PartitionProducerPool.EventHubProducer.CreateBatchAsync(options, cancellationToken).ConfigureAwait(false);
return new EventDataBatch(transportBatch, FullyQualifiedNamespace, EventHubName, options);
}
/// <summary>
/// Closes the producer.
/// </summary>
///
/// <param name="cancellationToken">An optional <see cref="CancellationToken" /> instance to signal the request to cancel the operation.</param>
///
/// <returns>A task to be resolved on when the operation has completed.</returns>
///
public virtual async Task CloseAsync(CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
if (IsClosed)
{
return;
}
IsClosed = true;
var identifier = GetHashCode().ToString(CultureInfo.InvariantCulture);
EventHubsEventSource.Log.ClientCloseStart(nameof(EventHubProducerClient), EventHubName, identifier);
// Attempt to close the pool of producers. In the event that an exception is encountered,
// it should not impact the attempt to close the connection, assuming ownership.
var transportProducerPoolException = default(Exception);
try
{
await PartitionProducerPool.CloseAsync(cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
EventHubsEventSource.Log.ClientCloseError(nameof(EventHubProducerClient), EventHubName, identifier, ex.Message);
transportProducerPoolException = ex;
}
// An exception when closing the connection supersedes one observed when closing the
// individual transport clients.
try
{
if (OwnsConnection)
{
await Connection.CloseAsync().ConfigureAwait(false);
}
}
catch (Exception ex)
{
EventHubsEventSource.Log.ClientCloseError(nameof(EventHubProducerClient), EventHubName, identifier, ex.Message);
throw;
}
finally
{
EventHubsEventSource.Log.ClientCloseComplete(nameof(EventHubProducerClient), EventHubName, identifier);
}
// If there was an active exception pending from closing the
// transport producer pool, surface it now.
if (transportProducerPoolException != default)
{
ExceptionDispatchInfo.Capture(transportProducerPoolException).Throw();
}
}
/// <summary>
/// Performs the task needed to clean up resources used by the <see cref="EventHubProducerClient" />,
/// including ensuring that the client itself has been closed.
/// </summary>
///
/// <returns>A task to be resolved on when the operation has completed.</returns>
///
[SuppressMessage("Usage", "AZC0002:Ensure all service methods take an optional CancellationToken parameter.", Justification = "This signature must match the IAsyncDisposable interface.")]
public virtual async ValueTask DisposeAsync() => await CloseAsync().ConfigureAwait(false);
/// <summary>
/// Determines whether the specified <see cref="System.Object" /> is equal to this instance.
/// </summary>
///
/// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param>
///
/// <returns><c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>.</returns>
///
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj) => base.Equals(obj);
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
///
/// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns>
///
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => base.GetHashCode();
/// <summary>
/// Converts the instance to string representation.
/// </summary>
///
/// <returns>A <see cref="System.String" /> that represents this instance.</returns>
///
[EditorBrowsable(EditorBrowsableState.Never)]
public override string ToString() => base.ToString();
/// <summary>
/// Sends a set of events to the associated Event Hub using a batched approach. Because the batch is implicitly created, the size of the event set is not
/// validated until this method is invoked. The call will fail if the size of the specified set of events exceeds the maximum allowable size of a single batch.
/// </summary>
///
/// <param name="events">The set of event data to send.</param>
/// <param name="options">The set of options to consider when sending this batch.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken" /> instance to signal the request to cancel the operation.</param>
///
private async Task SendInternalAsync(IReadOnlyList<EventData> events,
SendEventOptions options,
CancellationToken cancellationToken = default)
{
var attempts = 0;
var diagnosticIdentifiers = new List<string>();
InstrumentMessages(events);
foreach (var eventData in events)
{
if (EventDataInstrumentation.TryExtractDiagnosticId(eventData, out var identifier))
{
diagnosticIdentifiers.Add(identifier);
}
}
using DiagnosticScope scope = CreateDiagnosticScope(diagnosticIdentifiers);
var pooledProducer = PartitionProducerPool.GetPooledProducer(options.PartitionId, PartitionProducerLifespan);
while (!cancellationToken.IsCancellationRequested)
{
try
{
await using var _ = pooledProducer.ConfigureAwait(false);
await pooledProducer.TransportProducer.SendAsync(events, options, cancellationToken).ConfigureAwait(false);
return;
}
catch (EventHubsException eventHubException)
when (eventHubException.Reason == EventHubsException.FailureReason.ClientClosed && ShouldRecreateProducer(pooledProducer.TransportProducer, options.PartitionId))
{
if (++attempts >= MaximumCreateProducerAttempts)
{
scope.Failed(eventHubException);
throw;
}
pooledProducer = PartitionProducerPool.GetPooledProducer(options.PartitionId, PartitionProducerLifespan);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
throw new TaskCanceledException();
}
/// <summary>
/// Sends a set of events to the associated Event Hub using a batched approach.
/// </summary>
///
/// <param name="eventBatch">The set of event data to send. A batch may be created using <see cref="CreateBatchAsync(CancellationToken)" />.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken" /> instance to signal the request to cancel the operation.</param>
///
private async Task SendInternalAsync(EventDataBatch eventBatch,
CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = CreateDiagnosticScope(eventBatch.GetEventDiagnosticIdentifiers());
var attempts = 0;
var pooledProducer = PartitionProducerPool.GetPooledProducer(eventBatch.SendOptions.PartitionId, PartitionProducerLifespan);
try
{
while (!cancellationToken.IsCancellationRequested)
{
try
{
await using var _ = pooledProducer.ConfigureAwait(false);
eventBatch.Lock();
await pooledProducer.TransportProducer.SendAsync(eventBatch, cancellationToken).ConfigureAwait(false);
return;
}
catch (EventHubsException eventHubException)
when (eventHubException.Reason == EventHubsException.FailureReason.ClientClosed && ShouldRecreateProducer(pooledProducer.TransportProducer, eventBatch.SendOptions.PartitionId))
{
if (++attempts >= MaximumCreateProducerAttempts)
{
scope.Failed(eventHubException);
throw;
}
pooledProducer = PartitionProducerPool.GetPooledProducer(eventBatch.SendOptions.PartitionId, PartitionProducerLifespan);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
}
finally
{
eventBatch.Unlock();
}
throw new TaskCanceledException();
}
/// <summary>
/// Sends a set of events to the associated Event Hub using a batched approach. Because the batch is implicitly created, the size of the event set is not
/// validated until this method is invoked. The call will fail if the size of the specified set of events exceeds the maximum allowable size of a single batch.
/// </summary>
///
/// <param name="eventSet">The set of event data to send.</param>
/// <param name="options">The set of options to consider when sending this batch.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken" /> instance to signal the request to cancel the operation.</param>
///
private async Task SendIdempotentAsync(IReadOnlyList<EventData> eventSet,
SendEventOptions options,
CancellationToken cancellationToken = default)
{
AssertPartitionIsReferenced(options.PartitionId);
AssertIdempotentEventsNotPublished(eventSet);
try
{
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
EventHubsEventSource.Log.IdempotentPublishStart(EventHubName, options.PartitionId);
var partitionState = PartitionState.GetOrAdd(options.PartitionId, new PartitionPublishingState(options.PartitionId));
try
{
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
await partitionState.PublishingGuard.WaitAsync(cancellationToken).ConfigureAwait(false);
EventHubsEventSource.Log.IdempotentSynchronizationAcquire(EventHubName, options.PartitionId);
// Ensure that the partition state has been initialized.
if (!partitionState.IsInitialized)
{
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
await InitializePartitionStateAsync(partitionState, cancellationToken).ConfigureAwait(false);
}
// Sequence the events for publishing.
var lastSequence = partitionState.LastPublishedSequenceNumber.Value;
var firstSequence = lastSequence;
foreach (var eventData in eventSet)
{
lastSequence = NextSequence(lastSequence);
eventData.PendingPublishSequenceNumber = lastSequence;
}
// Publish the events.
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
EventHubsEventSource.Log.IdempotentSequencePublish(EventHubName, options.PartitionId, firstSequence, lastSequence);
await SendInternalAsync(eventSet, options, cancellationToken).ConfigureAwait(false);
// Update state and commit the sequencing.
EventHubsEventSource.Log.IdempotentSequenceUpdate(EventHubName, options.PartitionId, partitionState.LastPublishedSequenceNumber.Value, lastSequence);
partitionState.LastPublishedSequenceNumber = lastSequence;
foreach (var eventData in eventSet)
{
eventData.CommitPublishingState();
}
}
catch
{
// Clear the pending sequence numbers in the face of an exception.
foreach (var eventData in eventSet)
{
eventData.PendingPublishSequenceNumber = null;
}
throw;
}
finally
{
partitionState.PublishingGuard.Release();
EventHubsEventSource.Log.IdempotentSynchronizationRelease(EventHubName, options.PartitionId);
}
}
catch (Exception ex)
{
EventHubsEventSource.Log.IdempotentPublishError(EventHubName, options.PartitionId, ex.Message);
throw;
}
finally
{
EventHubsEventSource.Log.IdempotentPublishComplete(EventHubName, options.PartitionId);
}
}
/// <summary>
/// Sends a set of events to the associated Event Hub using a batched approach.
/// </summary>
///
/// <param name="eventBatch">The set of event data to send. A batch may be created using <see cref="CreateBatchAsync(CancellationToken)" />.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken" /> instance to signal the request to cancel the operation.</param>
///
private async Task SendIdempotentAsync(EventDataBatch eventBatch,
CancellationToken cancellationToken = default)
{
var options = eventBatch.SendOptions;
AssertPartitionIsReferenced(options.PartitionId);
AssertIdempotentBatchNotPublished(eventBatch);
try
{
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
EventHubsEventSource.Log.IdempotentPublishStart(EventHubName, options.PartitionId);
var partitionState = PartitionState.GetOrAdd(options.PartitionId, new PartitionPublishingState(options.PartitionId));
var eventSet = eventBatch.AsEnumerable<EventData>() switch
{
IReadOnlyList<EventData> eventList => eventList,
IEnumerable<EventData> eventEnumerable => eventEnumerable.ToList()
};
try
{
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
await partitionState.PublishingGuard.WaitAsync(cancellationToken).ConfigureAwait(false);
EventHubsEventSource.Log.IdempotentSynchronizationAcquire(EventHubName, options.PartitionId);
// Ensure that the partition state has been initialized.
if (!partitionState.IsInitialized)
{
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
await InitializePartitionStateAsync(partitionState, cancellationToken).ConfigureAwait(false);
}
// Sequence the events for publishing.
var lastSequence = partitionState.LastPublishedSequenceNumber.Value;
var firstSequence = NextSequence(lastSequence);
foreach (var eventData in eventSet)
{
lastSequence = NextSequence(lastSequence);
eventData.PendingPublishSequenceNumber = lastSequence;
}
// Publish the events.
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
EventHubsEventSource.Log.IdempotentSequencePublish(EventHubName, options.PartitionId, firstSequence, lastSequence);
await SendInternalAsync(eventBatch, cancellationToken).ConfigureAwait(false);
// Update state and commit the sequencing. This needs only to happen at the batch level, as the contained
// events are not accessible by callers.
EventHubsEventSource.Log.IdempotentSequenceUpdate(EventHubName, options.PartitionId, partitionState.LastPublishedSequenceNumber.Value, lastSequence);
partitionState.LastPublishedSequenceNumber = lastSequence;
eventBatch.StartingPublishedSequenceNumber = firstSequence;
}
catch
{
// Clear the pending sequence numbers in the face of an exception.
foreach (var eventData in eventSet)
{
eventData.PendingPublishSequenceNumber = null;
}
throw;
}
finally
{
partitionState.PublishingGuard.Release();
EventHubsEventSource.Log.IdempotentSynchronizationRelease(EventHubName, options.PartitionId);
}
}
catch (Exception ex)
{
EventHubsEventSource.Log.IdempotentPublishError(EventHubName, options.PartitionId, ex.Message);
throw;
}
finally
{
EventHubsEventSource.Log.IdempotentPublishComplete(EventHubName, options.PartitionId);
}
}
/// <summary>
/// Initializes state instance for a given partition.
/// </summary>
///
/// <param name="partitionState">The state of the partition to be initialized. This parameter will be mutated by this call.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken" /> instance to signal the request to cancel the operation.</param>
///
/// <remarks>
/// The <paramref name="partitionState"/> parameter will be mutated by this call. To avoid duplicate initialization or state corruption, this
/// method should only be called while the <see cref="PartitionPublishingState.PublishingGuard" /> primitive of the state instance is held.
/// </remarks>
///
private async Task InitializePartitionStateAsync(PartitionPublishingState partitionState,
CancellationToken cancellationToken = default)
{
if (partitionState.IsInitialized)
{
return;
}
var attempts = 0;
var pooledProducer = PartitionProducerPool.GetPooledProducer(partitionState.PartitionId, PartitionProducerLifespan);
while (!cancellationToken.IsCancellationRequested)
{
try
{
await using var _ = pooledProducer.ConfigureAwait(false);
var properties = await pooledProducer.TransportProducer.ReadInitializationPublishingPropertiesAsync(cancellationToken).ConfigureAwait(false);
partitionState.ProducerGroupId = properties.ProducerGroupId;
partitionState.OwnerLevel = properties.OwnerLevel;
partitionState.LastPublishedSequenceNumber = properties.LastPublishedSequenceNumber;
// If the state was not initialized and no exception has occurred, then the service is behaving
// unexpectedly and the client should be considered invalid.
if (!partitionState.IsInitialized)
{
throw new EventHubsException(false, EventHubName, EventHubsException.FailureReason.InvalidClientState);
}
EventHubsEventSource.Log.IdempotentPublishInitializeState(
EventHubName,
partitionState.PartitionId,
partitionState.ProducerGroupId.Value,
partitionState.OwnerLevel.Value,
partitionState.LastPublishedSequenceNumber.Value);
return;
}
catch (EventHubsException eventHubException)
when (eventHubException.Reason == EventHubsException.FailureReason.ClientClosed && ShouldRecreateProducer(pooledProducer.TransportProducer, partitionState.PartitionId))
{
if (++attempts >= MaximumCreateProducerAttempts)
{
throw;
}
pooledProducer = PartitionProducerPool.GetPooledProducer(partitionState.PartitionId, PartitionProducerLifespan);
}
}
throw new TaskCanceledException();
}
/// <summary>
/// Creates and configures a diagnostics scope to be used for instrumenting
/// events.
/// </summary>
///
/// <param name="diagnosticIdentifiers">The set of diagnostic identifiers to which the scope will be linked.</param>
///
/// <returns>The requested <see cref="DiagnosticScope" />.</returns>
///
private DiagnosticScope CreateDiagnosticScope(IEnumerable<string> diagnosticIdentifiers)
{
DiagnosticScope scope = EventDataInstrumentation.ScopeFactory.CreateScope(DiagnosticProperty.ProducerActivityName);
scope.AddAttribute(DiagnosticProperty.KindAttribute, DiagnosticProperty.ClientKind);
scope.AddAttribute(DiagnosticProperty.ServiceContextAttribute, DiagnosticProperty.EventHubsServiceContext);
scope.AddAttribute(DiagnosticProperty.EventHubAttribute, EventHubName);
scope.AddAttribute(DiagnosticProperty.EndpointAttribute, FullyQualifiedNamespace);
if (scope.IsEnabled)
{
foreach (var identifier in diagnosticIdentifiers)
{
scope.AddLink(identifier);
}
}
scope.Start();
return scope;
}
/// <summary>
/// Performs the actions needed to instrument a set of events.
/// </summary>
///
/// <param name="events">The events to instrument.</param>
///
private void InstrumentMessages(IEnumerable<EventData> events)
{
foreach (EventData eventData in events)
{
EventDataInstrumentation.InstrumentEvent(eventData, FullyQualifiedNamespace, EventHubName);
}
}
/// <summary>
/// Checks if the <see cref="TransportProducer" /> returned by the <see cref="TransportProducerPool" /> is still open.
/// </summary>
///
/// <param name="producer">The <see cref="TransportProducer" /> that has being checked.</param>
/// <param name="partitionId">The unique identifier of a partition associated with the Event Hub.</param>
///
/// <returns><c>true</c> if the specified <see cref="TransportProducer" /> is closed; otherwise, <c>false</c>.</returns>
///
private bool ShouldRecreateProducer(TransportProducer producer,
string partitionId) => !string.IsNullOrEmpty(partitionId)
&& producer.IsClosed
&& !IsClosed
&& !Connection.IsClosed;
/// <summary>
/// Ensures that no more than a single partition reference is active.
/// </summary>
///
/// <param name="partitionId">The identifier of the partition to which the producer is bound.</param>
/// <param name="partitionKey">The hash key for partition routing that was requested for a publish operation.</param>
///
private static void AssertSinglePartitionReference(string partitionId,
string partitionKey)
{
if ((!string.IsNullOrEmpty(partitionId)) && (!string.IsNullOrEmpty(partitionKey)))
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.CannotSendWithPartitionIdAndPartitionKey, partitionKey, partitionId));
}
}
/// <summary>
/// Ensures that a partition reference is active and the request is not for publishing
/// to the Event Hubs gateway.
/// </summary>
///
/// <param name="partitionId">The identifier of the partition to which the producer is bound.</param>
///
private static void AssertPartitionIsReferenced(string partitionId)
{
if (string.IsNullOrEmpty(partitionId))
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.CannotPublishToGateway, partitionId));
}
}
/// <summary>
/// Ensures that a batch of events has not been previously acknowledged by the Event Hubs
/// service as having been successfully published.
/// </summary>
///
/// <param name="batch">The <see cref="EventDataBatch" /> to consider.</param>
///
private static void AssertIdempotentBatchNotPublished(EventDataBatch batch)
{
if ((batch.StartingPublishedSequenceNumber.HasValue)
|| (batch.AsEnumerable<EventData>().Any(eventData => eventData.PublishedSequenceNumber.HasValue)))
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.IdempotentAlreadyPublished));
}
}
/// <summary>
/// Ensures that a batch of events has not been previously acknowledged by the Event Hubs
/// service as having been successfully published.
/// </summary>
///
/// <param name="eventSet">The set of <see cref="EventData" /> to consider.</param>
///
private static void AssertIdempotentEventsNotPublished(IEnumerable<EventData> eventSet)
{
foreach (var eventData in eventSet)
{
if (eventData.PublishedSequenceNumber.HasValue)
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.IdempotentAlreadyPublished));
}
}
}
/// <summary>
/// Calculates the next sequence number based on the current sequence number.
/// </summary>
///
/// <param name="currentSequence">The current sequence number to consider.</param>
///
/// <returns>The next sequence number, in proper order.</returns>
///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int NextSequence(int currentSequence)
{
if (unchecked(++currentSequence) < 0)
{
currentSequence = 0;
}
return currentSequence;
}
/// <summary>
/// Indicates whether publishing requires stateful partitions.
/// </summary>
///
/// <param name="options">The set of options to consider for making the determination.</param>
///
/// <returns><c>true</c> if publishing is stateful; otherwise, <c>false</c>.</returns>
///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool RequiresStatefulPartitions(EventHubProducerClientOptions options) => options.EnableIdempotentPartitions;
/// <summary>
/// Creates a set of publishing properties based on the configuration of a producer and the current
/// partition publishing state.
/// </summary>
///
/// <param name="options">The options that describe the configuration of the producer.</param>
/// <param name="state">The current state of publishing for the partition, as observed by the producer..</param>
///
/// <returns>The set of properties that represents the current state.</returns>
///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static PartitionPublishingProperties CreatePublishingPropertiesFromPartitionState(EventHubProducerClientOptions options,
PartitionPublishingState state) =>
new PartitionPublishingProperties(options.EnableIdempotentPartitions,
state.ProducerGroupId,
state.OwnerLevel,
state.LastPublishedSequenceNumber);
}
}
| 50.498425 | 238 | 0.610497 | [
"MIT"
] | HarshaNalluru/azure-sdk-for-net | sdk/eventhub/Azure.Messaging.EventHubs/src/Producer/EventHubProducerClient.cs | 64,135 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.vod.Model.V20170314;
namespace Aliyun.Acs.vod.Transform.V20170314
{
public class SubmitAIASRJobResponseUnmarshaller
{
public static SubmitAIASRJobResponse Unmarshall(UnmarshallerContext context)
{
SubmitAIASRJobResponse submitAIASRJobResponse = new SubmitAIASRJobResponse();
submitAIASRJobResponse.HttpResponse = context.HttpResponse;
submitAIASRJobResponse.RequestId = context.StringValue("SubmitAIASRJob.RequestId");
SubmitAIASRJobResponse.SubmitAIASRJob_AIASRJob aIASRJob = new SubmitAIASRJobResponse.SubmitAIASRJob_AIASRJob();
aIASRJob.JobId = context.StringValue("SubmitAIASRJob.AIASRJob.JobId");
aIASRJob.MediaId = context.StringValue("SubmitAIASRJob.AIASRJob.MediaId");
aIASRJob.Status = context.StringValue("SubmitAIASRJob.AIASRJob.Status");
aIASRJob.Code = context.StringValue("SubmitAIASRJob.AIASRJob.Code");
aIASRJob.Message = context.StringValue("SubmitAIASRJob.AIASRJob.Message");
aIASRJob.CreationTime = context.StringValue("SubmitAIASRJob.AIASRJob.CreationTime");
aIASRJob.Data = context.StringValue("SubmitAIASRJob.AIASRJob.Data");
submitAIASRJobResponse.AIASRJob = aIASRJob;
return submitAIASRJobResponse;
}
}
}
| 42.5 | 114 | 0.774588 | [
"Apache-2.0"
] | sdk-team/aliyun-openapi-net-sdk | aliyun-net-sdk-vod/Vod/Transform/V20170314/SubmitAIASRJobResponseUnmarshaller.cs | 2,125 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameEnd : MonoBehaviour
{
void OnTriggerEnter2D(Collider2D other) {
var ball = other.GetComponent<Ball>();
if (ball != null)
{
SceneManager.LoadScene(0);
}
}
}
| 21.375 | 46 | 0.654971 | [
"MIT"
] | Adri102/2D-Unity-Game | Assets/Tilemap/Brick/Scripts/GameEnd.cs | 344 | C# |
#region License
// Copyright (c) 2011, ClearCanvas Inc.
// All rights reserved.
// http://www.clearcanvas.ca
//
// This software is licensed under the Open Software License v3.0.
// For the complete license, see http://www.clearcanvas.ca/OSLv3.0
#endregion
using System.ServiceModel;
namespace ClearCanvas.ImageViewer.Common.Automation
{
[ServiceContract(SessionMode = SessionMode.Allowed, ConfigurationName = "IDicomExplorerAutomation", Namespace = AutomationNamespace.Value)]
public interface IDicomExplorerAutomation
{
[FaultContract(typeof(NoLocalStoreFault))]
[FaultContract(typeof(DicomExplorerNotFoundFault))]
[OperationContract(IsOneWay = false)]
SearchLocalStudiesResult SearchLocalStudies(SearchLocalStudiesRequest request);
[FaultContract(typeof(ServerNotFoundFault))]
[FaultContract(typeof(DicomExplorerNotFoundFault))]
[OperationContract(IsOneWay = false)]
SearchRemoteStudiesResult SearchRemoteStudies(SearchRemoteStudiesRequest request);
}
}
| 33.7 | 141 | 0.782394 | [
"Apache-2.0"
] | SNBnani/Xian | ImageViewer/Common/Automation/IDicomExplorerAutomation.cs | 1,011 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.UI.Xaml.Controls
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
#endif
public partial class MenuFlyoutSubItem : global::Windows.UI.Xaml.Controls.MenuFlyoutItemBase
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public string Text
{
get
{
return (string)this.GetValue(TextProperty);
}
set
{
this.SetValue(TextProperty, value);
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public global::System.Collections.Generic.IList<global::Windows.UI.Xaml.Controls.MenuFlyoutItemBase> Items
{
get
{
throw new global::System.NotImplementedException("The member IList<MenuFlyoutItemBase> MenuFlyoutSubItem.Items is not implemented in Uno.");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public global::Windows.UI.Xaml.Controls.IconElement Icon
{
get
{
return (global::Windows.UI.Xaml.Controls.IconElement)this.GetValue(IconProperty);
}
set
{
this.SetValue(IconProperty, value);
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public static global::Windows.UI.Xaml.DependencyProperty TextProperty { get; } =
Windows.UI.Xaml.DependencyProperty.Register(
"Text", typeof(string),
typeof(global::Windows.UI.Xaml.Controls.MenuFlyoutSubItem),
new FrameworkPropertyMetadata(default(string)));
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public static global::Windows.UI.Xaml.DependencyProperty IconProperty { get; } =
Windows.UI.Xaml.DependencyProperty.Register(
"Icon", typeof(global::Windows.UI.Xaml.Controls.IconElement),
typeof(global::Windows.UI.Xaml.Controls.MenuFlyoutSubItem),
new FrameworkPropertyMetadata(default(global::Windows.UI.Xaml.Controls.IconElement)));
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public MenuFlyoutSubItem()
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Xaml.Controls.MenuFlyoutSubItem", "MenuFlyoutSubItem.MenuFlyoutSubItem()");
}
#endif
// Forced skipping of method Windows.UI.Xaml.Controls.MenuFlyoutSubItem.MenuFlyoutSubItem()
// Forced skipping of method Windows.UI.Xaml.Controls.MenuFlyoutSubItem.Items.get
// Forced skipping of method Windows.UI.Xaml.Controls.MenuFlyoutSubItem.Text.get
// Forced skipping of method Windows.UI.Xaml.Controls.MenuFlyoutSubItem.Text.set
// Forced skipping of method Windows.UI.Xaml.Controls.MenuFlyoutSubItem.Icon.get
// Forced skipping of method Windows.UI.Xaml.Controls.MenuFlyoutSubItem.Icon.set
// Forced skipping of method Windows.UI.Xaml.Controls.MenuFlyoutSubItem.IconProperty.get
// Forced skipping of method Windows.UI.Xaml.Controls.MenuFlyoutSubItem.TextProperty.get
}
}
| 38.839506 | 164 | 0.745073 | [
"Apache-2.0"
] | dansiegel/Uno | src/Uno.UI/Generated/3.0.0.0/Windows.UI.Xaml.Controls/MenuFlyoutSubItem.cs | 3,146 | C# |
namespace Morth;
public class CompileError : Exception
{
public CompileError(SourceLocation location, string message) : base($"{location}: {message}")
{
}
}
| 18.888889 | 97 | 0.694118 | [
"MIT"
] | Phytolizer/morth | cs/Morth/CompileError.cs | 170 | C# |
using System;
namespace DotnetSpider.Portal.Common
{
public static class ServiceProvider
{
public static IServiceProvider Instance;
}
} | 15.666667 | 42 | 0.794326 | [
"MIT"
] | ACGSinon/DotnetSpider | src/DotnetSpider.Portal/Common/ServiceProvider.cs | 141 | C# |
using Grimoire.Game;
using System.Threading.Tasks;
namespace Grimoire.Botting.Commands.Misc.Statements
{
public class CmdItemNotPickupable : StatementCommand, IBotCommand
{
public CmdItemNotPickupable()
{
Tag = "Item";
Text = "Has not dropped";
}
public Task Execute(IBotEngine instance)
{
if (World.DropStack.Contains((instance.IsVar(Value1) ? Configuration.Tempvariable[instance.GetVar(Value1)] : Value1)))
{
instance.Index++;
}
return Task.FromResult<object>(null);
}
public override string ToString()
{
return "Item has not dropped: " + Value1;
}
}
} | 26.5 | 131 | 0.572776 | [
"CC0-1.0"
] | 0zl/meow | Grimoire.Botting.Commands.Misc.Statements/CmdItemNotPickupable.cs | 742 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace FirLib.Core.Services.ConfigurationFiles
{
public class ConfigurationFileAccessorApplication : ConfigurationFileAccessorBase
{
public ConfigurationFileAccessorApplication(string appName)
: base(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
appName)
{
}
}
}
| 24.5 | 85 | 0.69161 | [
"MIT"
] | RolandKoenig/FirLib | src/FirLib.Core/Services/ConfigurationFiles/ConfigurationFileAccessorApplication.cs | 443 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entities.Wrappers
{
public class PagedResponse<T> : Response<T>
{
public int PageNumber { get; set; }
public int PageSize { get; set; }
public Uri FirstPage { get; set; }
public Uri LastPage { get; set; }
public int TotalPages { get; set; }
public int TotalRecords { get; set; }
public Uri NextPage { get; set; }
public Uri PreviousPage { get; set; }
public PagedResponse(T data, int pageNumber, int pageSize)
{
this.PageNumber = pageNumber;
this.PageSize = pageSize;
this.Data = data;
this.Message = null;
this.Succeeded = true;
this.Errors = null;
}
}
}
| 28.533333 | 66 | 0.58528 | [
"MIT"
] | MikyM/Portfolio | Entities/Wrappers/PagedResponse.cs | 858 | 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("MeetUp.BLL")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MeetUp.BLL")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[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("3020a898-ae1d-43c0-bc0f-d67fedb54c6f")]
// 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.513514 | 84 | 0.745677 | [
"MIT"
] | Sebastian-Gruchacz/MeetUp4 | Data/MeetUp.BLL/Properties/AssemblyInfo.cs | 1,391 | C# |
using Outcompute.Trader.Trading.Algorithms.Context;
using Outcompute.Trader.Trading.Providers;
namespace Outcompute.Trader.Trading.Commands.RedeemSavings;
internal class RedeemSavingsExecutor : IAlgoCommandExecutor<RedeemSavingsCommand, RedeemSavingsEvent>
{
private readonly ISavingsProvider _savings;
public RedeemSavingsExecutor(ISavingsProvider savings)
{
_savings = savings;
}
public ValueTask<RedeemSavingsEvent> ExecuteAsync(IAlgoContext context, RedeemSavingsCommand command, CancellationToken cancellationToken = default)
{
return _savings.RedeemAsync(command.Asset, command.Amount, cancellationToken);
}
} | 34.947368 | 152 | 0.798193 | [
"MIT"
] | JorgeCandeias/Trader | Trader.Trading/Commands/RedeemSavings/RedeemSavingsExecutor.cs | 666 | C# |
using System;
using SortAlgorithms.QuickSort;
using Xunit;
namespace SortAlgorithms.Tests;
public class TestQuickSort
{
private readonly QuickSortAlgorithm _sut = new QuickSortAlgorithm();
[Fact]
public void Test_QuickSort_UnorderedArray()
{
// Arrange
var inputArray = new[] { 1, 5, 0, 34, 3, 9 };
var expectedArray = new[] { 0, 1, 3, 5, 9, 34 };
// Act
var outputArray = _sut.Sort(inputArray);
// Assert
Assert.Equal(expectedArray, outputArray);
}
[Fact]
public void Test_QuickSort_OrderedArray()
{
// Arrange
var inputArray = new[] { 0, 1, 3, 5, 9, 34 };
var expectedArray = new[] { 0, 1, 3, 5, 9, 34 };
// Act
var outputArray = _sut.Sort(inputArray);
// Assert
Assert.Equal(expectedArray, outputArray);
}
[Fact]
public void Test_QuickSort_EmptyArray()
{
// Arrange
var inputArray = System.Array.Empty<int>();
var expectedMessage = $"The array must contain at least two elements! The passed array has {inputArray.Length} elements.";
// Act
Action act = () => _sut.Sort(inputArray);
// Assert
var exception = Assert.Throws<ArgumentException>(act);
Assert.Equal(expectedMessage, exception.Message);
}
[Fact]
public void Test_QuickSort_NullArray()
{
// Arrange
int[] inputArray = null;
// Act
Action act = () => _sut.Sort(inputArray);
// Assert
Assert.Throws<ArgumentNullException>(act);
}
} | 24.454545 | 130 | 0.580545 | [
"MIT"
] | pncsoares/sort-algorithms | SortAlgorithms/SortAlgorithms.Tests/TestQuickSort.cs | 1,614 | 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 iot-2015-05-28.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.IoT.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.IoT.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for CreateBillingGroup operation
/// </summary>
public class CreateBillingGroupResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
CreateBillingGroupResponse response = new CreateBillingGroupResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("billingGroupArn", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.BillingGroupArn = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("billingGroupId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.BillingGroupId = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("billingGroupName", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.BillingGroupName = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null))
{
if (errorResponse.Code != null && errorResponse.Code.Equals("InternalFailureException"))
{
return InternalFailureExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidRequestException"))
{
return InvalidRequestExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceAlreadyExistsException"))
{
return ResourceAlreadyExistsExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ThrottlingException"))
{
return ThrottlingExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonIoTException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static CreateBillingGroupResponseUnmarshaller _instance = new CreateBillingGroupResponseUnmarshaller();
internal static CreateBillingGroupResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static CreateBillingGroupResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 40.246269 | 186 | 0.631003 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/IoT/Generated/Model/Internal/MarshallTransformations/CreateBillingGroupResponseUnmarshaller.cs | 5,393 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Sokan.Yastah.Business.Characters;
using Sokan.Yastah.Data.Characters;
namespace Sokan.Yastah.Api.Characters
{
public class LevelsController
: CharactersControllerBase
{
#region Construction
public LevelsController(
ICharacterLevelsOperations characterLevelsOperations,
ILogger<LevelsController> logger)
: base(logger)
=> _characterLevelsOperations = characterLevelsOperations;
#endregion Construction
#region Actions
[HttpGet(DefaultAreaActionRouteTemplate)]
public ValueTask<IActionResult> Definitions()
=> PerformOperationAsync(() => _characterLevelsOperations.GetDefinitionsAsync(
cancellationToken: HttpContext.RequestAborted));
[HttpPut(DefaultAreaActionRouteTemplate)]
public Task<IActionResult> ExperienceDiffs(
[FromBody]IReadOnlyList<int> body)
=> PerformOperationAsync(() => _characterLevelsOperations.UpdateExperienceDiffsAsync(
experienceDiffs: body,
cancellationToken: HttpContext.RequestAborted));
#endregion Actions
#region State
private readonly ICharacterLevelsOperations _characterLevelsOperations;
#endregion State
}
}
| 30.4375 | 97 | 0.687201 | [
"MIT"
] | ChaseDRedmon/Sokan.Yastah | Sokan.Yastah.Api/Characters/LevelsController.cs | 1,463 | C# |
using CGF.System.Internals;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ImageConverter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
if(dlg.ShowDialog() == DialogResult.OK)
{
Bitmap bmp = (Bitmap)Image.FromFile(dlg.FileName);
RWStream str = new RWStream();
str.WriteInt32(bmp.Width);
str.WriteInt32(bmp.Height);
for (int y = 0; y < bmp.Height; y++)
{
for (int x = 0; x < bmp.Width; x++)
{
var px = bmp.GetPixel(x, y);
str.WriteInt32(((px.R << 16) | (px.G << 8) | px.B));
}
}
File.WriteAllBytes("img.cif", str._buffer.ToArray());
}
}
}
}
| 27.288889 | 76 | 0.508958 | [
"MIT"
] | Myvar/CosmosGuiFramework | CosmosGuiFramework/ImageConverter/Form1.cs | 1,230 | C# |
namespace Team8Project.IO.Contracts
{
public interface IRenderer
{
void UpdataScreen();
void InitialScreen();
void SetScreenSize();
void UpdateActiveHero();
string[] CharacterSelection();
}
} | 20.416667 | 38 | 0.612245 | [
"MIT"
] | ateber91/GameBasics | Team8Project/Team8Project/IO/Contracts/IRenderer.cs | 247 | 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.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.ComponentModel
{
public partial class ArrayConverter : System.ComponentModel.CollectionConverter
{
public ArrayConverter() { }
public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { return default(object); }
}
public abstract partial class BaseNumberConverter : System.ComponentModel.TypeConverter
{
protected BaseNumberConverter() { }
public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type sourceType) { return default(bool); }
public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type t) { return default(bool); }
public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { return default(object); }
public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { return default(object); }
}
public partial class BooleanConverter : System.ComponentModel.TypeConverter
{
public BooleanConverter() { }
public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type sourceType) { return default(bool); }
public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { return default(object); }
}
public partial class ByteConverter : System.ComponentModel.BaseNumberConverter
{
public ByteConverter() { }
}
public partial class CharConverter : System.ComponentModel.TypeConverter
{
public CharConverter() { }
public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type sourceType) { return default(bool); }
public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { return default(object); }
public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { return default(object); }
}
public partial class CollectionConverter : System.ComponentModel.TypeConverter
{
public CollectionConverter() { }
public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { return default(object); }
}
public partial class DateTimeConverter : System.ComponentModel.TypeConverter
{
public DateTimeConverter() { }
public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type sourceType) { return default(bool); }
public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { return default(bool); }
public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { return default(object); }
public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { return default(object); }
}
public partial class DateTimeOffsetConverter : System.ComponentModel.TypeConverter
{
public DateTimeOffsetConverter() { }
public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type sourceType) { return default(bool); }
public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { return default(bool); }
public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { return default(object); }
public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { return default(object); }
}
public partial class DecimalConverter : System.ComponentModel.BaseNumberConverter
{
public DecimalConverter() { }
public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { return default(bool); }
public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { return default(object); }
}
public partial class DoubleConverter : System.ComponentModel.BaseNumberConverter
{
public DoubleConverter() { }
}
public partial class EnumConverter : System.ComponentModel.TypeConverter
{
public EnumConverter(System.Type type) { }
protected System.Type EnumType { get { return default(System.Type); } }
public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type sourceType) { return default(bool); }
public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { return default(bool); }
public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { return default(object); }
public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { return default(object); }
}
public partial class GuidConverter : System.ComponentModel.TypeConverter
{
public GuidConverter() { }
public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type sourceType) { return default(bool); }
public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { return default(bool); }
public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { return default(object); }
public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { return default(object); }
}
public partial class Int16Converter : System.ComponentModel.BaseNumberConverter
{
public Int16Converter() { }
}
public partial class Int32Converter : System.ComponentModel.BaseNumberConverter
{
public Int32Converter() { }
}
public partial class Int64Converter : System.ComponentModel.BaseNumberConverter
{
public Int64Converter() { }
}
public partial interface ITypeDescriptorContext : System.IServiceProvider
{
System.ComponentModel.IContainer Container { get; }
object Instance { get; }
System.ComponentModel.PropertyDescriptor PropertyDescriptor { get; }
void OnComponentChanged();
bool OnComponentChanging();
}
public partial class MultilineStringConverter : System.ComponentModel.TypeConverter
{
public MultilineStringConverter() { }
public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { return default(object); }
}
public partial class NullableConverter : System.ComponentModel.TypeConverter
{
public NullableConverter(System.Type type) { }
public System.Type NullableType { get { return default(System.Type); } }
public System.Type UnderlyingType { get { return default(System.Type); } }
public System.ComponentModel.TypeConverter UnderlyingTypeConverter { get { return default(System.ComponentModel.TypeConverter); } }
public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type sourceType) { return default(bool); }
public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { return default(bool); }
public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { return default(object); }
public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { return default(object); }
}
public abstract partial class PropertyDescriptor
{
internal PropertyDescriptor() { }
}
public partial class SByteConverter : System.ComponentModel.BaseNumberConverter
{
public SByteConverter() { }
}
public partial class SingleConverter : System.ComponentModel.BaseNumberConverter
{
public SingleConverter() { }
}
public partial class StringConverter : System.ComponentModel.TypeConverter
{
public StringConverter() { }
public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type sourceType) { return default(bool); }
public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { return default(object); }
}
public partial class TimeSpanConverter : System.ComponentModel.TypeConverter
{
public TimeSpanConverter() { }
public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type sourceType) { return default(bool); }
public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { return default(bool); }
public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { return default(object); }
public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { return default(object); }
}
public partial class TypeConverter
{
public TypeConverter() { }
public virtual bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type sourceType) { return default(bool); }
public bool CanConvertFrom(System.Type sourceType) { return default(bool); }
public virtual bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { return default(bool); }
public bool CanConvertTo(System.Type destinationType) { return default(bool); }
public virtual object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { return default(object); }
public object ConvertFrom(object value) { return default(object); }
public object ConvertFromInvariantString(string text) { return default(object); }
public object ConvertFromString(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, string text) { return default(object); }
public object ConvertFromString(string text) { return default(object); }
public virtual object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { return default(object); }
public object ConvertTo(object value, System.Type destinationType) { return default(object); }
public string ConvertToInvariantString(object value) { return default(string); }
public string ConvertToString(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { return default(string); }
public string ConvertToString(object value) { return default(string); }
protected System.Exception GetConvertFromException(object value) { return default(System.Exception); }
protected System.Exception GetConvertToException(object value, System.Type destinationType) { return default(System.Exception); }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(32767))]
public sealed partial class TypeConverterAttribute : System.Attribute
{
public TypeConverterAttribute(string typeName) { }
public TypeConverterAttribute(System.Type type) { }
public string ConverterTypeName { get { return default(string); } }
public override bool Equals(object obj) { return default(bool); }
public override int GetHashCode() { return default(int); }
}
public sealed partial class TypeDescriptor
{
internal TypeDescriptor() { }
public static System.ComponentModel.TypeConverter GetConverter(System.Type type) { return default(System.ComponentModel.TypeConverter); }
}
public abstract partial class TypeListConverter : System.ComponentModel.TypeConverter
{
protected TypeListConverter(System.Type[] types) { }
public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type sourceType) { return default(bool); }
public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { return default(bool); }
public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { return default(object); }
public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { return default(object); }
}
public partial class UInt16Converter : System.ComponentModel.BaseNumberConverter
{
public UInt16Converter() { }
}
public partial class UInt32Converter : System.ComponentModel.BaseNumberConverter
{
public UInt32Converter() { }
}
public partial class UInt64Converter : System.ComponentModel.BaseNumberConverter
{
public UInt64Converter() { }
}
}
| 73.592233 | 207 | 0.757124 | [
"MIT"
] | benjamin-bader/corefx | src/System.ComponentModel.TypeConverter/ref/System.ComponentModel.TypeConverter.cs | 15,160 | C# |
using System.Threading;
namespace Parenthless.EntityFrameworkCore.Clauses {
public class ToDictionaryAsyncClause {
public CancellationToken CancellationToken { get; }
public ToDictionaryAsyncClause(CancellationToken cancellationToken) {
CancellationToken = cancellationToken;
}
}
}
| 24.666667 | 71 | 0.810811 | [
"MIT"
] | ronnygunawan/parenthless-linq | Parenthless.EntityFrameworkCore/Clauses/ToDictionaryAsyncClause.cs | 298 | C# |
using System;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using ACT.SpecialSpellTimer.resources;
using FFXIV.Framework.Dialog;
using FFXIV.Framework.FFXIVHelper;
using FFXIV.Framework.Globalization;
using Prism.Commands;
namespace ACT.SpecialSpellTimer.Config.Views
{
/// <summary>
/// OptionsVisualView.xaml の相互作用ロジック
/// </summary>
public partial class OptionsVisualView :
UserControl,
ILocalizable
{
public OptionsVisualView()
{
this.InitializeComponent();
this.SetLocale(Settings.Default.UILocale);
this.LoadConfigViewResources();
this.nameStyleRadioButtons = new[]
{
this.NameStyle1RadioButton,
this.NameStyle2RadioButton,
this.NameStyle3RadioButton,
this.NameStyle4RadioButton,
};
this.Loaded += (x, y) =>
{
var target = this.nameStyleRadioButtons.FirstOrDefault(z =>
Convert.ToInt32(z.Tag) == (int)this.Config.PCNameInitialOnDisplayStyle);
if (target != null)
{
target.IsChecked = true;
}
};
void setNameStyle()
{
var source = this.nameStyleRadioButtons.FirstOrDefault(z => z.IsChecked ?? false);
if (source != null)
{
this.Config.PCNameInitialOnDisplayStyle = (NameStyles)Convert.ToInt32(source.Tag);
}
}
foreach (var button in this.nameStyleRadioButtons)
{
button.Checked += (x, y) => setNameStyle();
}
}
public void SetLocale(Locales locale) => this.ReloadLocaleDictionary(locale);
public Settings Config => Settings.Default;
private RadioButton[] nameStyleRadioButtons;
private ICommand CreateChangeColorCommand(
Func<Color> getCurrentColor,
Action<Color> changeColorAction)
=> new DelegateCommand(() =>
{
var result = ColorDialogWrapper.ShowDialog(getCurrentColor(), true);
if (result.Result)
{
changeColorAction.Invoke(result.Color);
}
});
private ICommand changeProgressBarBackgroundColorCommand;
public ICommand ChangeProgressBarBackgroundColorCommand =>
this.changeProgressBarBackgroundColorCommand ?? (this.changeProgressBarBackgroundColorCommand = this.CreateChangeColorCommand(
() => this.Config.BarDefaultBackgroundColor,
(color) => this.Config.BarDefaultBackgroundColor = color));
}
}
| 32.872093 | 138 | 0.583658 | [
"BSD-3-Clause"
] | Airex/ACT.SpecialSpellTimer | ACT.SpecialSpellTimer.Core/Config/Views/OptionsVisualView.xaml.cs | 2,845 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace LiteDB.Tests
{
[TestClass]
public class BulkInsertTest
{
[TestMethod]
public void BulkInsert_Test()
{
using (var file = new TempFile())
using (var db = new LiteEngine(file.Filename))
{
// let's bulk 500.000 documents
db.InsertBulk("col", GetDocs(1, 500000));
// and assert if all are inserted (based on collection header only)
Assert.AreEqual(500000, db.Count("col"));
// and now count all
Assert.AreEqual(500000, db.Count("col", Query.All()));
}
}
private IEnumerable<BsonDocument> GetDocs(int initial, int count, int type = 1)
{
for (var i = initial; i < initial + count; i++)
{
yield return new BsonDocument
{
{ "_id", i },
{ "name", Guid.NewGuid().ToString() },
{ "first", "John" },
{ "lorem", TempFile.LoremIpsum(3, 5, 2, 3, 3) }
};
}
}
}
} | 29.391304 | 87 | 0.510355 | [
"MIT"
] | RytisLT/LiteDB | LiteDB.Tests/Engine/BulkInsertTest.cs | 1,354 | C# |
using SafeObjectPool;
using System;
using System.Data;
using System.Data.Common;
using System.Threading;
namespace FreeSql
{
public class UnitOfWork : IUnitOfWork
{
#if ns20
public static readonly AsyncLocal<IUnitOfWork> Current = new AsyncLocal<IUnitOfWork>();
#endif
protected IFreeSql _fsql;
protected Object<DbConnection> _conn;
protected DbTransaction _tran;
public UnitOfWork(IFreeSql fsql)
{
_fsql = fsql;
#if ns20
Current.Value = this;
#endif
}
void ReturnObject()
{
_fsql.Ado.MasterPool.Return(_conn);
_tran = null;
_conn = null;
#if ns20
Current.Value = null;
#endif
}
public bool Enable { get; private set; } = true;
public void Close()
{
if (_tran != null)
throw new Exception("已开启事务,不能禁用工作单元");
Enable = false;
}
public void Open()
{
Enable = true;
}
public IsolationLevel? IsolationLevel { get; set; }
public DbTransaction GetOrBeginTransaction(bool isCreate = true)
{
if (_tran != null) return _tran;
if (isCreate == false) return null;
if (!Enable) return null;
if (_conn != null) _fsql.Ado.MasterPool.Return(_conn);
_conn = _fsql.Ado.MasterPool.Get();
try
{
_tran = IsolationLevel == null ?
_conn.Value.BeginTransaction() :
_conn.Value.BeginTransaction(IsolationLevel.Value);
}
catch
{
ReturnObject();
throw;
}
return _tran;
}
public void Commit()
{
try
{
if (_tran != null) _tran.Commit();
}
finally
{
ReturnObject();
}
}
public void Rollback()
{
try
{
if (_tran != null) _tran.Rollback();
}
finally
{
ReturnObject();
}
}
~UnitOfWork()
{
this.Dispose();
}
bool _isdisposed = false;
public void Dispose()
{
if (_isdisposed) return;
_isdisposed = true;
this.Rollback();
this.Close();
GC.SuppressFinalize(this);
}
}
}
| 22.901786 | 95 | 0.464717 | [
"MIT"
] | Coldairarrow/FreeSql | FreeSql.DbContext/UnitOfWork/UnitOfWork.cs | 2,595 | C# |
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using Lxna.Gui.Mobile.Models;
using Lxna.Gui.Mobile.ViewModels;
namespace Lxna.Gui.Mobile.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ItemDetailPage : ContentPage
{
ItemDetailViewModel viewModel;
public ItemDetailPage(ItemDetailViewModel viewModel)
{
InitializeComponent();
BindingContext = this.viewModel = viewModel;
}
public ItemDetailPage()
{
InitializeComponent();
var item = new Item
{
Text = "Item 1",
Description = "This is an item description."
};
viewModel = new ItemDetailViewModel(item);
BindingContext = viewModel;
}
}
} | 23.621622 | 61 | 0.572082 | [
"MIT"
] | gitter-badger/lxna | src/Lxna.Gui.Mobile/Views/ItemDetailPage.xaml.cs | 876 | C# |
namespace DxMessaging.Core
{
using MessageBus;
using System;
using System.Collections.Generic;
using System.Linq;
using Messages;
using UnityEngine;
/// <summary>
/// Abstraction layer for immediate-mode Message passing. An instance of this handles all
/// kinds of types to trigger functions that are registered with it.
/// </summary>
[Serializable]
public sealed class MessageHandler
{
/// <summary>
/// MessageBus for all MessageHandlers to use. Currently immutable, but may change in the future.
/// </summary>
public static readonly IMessageBus MessageBus = new MessageBus.MessageBus();
/// <summary>
/// Maps Types to the corresponding Handler of that type.
/// </summary>
/// <note>
/// Ideally, this would be something like a Dictionary[T,Handler[T]], but that can't be done with C#s type system.
/// </note>
private readonly Dictionary<IMessageBus, Dictionary<Type, IHandler>> _handlersByTypeByMessageBus;
/// <summary>
/// Whether or not this MessageHandler will process messages.
/// </summary>
public bool active;
/// <summary>
/// The Id of the GameObject that owns us.
/// </summary>
public readonly InstanceId owner;
public MessageHandler(InstanceId owner)
{
this.owner = owner;
_handlersByTypeByMessageBus = new Dictionary<IMessageBus, Dictionary<Type, IHandler>>();
}
/// <summary>
/// Callback from the MessageBus for handling UntargetedMessages - user code should generally never use this.
/// </summary>
/// <note>
/// In this case, "UntargetedMessage" refers to Targeted without targeting, and UntargetedMessages, hence T : AbstractMessage.
/// </note>
/// <param name="message">Message to handle.</param>
/// <param name="messageBus">The specific MessageBus to use.</param>
public void HandleUntargetedMessage(IMessage message, IMessageBus messageBus)
{
ActuallyHandleMessage(message.GetType(), typedHandler => typedHandler.HandleUntargeted(message), messageBus);
}
/// <summary>
/// Callback from the MessageBus for handling TargetedMessages when this MessageHandler has subscribed - user code should generally never use this.
/// </summary>
/// <note>
/// TargetedMessage refers to those that are intended for the GameObject that owns this MessageHandler.
/// </note>
/// <param name="message">Message to handle.</param>
/// <param name="messageBus">The specific MessageBus to use.</param>
public void HandleTargetedMessage(ITargetedMessage message, IMessageBus messageBus)
{
ActuallyHandleMessage(message.GetType(), typedHandler => typedHandler.HandleTargeted(message), messageBus);
}
/// <summary>
/// Callback from the MessageBus for handling SourcedBroadcastMessages - user code should generally never use this.
/// </summary>
/// <note>
/// SourcedBroadcastMessages generally refer to those that are sourced from the GameObject that owns this MessageHandler.
/// </note>
/// <param name="message">Message to handle</param>
/// <param name="messageBus">The specific MessageBus to use.</param>
public void HandleSourcedBroadcast(IBroadcastMessage message, IMessageBus messageBus)
{
ActuallyHandleMessage(message.GetType(), typedHandler => typedHandler.HandleSourcedBroadcast(message), messageBus);
}
/// <summary>
/// Callback from the MessageBus for handling Messages when this MessageHandler has subscribed to GlobalAcceptAll - user code should generally never use this.
/// </summary>
/// <param name="message">Message to handle.</param>
/// <param name="messageBus">The specific MessageBus to use.</param>
public void HandleGlobalUntargetedMessage(IUntargetedMessage message, IMessageBus messageBus)
{
// Use the "IMessage" explicitly to indicate global messages, allowing us to multi-purpose a single dictionary
ActuallyHandleMessage(typeof(IMessage), typedHandler => typedHandler.HandleGlobalUntargeted(message), messageBus);
}
/// <summary>
/// Callback from the MessageBus for handling Messages when this MessageHandler has subscribed to GlobalAcceptAll - user code should generally never use this.
/// </summary>
/// <param name="target">Target of the message.</param>
/// <param name="message">Message to handle.</param>
/// <param name="messageBus">The specific MessageBus to use.</param>
public void HandleGlobalTargetedMessage(InstanceId target, ITargetedMessage message, IMessageBus messageBus)
{
// Use the "IMessage" explicitly to indicate global messages, allowing us to multi-purpose a single dictionary
ActuallyHandleMessage(typeof(IMessage), typedHandler => typedHandler.HandleGlobalTargeted(target, message), messageBus);
}
/// <summary>
/// Callback from the MessageBus for handling Messages when this MessageHandler has subscribed to GlobalAcceptAll - user code should generally never use this.
/// </summary>
/// <param name="source">Source that this message is from.</param>
/// <param name="message">Message to handle.</param>
/// <param name="messageBus">The specific MessageBus to use.</param>
public void HandleGlobalSourcedBroadcastMessage(InstanceId source, IBroadcastMessage message, IMessageBus messageBus)
{
// Use the "IMessage" explicitly to indicate global messages, allowing us to multi-purpose a single dictionary
ActuallyHandleMessage(typeof(IMessage), typedHandler => typedHandler.HandleGlobalBroadcast(source, message), messageBus);
}
/// <summary>
/// Actual MessageHandler implementation.
/// </summary>
/// <typeparam name="T">Type of Message to handle.</typeparam>
/// <param name="handle">Handler function.</param>
/// <param name="messageBus">The specific MessageBus to use.</param>
private void ActuallyHandleMessage(Type type, Action<IHandler> handle, IMessageBus messageBus)
{
if (!active)
{
return;
}
IHandler handlerForType = GetHandlerForType(type, messageBus);
if (!ReferenceEquals(handlerForType, null))
{
handle(handlerForType);
}
}
/// <summary>
/// Registers this MessageHandler to Globally Accept All Messages via the MessageBus, properly handling de-registration.
/// </summary>
/// <param name="untargetedMessageHandler">MessageHandler to accept all UntargetedMessages.</param>
/// <param name="broadcastMessageHandler">MessageHandler to accept all TargetedMessages for all entities.</param>
/// <param name="targetedMessageHandler">MessageHandler to accept all BroadcastMessages for all entities.</param>
/// <param name="messageBus">IMessageBus override to register with, if any. Null/not provided defaults to the GlobalMessageBus.</param>
/// <returns>The de-registration action.</returns>
public Action RegisterGlobalAcceptAll(Action<IUntargetedMessage> untargetedMessageHandler, Action<InstanceId, ITargetedMessage> targetedMessageHandler, Action<InstanceId, IBroadcastMessage> broadcastMessageHandler, IMessageBus messageBus = null)
{
messageBus = messageBus ?? MessageBus;
Action messageBusDeregistration = messageBus.RegisterGlobalAcceptAll(this);
TypedHandler<IMessage> typedHandler = GetOrCreateHandlerForType<IMessage>(messageBus);
Action untargetedDeregistration = typedHandler.AddGlobalUntargetedHandler(untargetedMessageHandler, messageBusDeregistration);
Action targetedDeregistration = typedHandler.AddGlobalTargetedHandler(targetedMessageHandler, messageBusDeregistration);
Action broadcastDeregistration = typedHandler.AddGlobalBroadcastHandler(broadcastMessageHandler, messageBusDeregistration);
return () =>
{
untargetedDeregistration();
targetedDeregistration();
broadcastDeregistration();
};
}
/// <summary>
/// Registers this MessageHandler to accept TargetedMessages via the MessageBus, properly handling de-registration.
/// </summary>
/// <typeparam name="T">Type of Message to be handled.</typeparam>
/// <param name="messageHandler">Function that actually handles the message.</param>
/// <param name="messageBus">IMessageBus override to register with, if any. Null/not provided defaults to the GlobalMessageBus.</param>
/// <returns>The de-registration action.</returns>
public Action RegisterTargetedMessageHandler<T>(Action<T> messageHandler, IMessageBus messageBus = null) where T : ITargetedMessage
{
messageBus = messageBus ?? MessageBus;
Action messageBusDeregistration = messageBus.RegisterTargeted<T>(this);
TypedHandler<T> typedHandler = GetOrCreateHandlerForType<T>(messageBus);
return typedHandler.AddTargetedHandler(messageHandler, messageBusDeregistration);
}
public Action RegisterTargetedMessageHandler<T>(InstanceId target, Action<T> messageHandler, IMessageBus messageBus = null) where T : ITargetedMessage
{
messageBus = messageBus ?? MessageBus;
Action messageBusDeregistration = messageBus.RegisterTargeted<T>(target, this);
TypedHandler<T> typedHandler = GetOrCreateHandlerForType<T>(messageBus);
return typedHandler.AddTargetedHandler(messageHandler, messageBusDeregistration);
}
/// <summary>
/// Registers this MessageHandler to accept TargetedMessages without Targeting via the MessageBus, properly handling de-registration.
/// </summary>
/// <typeparam name="T">Type of Message to be handled.</typeparam>
/// <param name="messageHandler">Function that actually handles the message.</param>
/// <param name="messageBus">IMessageBus override to register with, if any. Null/not provided defaults to the GlobalMessageBus.</param>
/// <returns>The de-registration action.</returns>
public Action RegisterTargetedWithoutTargeting<T>(Action<T> messageHandler, IMessageBus messageBus = null) where T : ITargetedMessage
{
messageBus = messageBus ?? MessageBus;
Action messageBusDeregistration = messageBus.RegisterTargetedWithoutTargeting<T>(this);
TypedHandler<T> typedHandler = GetOrCreateHandlerForType<T>(messageBus);
return typedHandler.AddUntargetedHandler(messageHandler, messageBusDeregistration);
}
/// <summary>
/// Registers this MessageHandler to accept UntargetedMessages via the MessageBus, properly handling de-registration.
/// </summary>
/// <typeparam name="T">Type of Message to be handled.</typeparam>
/// <param name="messageHandler">Function that actually handles the message.</param>
/// <param name="messageBus">IMessageBus override to register with, if any. Null/not provided defaults to the GlobalMessageBus.</param>
/// <returns>The de-registration action.</returns>
public Action RegisterUntargetedMessageHandler<T>(Action<T> messageHandler, IMessageBus messageBus = null) where T : IUntargetedMessage
{
messageBus = messageBus ?? MessageBus;
Action messageBusDeregistration = messageBus.RegisterUntargeted<T>(this);
TypedHandler<T> typedHandler = GetOrCreateHandlerForType<T>(messageBus);
return typedHandler.AddUntargetedHandler(messageHandler, messageBusDeregistration);
}
/// <summary>
/// Registers this MessageHandler to accept BroadcastMessages via their MessageBus, properly handling de-registration.
/// </summary>
/// <typeparam name="T">Type of Message to be handled.</typeparam>
/// <param name="source">Source Id of BroadcastMessages to listen for.</param>
/// <param name="messageHandler">Function that actually handles the message.</param>
/// <param name="messageBus">IMessageBus override to register with, if any. Null/not provided defaults to the GlobalMessageBus.</param>
/// <returns>The de-registration action.</returns>
public Action RegisterSourcedBroadcastMessageHandler<T>(InstanceId source, Action<T> messageHandler, IMessageBus messageBus = null)
where T : IBroadcastMessage
{
messageBus = messageBus ?? MessageBus;
Action messageBusDeregistration = messageBus.RegisterSourcedBroadcast<T>(source, this);
TypedHandler<T> typedHandler = GetOrCreateHandlerForType<T>(messageBus);;
return typedHandler.AddSourcedBroadcastHandler(messageHandler, messageBusDeregistration);
}
/// <summary>
/// Registers this MessageHandler to accept BroadcastMessage regardless of source via their Messagebus, properly handling de-registration.
/// </summary>
/// <typeparam name="T">Type of Message to be handled.</typeparam>
/// <param name="messageHandler">Function that actually handles the message.</param>
/// <param name="messageBus">IMessageBus override to register with, if any. Null/not provided defaults to the GlobalMessageBus.</param>
/// <returns>The de-registration action.</returns>
public Action RegisterSourcedBroadcastWithoutSource<T>(Action<T> messageHandler, IMessageBus messageBus = null) where T : IBroadcastMessage
{
messageBus = messageBus ?? MessageBus;
Action messageBusDeregistration = messageBus.RegisterSourcedBroadcastWithoutSource<T>(this);
TypedHandler<T> typedHandler = GetOrCreateHandlerForType<T>(messageBus);
return typedHandler.AddUntargetedHandler(messageHandler, messageBusDeregistration);
}
/// <summary>
/// Registers this MessageHandler to intercept messages of the provided type for the provided MessageBus, properly handling de-registration
/// </summary>
/// <typeparam name="T">Type of Message to be handled.</typeparam>
/// <param name="transformer">Interceptor function.</param>
/// <param name="messageBus">IMessageBus override to register with, if any. Null/not provided defaults to the GlobalMessageBus.</param>
/// <returns>The de-registration action.</returns>
public Action RegisterIntercept<T>(Func<T, T> transformer, IMessageBus messageBus = null) where T : IMessage
{
return (messageBus ?? MessageBus).RegisterIntercept(transformer);
}
public override string ToString()
{
return new
{
OwnerId = owner,
HandlerTypes = string.Join(",",
_handlersByTypeByMessageBus.Values.SelectMany(key => key.Keys).Select(type => type.Name)
.OrderBy(_ => _))
}.ToString();
}
/// <summary>
/// Retrieves an existing Handler for the specific type, if it exists, or creates a new Handler, if none exist.
/// </summary>
/// <typeparam name="T">Type of Message to retrieve a Handler for.</typeparam>
/// <returns>Non-Null Handler for the specific type.</returns>
private TypedHandler<T> GetOrCreateHandlerForType<T>(IMessageBus messageBus) where T : IMessage
{
Type type = typeof(T);
if (!_handlersByTypeByMessageBus.TryGetValue(messageBus, out Dictionary<Type, IHandler> handlersByType))
{
handlersByType = new Dictionary<Type, IHandler>();
_handlersByTypeByMessageBus[messageBus] = handlersByType;
}
if (handlersByType.TryGetValue(type, out IHandler existingTypedHandler))
{
return (TypedHandler<T>) existingTypedHandler;
}
TypedHandler<T> newTypedHandler = new TypedHandler<T>();
handlersByType.Add(type, newTypedHandler);
return newTypedHandler;
}
/// <summary>
/// Gets an existing Handler for the specific type, if it exists.
/// </summary>
/// <param name="type">Message type to get the handler for.</param>
/// <param name="messageBus">The specific MessageBus to use.</param>
/// <returns>Existing handler for the specific type, or null if none exists..</returns>
private IHandler GetHandlerForType(Type type, IMessageBus messageBus)
{
if (_handlersByTypeByMessageBus.TryGetValue(messageBus, out Dictionary<Type, IHandler> handlersByType) && handlersByType.TryGetValue(type, out IHandler existingTypedHandler))
{
return existingTypedHandler;
}
return null;
}
/// <summary>
/// Needed for actually emitting messages
/// </summary>
private interface IHandler
{
void HandleUntargeted(IMessage message);
void HandleTargeted(ITargetedMessage message);
void HandleSourcedBroadcast(IBroadcastMessage message);
void HandleGlobalUntargeted(IUntargetedMessage message);
void HandleGlobalTargeted(InstanceId target, ITargetedMessage message);
void HandleGlobalBroadcast(InstanceId source, IBroadcastMessage message);
}
/// <summary>
/// One-size-fits-all wrapper around all possible Messaging sinks for a particular MessageHandler & MessageType.
/// </summary>
/// <typeparam name="T">Message type that this Handler exists to serve.</typeparam>
[Serializable]
private sealed class TypedHandler<T> : IHandler where T: IMessage
{
private readonly HashSet<Action<T>> _targetedHandlers;
private readonly HashSet<Action<T>> _untargetedHandlers;
private readonly HashSet<Action<T>> _broadcastHandlers;
private readonly HashSet<Action<IUntargetedMessage>> _globalUntargetedHandlers;
private readonly HashSet<Action<InstanceId, ITargetedMessage>> _globalTargetedHandlers;
private readonly HashSet<Action<InstanceId, IBroadcastMessage>> _globalBroadcastHandlers;
// Buffers so we don't allocate memory as often
private readonly Stack<List<Action<T>>> _handlersStack;
private readonly Stack<List<Action<IUntargetedMessage>>> _globalUntargetedHandlersStack;
private readonly Stack<List<Action<InstanceId, ITargetedMessage>>> _globalTargetedHandlersStack;
private readonly Stack<List<Action<InstanceId, IBroadcastMessage>>> _globalBroadcastHandlersStack;
public TypedHandler()
{
_targetedHandlers = new HashSet<Action<T>>();
_untargetedHandlers = new HashSet<Action<T>>();
_broadcastHandlers = new HashSet<Action<T>>();
_globalUntargetedHandlers = new HashSet<Action<IUntargetedMessage>>();
_globalTargetedHandlers = new HashSet<Action<InstanceId, ITargetedMessage>>();
_globalBroadcastHandlers = new HashSet<Action<InstanceId, IBroadcastMessage>>();
_handlersStack = new Stack<List<Action<T>>>();
_globalUntargetedHandlersStack = new Stack<List<Action<IUntargetedMessage>>>();
_globalTargetedHandlersStack = new Stack<List<Action<InstanceId, ITargetedMessage>>>();
_globalBroadcastHandlersStack = new Stack<List<Action<InstanceId, IBroadcastMessage>>>();
}
/// <summary>
/// Emits the UntargetedMessage to all subscribed listeners.
/// </summary>
/// <param name="message">Message to emit.</param>
public void HandleUntargeted(IMessage message)
{
List<Action<T>> handlers = GetOrAddNewHandlerStack(_untargetedHandlers);
try
{
foreach (Action<T> handler in handlers)
{
handler((T) message);
}
}
finally
{
_handlersStack.Push(handlers);
}
}
/// <summary>
/// Emits the TargetedMessage to all subscribed listeners.
/// </summary>
/// <param name="message">Message to emit.</param>
public void HandleTargeted(ITargetedMessage message)
{
List<Action<T>> handlers = GetOrAddNewHandlerStack(_targetedHandlers);
try
{
foreach (Action<T> handler in handlers)
{
handler((T) message);
}
}
finally
{
_handlersStack.Push(handlers);
}
}
/// <summary>
/// Emits the BroadcastMessage to all subscribed listeners.
/// </summary>
/// <param name="message">Message to emit.</param>
public void HandleSourcedBroadcast(IBroadcastMessage message)
{
List<Action<T>> handlers = GetOrAddNewHandlerStack(_broadcastHandlers);
try
{
foreach (Action<T> handler in handlers)
{
handler((T) message);
}
}
finally
{
_handlersStack.Push(handlers);
}
}
/// <summary>
/// Emits the UntargetedMessage to all global listeners.
/// </summary>
/// <param name="message">Message to emit.</param>
public void HandleGlobalUntargeted(IUntargetedMessage message)
{
if (_globalUntargetedHandlersStack.TryPop(out List<Action<IUntargetedMessage>> handlers))
{
handlers.Clear();
handlers.AddRange(_globalUntargetedHandlers);
}
else
{
handlers = new List<Action<IUntargetedMessage>>(_globalUntargetedHandlers);
}
try
{
foreach (Action<IUntargetedMessage> handler in handlers)
{
handler(message);
}
}
finally
{
_globalUntargetedHandlersStack.Push(handlers);
}
}
/// <summary>
/// Emits the TargetedMessage to all global listeners.
/// </summary>
/// <param name="target">Target that this message is intended for.</param>
/// <param name="message">Message to emit.</param>
public void HandleGlobalTargeted(InstanceId target, ITargetedMessage message)
{
if (_globalTargetedHandlersStack.TryPop(out List<Action<InstanceId, ITargetedMessage>> handlers))
{
handlers.Clear();
handlers.AddRange(_globalTargetedHandlers);
}
else
{
handlers = new List<Action<InstanceId, ITargetedMessage>>(_globalTargetedHandlers);
}
try
{
foreach (Action<InstanceId, ITargetedMessage> handler in handlers)
{
handler(target, message);
}
}
finally
{
_globalTargetedHandlersStack.Push(handlers);
}
}
/// <summary>
/// Emits the BroadcastMessage to all global listeners.
/// </summary>
/// <param name="source">Source that this message is from.</param>
/// <param name="message">Message to emit.</param>
public void HandleGlobalBroadcast(InstanceId source, IBroadcastMessage message)
{
if (_globalBroadcastHandlersStack.TryPop(out List<Action<InstanceId, IBroadcastMessage>> handlers))
{
handlers.Clear();
handlers.AddRange(_globalBroadcastHandlers);
}
else
{
handlers = new List<Action<InstanceId, IBroadcastMessage>>(_globalBroadcastHandlers);
}
try
{
foreach (Action<InstanceId, IBroadcastMessage> handler in handlers)
{
handler(source, message);
}
}
finally
{
_globalBroadcastHandlersStack.Push(handlers);
}
}
/// <summary>
/// Adds a TargetedHandler to listen to Messages of the given type, returning a de-registration action.
/// </summary>
/// <param name="handler">Relevant MessageHandler.</param>
/// <param name="deregistration">Deregistration action for the handler.</param>
/// <returns>De-registration action to un-register the handler.</returns>
public Action AddTargetedHandler(Action<T> handler, Action deregistration)
{
bool added = _targetedHandlers.Add(handler);
return () =>
{
if (!added)
{
return;
}
_ = _targetedHandlers.Remove(handler);
deregistration?.Invoke();
};
}
/// <summary>
/// Adds a UntargetedHandler to listen to Messages of the given type, returning a de-registration action.
/// </summary>
/// <param name="handler">Relevant MessageHandler.</param>
/// <param name="deregistration">Deregistration action for the handler.</param>
/// <returns>De-registration action to un-register the handler.</returns>
public Action AddUntargetedHandler(Action<T> handler, Action deregistration)
{
bool added = _untargetedHandlers.Add(handler);
return () =>
{
if (!added)
{
return;
}
_ = _untargetedHandlers.Remove(handler);
deregistration?.Invoke();
};
}
/// <summary>
/// Adds a SourcedBroadcastHandler to listen to Messages of the given type from an entity, returning a de-registration action.
/// </summary>
/// <param name="handler">Relevant MessageHandler.</param>
/// <param name="deregistration">Deregistration action for the handler.</param>
/// <returns>De-registration action to un-register the handler.</returns>
public Action AddSourcedBroadcastHandler(Action<T> handler, Action deregistration)
{
bool added = _broadcastHandlers.Add(handler);
return () =>
{
if (!added)
{
return;
}
_ = _broadcastHandlers.Remove(handler);
deregistration?.Invoke();
};
}
/// <summary>
/// Adds a Global UntargetedHandler to listen to all Untargeted Messages of all types, returning the de-registration action.
/// </summary>
/// <param name="handler">Relevant MessageHandler.</param>
/// <param name="deregistration">Deregistration action for the handler.</param>
/// <returns>De-registration action to un-register the handler.</returns>
public Action AddGlobalUntargetedHandler(Action<IUntargetedMessage> handler, Action deregistration)
{
bool added = _globalUntargetedHandlers.Add(handler);
return () =>
{
if (!added)
{
return;
}
_ = _globalUntargetedHandlers.Remove(handler);
deregistration?.Invoke();
};
}
/// <summary>
/// Adds a Global TargetedHandler to listen to all Targeted Messages of all types for all entities, returning the de-registration action.
/// </summary>
/// <param name="handler">Relevant MessageHandler.</param>
/// <param name="deregistration">Deregistration action for the handler.</param>
/// <returns>De-registration action to un-register the handler.</returns>
public Action AddGlobalTargetedHandler(Action<InstanceId, ITargetedMessage> handler, Action deregistration)
{
bool added = _globalTargetedHandlers.Add(handler);
return () =>
{
if (!added)
{
return;
}
_ = _globalTargetedHandlers.Remove(handler);
deregistration?.Invoke();
};
}
/// <summary>
/// Adds a Global BroadcastHandler to listen to all Targeted Messages of all types for all entities, returning the de-registration action.
/// </summary>
/// <param name="handler">Relevant MessageHandler.</param>
/// <param name="deregistration">Deregistration action for the handler.</param>
/// <returns>De-registration action to un-register the handler.</returns>
public Action AddGlobalBroadcastHandler(Action<InstanceId, IBroadcastMessage> handler, Action deregistration)
{
bool added = _globalBroadcastHandlers.Add(handler);
return () =>
{
if (!added)
{
return;
}
_ = _globalBroadcastHandlers.Remove(handler);
deregistration?.Invoke();
};
}
private List<Action<T>> GetOrAddNewHandlerStack(IEnumerable<Action<T>> handlers)
{
if (_handlersStack.TryPop(out List<Action<T>> handlerStack))
{
handlerStack.Clear();
handlerStack.AddRange(handlers);
return handlerStack;
}
return new List<Action<T>>(handlers);
}
}
}
}
| 48.640986 | 253 | 0.599278 | [
"MIT"
] | wallstop/DxMessaging | Core/MessageHandler.cs | 31,570 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
using System;
using System.Diagnostics;
using System.Threading;
namespace FASTER.core
{
/// <summary>
/// Scan iterator for hybrid log
/// </summary>
public sealed class BlittableScanIterator<Key, Value> : IFasterScanIterator<Key, Value>
{
private readonly int frameSize;
private readonly BlittableAllocator<Key, Value> hlog;
private readonly long endAddress;
private readonly BlittableFrame frame;
private readonly CountdownEvent[] loaded;
private readonly LightEpoch epoch;
private bool first = true;
private long currentAddress, nextAddress;
private Key currentKey;
private Value currentValue;
private long currentPhysicalAddress;
/// <summary>
/// Current address
/// </summary>
public long CurrentAddress => currentAddress;
/// <summary>
/// Next address
/// </summary>
public long NextAddress => nextAddress;
/// <summary>
/// Constructor
/// </summary>
/// <param name="hlog"></param>
/// <param name="beginAddress"></param>
/// <param name="endAddress"></param>
/// <param name="scanBufferingMode"></param>
/// <param name="epoch"></param>
public unsafe BlittableScanIterator(BlittableAllocator<Key, Value> hlog, long beginAddress, long endAddress, ScanBufferingMode scanBufferingMode, LightEpoch epoch)
{
this.hlog = hlog;
// If we are protected when creating the iterator, we do not need per-GetNext protection
if (!epoch.ThisInstanceProtected())
this.epoch = epoch;
if (beginAddress == 0)
beginAddress = hlog.GetFirstValidLogicalAddress(0);
this.endAddress = endAddress;
currentAddress = -1;
nextAddress = beginAddress;
if (scanBufferingMode == ScanBufferingMode.SinglePageBuffering)
frameSize = 1;
else if (scanBufferingMode == ScanBufferingMode.DoublePageBuffering)
frameSize = 2;
else if (scanBufferingMode == ScanBufferingMode.NoBuffering)
{
frameSize = 0;
return;
}
frame = new BlittableFrame(frameSize, hlog.PageSize, hlog.GetDeviceSectorSize());
loaded = new CountdownEvent[frameSize];
// Only load addresses flushed to disk
if (nextAddress < hlog.HeadAddress)
{
var frameNumber = (nextAddress >> hlog.LogPageSizeBits) % frameSize;
hlog.AsyncReadPagesFromDeviceToFrame
(nextAddress >> hlog.LogPageSizeBits,
1, endAddress, AsyncReadPagesCallback, Empty.Default,
frame, out loaded[frameNumber]);
}
}
/// <summary>
/// Gets reference to current key
/// </summary>
/// <returns></returns>
public ref Key GetKey()
{
if (currentPhysicalAddress != 0)
return ref hlog.GetKey(currentPhysicalAddress);
return ref currentKey;
}
/// <summary>
/// Gets reference to current value
/// </summary>
/// <returns></returns>
public ref Value GetValue()
{
if (currentPhysicalAddress != 0)
return ref hlog.GetValue(currentPhysicalAddress);
return ref currentValue;
}
/// <summary>
/// Get next record
/// </summary>
/// <param name="recordInfo"></param>
/// <returns>True if record found, false if end of scan</returns>
public bool GetNext(out RecordInfo recordInfo)
{
recordInfo = default;
while (true)
{
currentAddress = nextAddress;
// Check for boundary conditions
if (currentAddress >= endAddress)
{
return false;
}
epoch?.Resume();
var headAddress = hlog.HeadAddress;
if (currentAddress < hlog.BeginAddress)
{
epoch?.Suspend();
throw new FasterException("Iterator address is less than log BeginAddress " + hlog.BeginAddress);
}
if (frameSize == 0 && currentAddress < headAddress)
{
epoch?.Suspend();
throw new FasterException("Iterator address is less than log HeadAddress in memory-scan mode");
}
var currentPage = currentAddress >> hlog.LogPageSizeBits;
var offset = currentAddress & hlog.PageSizeMask;
if (currentAddress < headAddress)
BufferAndLoad(currentAddress, currentPage, currentPage % frameSize);
long physicalAddress;
if (currentAddress >= headAddress)
{
physicalAddress = hlog.GetPhysicalAddress(currentAddress);
currentPhysicalAddress = 0;
}
else
{
currentPhysicalAddress = physicalAddress = frame.GetPhysicalAddress(currentPage % frameSize, offset);
}
// Check if record fits on page, if not skip to next page
var recordSize = hlog.GetRecordSize(physicalAddress).Item2;
if ((currentAddress & hlog.PageSizeMask) + recordSize > hlog.PageSize)
{
nextAddress = (1 + (currentAddress >> hlog.LogPageSizeBits)) << hlog.LogPageSizeBits;
epoch?.Suspend();
continue;
}
nextAddress = currentAddress + recordSize;
ref var info = ref hlog.GetInfo(physicalAddress);
if (info.Invalid || info.IsNull())
{
epoch?.Suspend();
continue;
}
recordInfo = info;
if (currentPhysicalAddress == 0)
{
currentKey = hlog.GetKey(physicalAddress);
currentValue = hlog.GetValue(physicalAddress);
}
epoch?.Suspend();
return true;
}
}
/// <summary>
/// Get next record in iterator
/// </summary>
/// <param name="recordInfo"></param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
public bool GetNext(out RecordInfo recordInfo, out Key key, out Value value)
{
if (GetNext(out recordInfo))
{
key = GetKey();
value = GetValue();
return true;
}
key = default;
value = default;
return false;
}
/// <summary>
/// Dispose the iterator
/// </summary>
public void Dispose()
{
frame?.Dispose();
}
private unsafe void BufferAndLoad(long currentAddress, long currentPage, long currentFrame)
{
if (first || (currentAddress & hlog.PageSizeMask) == 0)
{
// Prefetch pages based on buffering mode
if (frameSize == 1)
{
if (!first)
{
hlog.AsyncReadPagesFromDeviceToFrame(currentAddress >> hlog.LogPageSizeBits, 1, endAddress, AsyncReadPagesCallback, Empty.Default, frame, out loaded[currentFrame]);
}
}
else
{
var endPage = endAddress >> hlog.LogPageSizeBits;
if ((endPage > currentPage) &&
((endPage > currentPage + 1) || ((endAddress & hlog.PageSizeMask) != 0)))
{
hlog.AsyncReadPagesFromDeviceToFrame(1 + (currentAddress >> hlog.LogPageSizeBits), 1, endAddress, AsyncReadPagesCallback, Empty.Default, frame, out loaded[(currentPage + 1) % frameSize]);
}
}
first = false;
}
epoch?.Suspend();
loaded[currentFrame].Wait();
epoch?.Resume();
}
private unsafe void AsyncReadPagesCallback(uint errorCode, uint numBytes, object context)
{
if (errorCode != 0)
{
Trace.TraceError("AsyncReadPagesCallback error: {0}", errorCode);
}
var result = (PageAsyncReadResult<Empty>)context;
if (result.freeBuffer1 != null)
{
hlog.PopulatePage(result.freeBuffer1.GetValidPointer(), result.freeBuffer1.required_bytes, result.page);
result.freeBuffer1.Return();
result.freeBuffer1 = null;
}
if (result.handle != null)
{
result.handle.Signal();
}
Interlocked.MemoryBarrier();
}
}
}
| 34.633333 | 211 | 0.518982 | [
"MIT"
] | FlorianGrimm/Latrans | src/Brimborium.Latrans.StoreageFASTER/Allocator/BlittableScanIterator.cs | 9,353 | C# |
using System;
using System.Collections.Generic;
using System.Data.EntityClient;
using System.Data.Metadata.Edm;
using System.Data.Services;
using System.Data.Services.Common;
using System.Data.SqlClient;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Web;
using StackExchange.DataExplorer.Models.StackEntities;
using System.Collections.Specialized;
using System.Text.RegularExpressions;
using StackExchange.DataExplorer.Helpers;
using StackExchange.DataExplorer.Models;
namespace StackExchange.DataExplorer
{
public class OData : DataService<Entities>
{
const int ConnectionPoolSize = 10;
private static Regex _ipAddress = new Regex(@"\b([0-9]{1,3}\.){3}[0-9]{1,3}$", RegexOptions.Compiled | RegexOptions.ExplicitCapture);
private static bool IsPrivateIP(string s) {
return (s.StartsWith("192.168.") || s.StartsWith("10.") || s.StartsWith("127.0.0."));
}
/// <summary>
/// retrieves the IP address of the current request -- handles proxies and private networks
/// </summary>
public static string GetRemoteIP(NameValueCollection ServerVariables) {
var ip = ServerVariables["REMOTE_ADDR"]; // could be a proxy -- beware
var ipForwarded = ServerVariables["HTTP_X_FORWARDED_FOR"];
// check if we were forwarded from a proxy
if (ipForwarded.HasValue()) {
ipForwarded = _ipAddress.Match(ipForwarded).Value;
if (ipForwarded.HasValue() && !IsPrivateIP(ipForwarded))
ip = ipForwarded;
}
return ip.HasValue() ? ip : "X.X.X.X";
}
public static string GetRemoteIP() {
NameValueCollection ServerVaraibles;
// This is a nasty hack so we don't crash the non-request test cases
if (HttpContext.Current != null && HttpContext.Current.Request != null)
{
ServerVaraibles = HttpContext.Current.Request.ServerVariables;
}
else
{
ServerVaraibles = new NameValueCollection();
}
return GetRemoteIP(ServerVaraibles);
}
// This method is called only once to initialize service-wide policies.
public static void InitializeService(DataServiceConfiguration config)
{
config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
config.SetEntitySetPageSize("*", 50);
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
config.UseVerboseErrors = true;
}
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope",
Justification = "If we dispose our connection our data source will be hosed")]
protected override Entities CreateDataSource()
{
//throw new NotImplementedException("OData has been disabled while diagnosing a resource leak should be up by the 15th of August!");
// var siteName = HttpContext.Current.Request.ServerVariables["ODATA_SITE"].ToLower();
// YES, server vars would be nicer, but unfourtunatly pushing them through with rewrite,
// requires and edit to applicationHost.config, which is super duper hairy in azure.
string siteName = HttpContext.Current.Request.Params["5D6DA575E16342AEB6AF9177FF673569"];
if (siteName == null) {
return null;
}
// how about only 1 request per 1 seconds - people are hammering this stuff like there
// is no tomorrow
string cacheKey = GetRemoteIP() + "_last_odata";
DateTime? lastRequest = HttpContext.Current.Cache.Get(cacheKey) as DateTime?;
if (lastRequest != null && (DateTime.Now - lastRequest.Value).TotalMilliseconds < 1000) {
throw new InvalidOperationException("Sorry only one request per 1 second");
}
HttpContext.Current.Cache[cacheKey] = DateTime.Now;
UriTemplateMatch match = WebOperationContext.Current.IncomingRequest.UriTemplateMatch;
var builder = new UriBuilder(match.BaseUri);
builder.Path = builder.Path.Replace("OData.svc", siteName + "/atom");
Uri serviceUri = builder.Uri;
OperationContext.Current.IncomingMessageProperties["MicrosoftDataServicesRootUri"] = serviceUri;
builder = new UriBuilder(match.RequestUri);
builder.Path = builder.Path.Replace("odata.svc", siteName + "/atom");
builder.Host = serviceUri.Host;
OperationContext.Current.IncomingMessageProperties["MicrosoftDataServicesRequestUri"] = builder.Uri;
SqlConnection sqlConnection = Current.DB.Query<Site>("select * from Sites where lower(Name) = @siteName", new {siteName}).First().GetConnection(ConnectionPoolSize);
Current.RegisterConnectionForDisposal(sqlConnection);
var workspace = new MetadataWorkspace(
new[] {"res://*/"},
new List<Assembly> {GetType().Assembly});
var connection = new EntityConnection(workspace, sqlConnection);
var entities = new Entities(connection);
return entities;
}
protected override void OnStartProcessingRequest(ProcessRequestArgs args)
{
base.OnStartProcessingRequest(args);
HttpCachePolicy c = HttpContext.Current.Response.Cache;
c.SetCacheability(HttpCacheability.ServerAndPrivate);
c.SetExpires(HttpContext.Current.Timestamp.AddSeconds(600));
c.VaryByHeaders["Accept"] = true;
c.VaryByHeaders["Accept-Charset"] = true;
c.VaryByHeaders["Accept-Encoding"] = true;
c.VaryByParams["*"] = true;
// don't allow clients to mess with this. its valid period
c.SetValidUntilExpires(true);
}
}
} | 42.773973 | 177 | 0.631385 | [
"MIT"
] | Nsm7Nash/stack-exchange-data-explorer | App/StackExchange.DataExplorer/OData.svc.cs | 6,247 | C# |
using UnityEngine;
namespace Scripts.Image_Effects
{
[ExecuteInEditMode]
[AddComponentMenu("Image Effects/PixelBoy")]
public class PixelBoy : MonoBehaviour
{
public int w = 720;
int h;
void Update()
{
float ratio = Camera.main.pixelHeight / (float)Camera.main.pixelWidth;
h = Mathf.RoundToInt(w * ratio);
}
void OnRenderImage(RenderTexture source, RenderTexture destination)
{
source.filterMode = FilterMode.Point;
RenderTexture buffer = RenderTexture.GetTemporary(w, h, -1);
buffer.filterMode = FilterMode.Point;
Graphics.Blit(source, buffer);
Graphics.Blit(buffer, destination);
RenderTexture.ReleaseTemporary(buffer);
}
}
} | 28.892857 | 82 | 0.608158 | [
"MIT"
] | Bennef/BIP | Assets/Scripts/Image_Effects/PixelBoy.cs | 809 | C# |
using System;
using UnityEngine;
namespace UnityEditor.VFX.Operator
{
[VFXInfo(category = "Bitwise")]
class BitwiseAnd : VFXOperator
{
override public string name { get { return "And"; } }
public class InputProperties
{
static public uint FallbackValue = 0;
[Tooltip("Sets the first operand.")]
public uint a = FallbackValue;
[Tooltip("Sets the second operand.")]
public uint b = FallbackValue;
}
public class OutputProperties
{
[Tooltip("Outputs the result of the logical AND operation between the two operands. For example, 5 (0101 in binary) with 3 (0011 in binary) returns 1 (0001 in binary).")]
public uint o = 0;
}
protected override sealed VFXExpression[] BuildExpression(VFXExpression[] inputExpression)
{
return new[] { new VFXExpressionBitwiseAnd(inputExpression[0], inputExpression[1]) };
}
}
}
| 31.3125 | 182 | 0.610778 | [
"MIT"
] | Acromatic/HDRP-Unity-Template-GitHub-Template | Library/PackageCache/com.unity.visualeffectgraph@10.2.2/Editor/Models/Operators/Implementations/BitwiseAnd.cs | 1,002 | C# |
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEditor;
namespace ME.ECSEditor {
using ME.ECS;
public class WorldsViewerEditor : EditorWindow {
public class WorldEditor {
public World world;
public bool foldout;
public bool foldoutSystems;
public bool foldoutModules;
public bool foldoutEntitiesStorage;
public bool foldoutFilters;
private List<ME.ECS.IStorage> foldoutStorages = new List<ME.ECS.IStorage>();
private Dictionary<object, int> pageObjects = new Dictionary<object, int>();
private Dictionary<object, int> onPageCountObjects = new Dictionary<object, int>();
private Dictionary<object, string> searchObjects = new Dictionary<object, string>();
private HashSet<int> foldoutCustoms = new HashSet<int>();
private Dictionary<object, List<int>> foldoutStorageFilters = new Dictionary<object, List<int>>();
private Dictionary<object, List<int>> foldoutStorageData = new Dictionary<object, List<int>>();
private Dictionary<object, List<int>> foldoutStorageStructComponents = new Dictionary<object, List<int>>();
private Dictionary<object, List<int>> foldoutStorageViews = new Dictionary<object, List<int>>();
public bool IsFoldOutCustom(object instance) {
var hc = (instance != null ? instance.GetHashCode() : 0);
return this.foldoutCustoms.Contains(hc);
}
public void SetFoldOutCustom(object instance, bool state) {
var hc = (instance != null ? instance.GetHashCode() : 0);
if (state == true) {
if (this.foldoutCustoms.Contains(hc) == false) this.foldoutCustoms.Add(hc);
} else {
this.foldoutCustoms.Remove(hc);
}
}
public bool IsFoldOutFilters(object key, int entityId) {
List<int> list;
if (this.foldoutStorageFilters.TryGetValue(key, out list) == true) {
return list.Contains(entityId);
}
return false;
}
public void SetFoldOutFilters(object key, int entityId, bool state) {
List<int> list;
if (this.foldoutStorageFilters.TryGetValue(key, out list) == true) {
if (state == true) {
if (list.Contains(entityId) == false) list.Add(entityId);
} else {
list.Remove(entityId);
}
} else {
if (state == true) {
list = new List<int>();
list.Add(entityId);
this.foldoutStorageFilters.Add(key, list);
}
}
}
public bool IsFoldOutStructComponents(object storage, int entityId) {
List<int> list;
if (this.foldoutStorageStructComponents.TryGetValue(storage, out list) == true) {
return list.Contains(entityId);
}
return true;
}
public void SetFoldOutStructComponents(object storage, int entityId, bool state) {
List<int> list;
if (this.foldoutStorageStructComponents.TryGetValue(storage, out list) == true) {
if (state == true) {
if (list.Contains(entityId) == false) list.Add(entityId);
} else {
list.Remove(entityId);
}
} else {
if (state == true) {
list = new List<int>();
list.Add(entityId);
this.foldoutStorageStructComponents.Add(storage, list);
}
}
}
public bool IsFoldOutData(object storage, int entityId) {
List<int> list;
if (this.foldoutStorageData.TryGetValue(storage, out list) == true) {
return list.Contains(entityId);
}
return true;
}
public void SetFoldOutData(object storage, int entityId, bool state) {
List<int> list;
if (this.foldoutStorageData.TryGetValue(storage, out list) == true) {
if (state == true) {
if (list.Contains(entityId) == false) list.Add(entityId);
} else {
list.Remove(entityId);
}
} else {
if (state == true) {
list = new List<int>();
list.Add(entityId);
this.foldoutStorageData.Add(storage, list);
}
}
}
public bool IsFoldOutViews(object storage, int entityId) {
List<int> list;
if (this.foldoutStorageViews.TryGetValue(storage, out list) == true) {
return list.Contains(entityId);
}
return true;
}
public void SetFoldOutViews(object storage, int entityId, bool state) {
List<int> list;
if (this.foldoutStorageViews.TryGetValue(storage, out list) == true) {
if (state == true) {
if (list.Contains(entityId) == false) list.Add(entityId);
} else {
list.Remove(entityId);
}
} else {
if (state == true) {
list = new List<int>();
list.Add(entityId);
this.foldoutStorageViews.Add(storage, list);
}
}
}
public bool IsFoldOut(IStorage storage) {
return this.foldoutStorages.Contains(storage);
}
public void SetFoldOut(IStorage storage, bool state) {
if (state == true) {
if (this.foldoutStorages.Contains(storage) == false) this.foldoutStorages.Add(storage);
} else {
this.foldoutStorages.Remove(storage);
}
}
public int GetPage(object storage) {
if (this.pageObjects.ContainsKey(storage) == false) {
return 0;
}
return this.pageObjects[storage];
}
public void SetPage(object storage, int page) {
if (this.pageObjects.ContainsKey(storage) == true) {
this.pageObjects[storage] = page;
} else {
this.pageObjects.Add(storage, page);
}
}
public int GetOnPageCount(object storage) {
if (this.onPageCountObjects.ContainsKey(storage) == false) {
return 10;
}
return this.onPageCountObjects[storage];
}
public void SetOnPageCount(object storage, int page) {
if (this.onPageCountObjects.ContainsKey(storage) == true) {
this.onPageCountObjects[storage] = page;
} else {
this.onPageCountObjects.Add(storage, page);
}
}
public string GetSearch(object storage) {
if (this.searchObjects.ContainsKey(storage) == false) {
return string.Empty;
}
return this.searchObjects[storage];
}
public void SetSearch(object storage, string search) {
if (this.searchObjects.ContainsKey(storage) == true) {
this.searchObjects[storage] = search;
} else {
this.searchObjects.Add(storage, search);
}
}
public FiltersStorage GetFilters() {
return WorldHelper.GetFilters(this.world);
}
public IStructComponentsContainer GetStructComponentsStorage() {
return WorldHelper.GetStructComponentsStorage(this.world);
}
public Storage GetEntitiesStorage() {
return WorldHelper.GetEntitiesStorage(this.world);
}
public ME.ECS.Collections.BufferArray<SystemGroup> GetSystems() {
return WorldHelper.GetSystems(this.world);
}
public ME.ECS.Collections.ListCopyable<ME.ECS.IModuleBase> GetModules() {
return WorldHelper.GetModules(this.world);
}
public bool HasMethod(object instance, string methodName) {
return WorldHelper.HasMethod(instance, methodName);
}
public override string ToString() {
return "World " + this.world.id.ToString() + " (Tick: " + this.world.GetCurrentTick().ToString() + ")";
}
}
private List<WorldEditor> worlds = new List<WorldEditor>();
private Vector2 scrollPosition;
private Vector2 scrollEntitiesPosition;
[MenuItem("ME.ECS/Worlds Viewer...")]
public static void ShowInstance() {
var instance = EditorWindow.GetWindow(typeof(WorldsViewerEditor));
var icon = EditorUtilities.Load<Texture2D>("ECSEditor/EditorResources/icon-worldviewer.png");
instance.titleContent = new GUIContent("Worlds Viewer", icon);
instance.Show();
}
public void Update() {
this.Repaint();
}
private static Dictionary<System.Type, IGUIEditorBase> editors;
public static IGUIEditorBase GetEditor<T>(T instance, IGUIEditorBase editor) {
var editorT = editor as IGUIEditor<T>;
if (editorT != null) {
editorT.target = instance;
return editorT;
} else {
var prop = editor.GetType().GetProperty("target", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.SetProperty | System.Reflection.BindingFlags.Public);
if (prop != null) {
prop.SetValue(editor, instance);
return editor;
}
}
return null;
}
public static IGUIEditorBase GetEditor<T>(T[] instances, IGUIEditorBase editor) {
var editorT = editor as IGUIEditor<T>;
if (editorT != null) {
editorT.target = instances[0];
editorT.targets = instances;
return editorT;
} else {
var prop = editor.GetType().GetProperty("target", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.SetProperty | System.Reflection.BindingFlags.Public);
if (prop != null) {
prop.SetValue(editor, instances[0]);
return editor;
}
var propTargets = editor.GetType().GetProperty("targets", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.SetProperty | System.Reflection.BindingFlags.Public);
if (propTargets != null) {
propTargets.SetValue(editor, instances);
return editor;
}
}
return null;
}
public static IGUIEditorBase GetEditor<T>(T instance, System.Type type) {
IGUIEditorBase editor;
if (WorldsViewerEditor.editors.TryGetValue(type, out editor) == true) {
return WorldsViewerEditor.GetEditor(instance, editor);
}
return null;
}
public static IGUIEditorBase GetEditor<T>(T[] instances, System.Type type) {
IGUIEditorBase editor;
if (WorldsViewerEditor.editors.TryGetValue(type, out editor) == true) {
return WorldsViewerEditor.GetEditor(instances, editor);
}
return null;
}
public static IGUIEditorBase GetEditor<T>(T[] instances) {
return WorldsViewerEditor.GetEditor(instances, out _);
}
public static IGUIEditorBase GetEditor<T>(T instance) {
return WorldsViewerEditor.GetEditor(instance, out _);
}
public static IGUIEditorBase GetEditor<T>(T[] instances, out int order) {
if (WorldsViewerEditor.editors == null) GUILayoutExt.CollectEditors<IGUIEditorBase, CustomEditorAttribute>(ref WorldsViewerEditor.editors);
order = 0;
var type = instances[0].GetType();
while (type != null && type != typeof(object)) {
var editor = WorldsViewerEditor.GetEditor(instances, type);
if (editor != null) {
var attrs = editor.GetType().GetCustomAttributes(typeof(CustomEditorAttribute), inherit: true);
order = ((CustomEditorAttribute)attrs[0]).order;
return editor;
}
var interfaces = type.GetInterfaces();
foreach (var @interface in interfaces) {
editor = WorldsViewerEditor.GetEditor(instances, @interface);
if (editor != null) {
var attrs = editor.GetType().GetCustomAttributes(typeof(CustomEditorAttribute), inherit: true);
order = ((CustomEditorAttribute)attrs[0]).order;
return editor;
}
}
type = type.BaseType;
}
return null;
}
public static IGUIEditorBase GetEditor<T>(T instance, out int order) {
if (WorldsViewerEditor.editors == null) GUILayoutExt.CollectEditors<IGUIEditorBase, CustomEditorAttribute>(ref WorldsViewerEditor.editors);
order = 0;
var type = instance.GetType();
while (type != null && type != typeof(object)) {
var editor = WorldsViewerEditor.GetEditor(instance, type);
if (editor != null) {
var attrs = editor.GetType().GetCustomAttributes(typeof(CustomEditorAttribute), inherit: true);
order = ((CustomEditorAttribute)attrs[0]).order;
return editor;
}
var interfaces = type.GetInterfaces();
foreach (var @interface in interfaces) {
editor = WorldsViewerEditor.GetEditor(instance, @interface);
if (editor != null) {
var attrs = editor.GetType().GetCustomAttributes(typeof(CustomEditorAttribute), inherit: true);
order = ((CustomEditorAttribute)attrs[0]).order;
return editor;
}
}
type = type.BaseType;
}
return null;
}
private void OnEnable() { EditorApplication.update += this.OnTryRepaint; }
private void OnDisable() { EditorApplication.update -= this.OnTryRepaint; }
private void OnTryRepaint() {
if(!this.refresh) return;
this.refresh = false;
base.Repaint();
}
private static readonly int resizePanelControlID = "ResizePanel".GetHashCode();
private float worldsSizeWidth = 300f;
private Vector2 lastMousePos;
private Vector2 dragDistance;
private float dragStartWidth;
private bool refresh;
private bool isDrag;
private void HandleResizePanels() {
this.refresh = this.position.Contains(Event.current.mousePosition);
var panelRect = new Rect(this.worldsSizeWidth + 6f, 0f, 6f, this.position.height);
var current = Event.current;
var controlID = GUIUtility.GetControlID(WorldsViewerEditor.resizePanelControlID, FocusType.Passive);
var hotControl = GUIUtility.hotControl;
//specify the area where you can click and drag from
var dragRegion = new Rect(panelRect.xMax - 5, panelRect.yMin - 5, 10, panelRect.height + 10);
EditorGUIUtility.AddCursorRect(dragRegion, MouseCursor.ResizeHorizontal);
if (this.isDrag == true) {
var color = Color.white;
color.a = 0.1f;
EditorGUI.DrawRect(panelRect, color);
}
switch (current.GetTypeForControl(controlID)) {
case EventType.MouseDown:
if (current.button == 0) {
var canDrag = dragRegion.Contains(current.mousePosition);
if (!canDrag) {
return;
}
//record in screenspace, not GUI space so that the resizing is consistent even if the cursor leaves the window
this.lastMousePos = GUIUtility.GUIToScreenPoint(current.mousePosition);
this.dragDistance = Vector2.zero;
this.dragStartWidth = this.worldsSizeWidth;
this.isDrag = true;
GUIUtility.hotControl = controlID;
current.Use();
}
break;
case EventType.MouseUp:
if (hotControl == controlID) {
this.isDrag = false;
GUIUtility.hotControl = 0;
current.Use();
}
break;
case EventType.MouseDrag:
if (hotControl == controlID) {
EditorGUIUtility.AddCursorRect(this.position, MouseCursor.ResizeHorizontal);
this.isDrag = true;
var screenPoint = GUIUtility.GUIToScreenPoint(current.mousePosition);
this.dragDistance += screenPoint - this.lastMousePos;
this.lastMousePos = screenPoint;
this.worldsSizeWidth = Mathf.Max(200, Mathf.Min(this.dragStartWidth + this.dragDistance.x, this.position.width - 200));
//this.refresh = true;
this.refresh = true;
current.Use();
}
break;
case EventType.KeyDown:
if (hotControl == controlID && current.keyCode == KeyCode.Escape) {
this.worldsSizeWidth = Mathf.Max(200, Mathf.Min(this.dragStartWidth, this.position.width - 200));
this.isDrag = false;
GUIUtility.hotControl = 0;
current.Use();
}
break;
/*case EventType.Layout:
case EventType.Repaint:
EditorGUI.DrawRect(dragRegion,Color.black);
break;*/
}
}
public void OnGUI() {
if (WorldsViewerEditor.editors == null) GUILayoutExt.CollectEditors<IGUIEditorBase, ComponentCustomEditorAttribute>(ref WorldsViewerEditor.editors);
if (this.worlds.Count != ME.ECS.Worlds.registeredWorlds.Count) {
this.worlds.Clear();
foreach (var item in ME.ECS.Worlds.registeredWorlds) {
var worldEditor = new WorldEditor();
worldEditor.world = item;
this.worlds.Add(worldEditor);
}
}
GUILayoutExt.Padding(6f, () => {
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true));
{
GUILayout.BeginVertical(GUILayout.Width(this.worldsSizeWidth), GUILayout.ExpandHeight(true));
GUILayout.Space(1.5f); // Unity GUI bug: we need to add extra space when use GUILayout.Width() control
var world = this.DrawWorlds();
GUILayout.Space(2f); // Unity GUI bug: we need to add extra space when use GUILayout.Width() control
GUILayout.EndVertical();
GUILayout.Space(4f);
GUILayout.BeginVertical(GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true));
this.DrawEntities(world);
GUILayout.EndVertical();
}
GUILayout.EndHorizontal();
});
this.HandleResizePanels();
}
public static void SelectEntity(Entity entity) {
var found = false;
var entities = Worlds.currentWorld.GetDebugEntities();
foreach (var ent in entities) {
if (ent.Key == entity) {
Selection.activeObject = ent.Value.gameObject;
found = true;
break;
}
}
if (found == false) {
var objects = GameObject.FindObjectsOfType<ME.ECS.Debug.EntityDebugComponent>();
foreach (var obj in objects) {
if (obj.entity == entity) {
Selection.activeObject = obj.gameObject;
found = true;
break;
}
}
}
if (found == false) {
if (entity.IsAlive() == false) {
EditorWindow.focusedWindow.ShowNotification(new GUIContent(entity.ToString() + " already in pool"));
} else {
var debug = new GameObject("Debug-" + entity.ToString(), typeof(ME.ECS.Debug.EntityDebugComponent));
var info = debug.GetComponent<ME.ECS.Debug.EntityDebugComponent>();
info.entity = entity;
info.world = Worlds.currentWorld;
info.hasName = false;
Selection.activeObject = debug;
}
}
}
private void DrawEntities(WorldEditor world) {
var style = EditorStyles.helpBox;
this.scrollEntitiesPosition = GUILayout.BeginScrollView(this.scrollEntitiesPosition, style, GUILayout.ExpandHeight(true));
{
if (world == null) {
var centeredStyle = new GUIStyle(EditorStyles.centeredGreyMiniLabel);
centeredStyle.stretchHeight = true;
centeredStyle.richText = true;
GUILayout.Label(@"Select world from the left list.", centeredStyle);
} else {
//var padding = 2f;
//var margin = 1f;
var dataStyle = new GUIStyle(EditorStyles.label);
dataStyle.richText = true;
dataStyle.wordWrap = true;
var modules = world.GetModules();
var componentsStructStorage = world.GetStructComponentsStorage();
var storage = (IStorage)world.GetEntitiesStorage();
GUILayout.BeginVertical();
{
var foldout = world.IsFoldOut(storage);
GUILayoutExt.FoldOut(ref foldout, GUILayoutExt.GetTypeLabel(storage.GetType()), () => {
var elements = PoolListCopyable<Entity>.Spawn(storage.AliveCount);
var elementsIdx = PoolListCopyable<int>.Spawn(storage.AliveCount);
var paramsList = PoolListCopyable<string>.Spawn(4);
var search = world.GetSearch(storage).ToLower();
var searchList = search.Split(new [] { ' ' }, System.StringSplitOptions.RemoveEmptyEntries);
var allEntities = PoolListCopyable<Entity>.Spawn(storage.AliveCount);
if (storage.ForEach(allEntities) == true) {
for (int i = 0; i < allEntities.Count; ++i) {
ref var entity = ref allEntities[i];
if (string.IsNullOrEmpty(search) == false) {
paramsList.Clear();
var name = entity.Read<ME.ECS.Name.Name>().value;
if (name != null) paramsList.Add(name.ToLower());
var registries = componentsStructStorage.GetAllRegistries();
for (int k = 0; k < registries.Length; ++k) {
var registry = registries.arr[k];
if (registry == null) continue;
var component = registry.GetObject(entity);
if (component == null) continue;
var compName = component.GetType().Name.ToLower();
paramsList.Add(compName);
}
if (paramsList.Count == 0) continue;
var notFound = false;
foreach (var p in searchList) {
if (paramsList.Contains(p) == false) {
notFound = true;
break;
}
}
if (notFound == true) continue;
}
elements.Add(entity);
elementsIdx.Add(i);
}
}
PoolListCopyable<Entity>.Recycle(ref allEntities);
PoolListCopyable<string>.Recycle(ref paramsList);
var elementsOnPage = world.GetOnPageCount(storage);
world.SetPage(storage, GUILayoutExt.Pages(elements.Count, world.GetPage(storage), elementsOnPage, (from, to) => {
if (elements.Count == 0) {
GUILayout.BeginVertical(GUILayout.ExpandHeight(true));
{
var centeredStyle = new GUIStyle(EditorStyles.centeredGreyMiniLabel);
centeredStyle.stretchHeight = true;
centeredStyle.richText = true;
GUILayout.Label("No entities found with the name component <b>" + search + "</b>.",
centeredStyle);
}
GUILayout.EndVertical();
} else {
for (var i = from; i < to; ++i) {
var item = elements[i];
var entityData = item;
GUILayout.Space(2f);
WorldsViewerEditor.DrawEntity(null, entityData, world, storage, componentsStructStorage, modules);
//list.Set(elementsIdx[i], entityData);
}
}
}, (onPage) => { world.SetOnPageCount(storage, onPage); },
() => {
world.SetSearch(
storage, EditorGUILayout.TextField(world.GetSearch(storage), EditorStyles.toolbarSearchField));
}
));
PoolListCopyable<Entity>.Recycle(ref elements);
PoolListCopyable<int>.Recycle(ref elementsIdx);
});
world.SetFoldOut(storage, foldout);
}
GUILayout.EndVertical();
}
}
GUILayout.EndScrollView();
}
public class DuplicateKeyComparer<TKey>
:
IComparer<TKey> where TKey : System.IComparable
{
#region IComparer<TKey> Members
public int Compare(TKey x, TKey y)
{
int result = x.CompareTo(y);
if (result == 0)
return 1; // Handle equality as beeing greater
else
return result;
}
#endregion
}
struct SharedRegistryData {
public uint groupId;
public IStructComponentBase component;
public IStructRegistryBase registry;
}
public static void DrawEntity(string search, Entity entityData, WorldEditor world, IStorage storage, IStructComponentsContainer componentsStructStorage, ME.ECS.Collections.ListCopyable<IModuleBase> modules) {
const float padding = 8f;
EditorGUIUtility.wideMode = true;
var name = (entityData.Has<ME.ECS.Name.Name>() == true ? entityData.Read<ME.ECS.Name.Name>().value : "Unnamed");
GUILayoutExt.DrawHeader("Entity " + entityData.id.ToString() + " (" + entityData.generation.ToString() + ") " + name);
{
var usedComponents = new HashSet<System.Type>();
var style = new GUIStyle(EditorStyles.toolbar);
style.fixedHeight = 0f;
style.stretchHeight = true;
GUILayoutExt.Box(
padding,
0f,
() => {
#region Data
//var foldoutData = world.IsFoldOutData(storage, entityData.id);
//GUILayoutExt.DrawFields(entityData);
var backStyle = new GUIStyle(EditorStyles.label);
backStyle.normal.background = Texture2D.whiteTexture;
var header = new GUIStyle(backStyle);
header.fixedHeight = 40f;
header.alignment = TextAnchor.MiddleCenter;
var backColor = GUI.backgroundColor;
GUI.backgroundColor = new Color(1f, 1f, 1f, 0.05f);
GUILayout.BeginHorizontal(backStyle);
{
GUILayout.Label("ID: " + entityData.id.ToString(), EditorStyles.miniLabel);
GUILayout.Label("Gen: " + entityData.generation.ToString(), EditorStyles.miniLabel);
GUILayout.Label("Version: " + entityData.GetVersion().ToString(), EditorStyles.miniLabel);
}
GUILayout.EndHorizontal();
GUILayoutExt.Separator();
GUI.backgroundColor = backColor;
#endregion
EditorGUILayout.Separator();
#region Components
{
var registries = componentsStructStorage.GetAllRegistries();
var sortedRegistries = new List<IStructRegistryBase>();
var components = new List<IStructComponentBase>();
for (int i = 0; i < registries.Length; ++i) {
var registry = registries.arr[i];
if (registry == null) {
continue;
}
#if VIEWS_MODULE_SUPPORT
if (registry is StructComponents<ME.ECS.Views.ViewComponent>) continue;
#endif
var component = registry.GetObject(entityData);
if (component == null) {
continue;
}
usedComponents.Add(component.GetType());
components.Add(registry.GetObject(entityData));
sortedRegistries.Add(registry);
}
GUILayoutExt.DrawFieldsSingle(search, entityData.ToString(), world, components.ToArray(),
(index, component, prop) => {
GUILayout.BeginVertical();
},
(index, component, prop) => {
usedComponents.Add(component.GetType());
GUILayoutExt.DrawComponentHelp(component.GetType());
GUILayout.EndVertical();
GUILayoutExt.Separator();
}, (index, component) => {
sortedRegistries[index].SetObject(entityData, component);
});
GUILayoutExt.DrawAddComponentMenu(entityData, usedComponents, componentsStructStorage);
}
#endregion
#region Shared Components
{
var registries = componentsStructStorage.GetAllRegistries();
var sortedRegistries = new List<SharedRegistryData>();
var components = new List<IStructComponentBase>();
for (int i = 0; i < registries.Length; ++i) {
var registry = registries.arr[i];
if (registry == null) {
continue;
}
#if VIEWS_MODULE_SUPPORT
if (registry is StructComponents<ME.ECS.Views.ViewComponent>) continue;
#endif
var groupIds = registry.GetSharedGroups(entityData);
if (groupIds != null) {
foreach (var groupId in groupIds) {
var component = registry.GetSharedObject(entityData, groupId);
if (component == null) {
continue;
}
if (GUILayoutExt.IsSearchValid(component, search) == false) continue;
usedComponents.Add(component.GetType());
components.Add(component);
var item = new SharedRegistryData() {
groupId = groupId,
component = component,
registry = registry,
};
sortedRegistries.Add(item);
}
}
}
var isFoldoutShared = world.IsFoldOutViews("Shared", entityData.id);
GUILayoutExt.FoldOut(ref isFoldoutShared, $"Shared Components ({sortedRegistries.Count})", () => {
GUILayoutExt.DrawFieldsSingle(search, entityData.ToString(), world, components.ToArray(),
(index, component, prop) => {
GUILayout.BeginVertical();
},
(index, component, prop) => {
usedComponents.Add(component.GetType());
GUILayoutExt.DrawComponentHelp(component.GetType());
GUILayout.EndVertical();
GUILayoutExt.Separator();
}, (index, component) => {
sortedRegistries[index].registry.SetSharedObject(entityData, component, sortedRegistries[index].groupId);
});
GUILayoutExt.DrawAddComponentMenu(entityData, usedComponents, componentsStructStorage);
});
world.SetFoldOutViews("Shared", entityData.id, isFoldoutShared);
}
#endregion
#region Filters
{
var filtersCnt = 0;
var containsFilters = PoolListCopyable<FilterData>.Spawn(1);
var filters = world.GetFilters();
for (int i = 0; i < filters.filters.Length; ++i) {
var filter = filters.filters.arr[i];
if (filter == null) continue;
if (filter.Contains(entityData) == true) {
containsFilters.Add(filter);
++filtersCnt;
}
}
var foldoutFilters = world.IsFoldOutFilters("Filters", entityData.id);
GUILayoutExt.FoldOut(ref foldoutFilters, "Filters (" + filtersCnt.ToString() + ")", () => {
foreach (var filter in containsFilters) {
WorldsViewerEditor.DrawFilter(filters, filter);
}
});
world.SetFoldOutFilters("Filters", entityData.id, foldoutFilters);
PoolListCopyable<FilterData>.Recycle(ref containsFilters);
}
#endregion
#if VIEWS_MODULE_SUPPORT
var activeViews = PoolListCopyable<ME.ECS.Views.IView>.Spawn(1);
var activeViewProviders = PoolListCopyable<ME.ECS.Views.IViewModuleBase>.Spawn(1);
var viewsModules = modules.OfType<ME.ECS.Views.IViewModuleBase>().ToArray();
foreach (var viewsModule in viewsModules) {
if (viewsModule != null) {
var allViews = viewsModule.GetData();
for (var k = 0; k < allViews.Length; ++k) {
if (k == entityData.id) {
var listViews = allViews.arr[k];
if (listViews.isNotEmpty == false) continue;
for (var j = 0; j < listViews.Length; ++j) {
activeViews.Add(listViews[j]);
activeViewProviders.Add(viewsModule);
}
}
}
}
}
if (activeViews.Count > 0) {
var foldoutViews = world.IsFoldOutViews("Views", entityData.id);
GUILayoutExt.FoldOut(ref foldoutViews, string.Format("Views ({0})", activeViews.Count), () => {
{ // Draw views table
for (var j = 0; j < activeViews.Count; ++j) {
var view = activeViews[j];
var provider = activeViewProviders[j].GetViewSourceProvider(view.prefabSourceId);
GUILayout.Label("Provider: " + GUILayoutExt.GetTypeLabel(provider.GetType()), EditorStyles.miniBoldLabel);
if (view is Object obj) {
EditorGUI.BeginDisabledGroup(true);
EditorGUILayout.ObjectField("Scene Object: ", obj, typeof(Object), allowSceneObjects: true);
EditorGUI.EndDisabledGroup();
}
GUILayout.Label(view.ToString(), EditorStyles.miniLabel);
//GUILayout.Label("Prefab Source Id: " + view.prefabSourceId.ToString());
//GUILayout.Label("Creation Tick: " +view.creationTick.ToString());
}
}
});
world.SetFoldOutViews("Views", entityData.id, foldoutViews);
}
PoolListCopyable<ME.ECS.Views.IView>.Recycle(ref activeViews);
PoolListCopyable<ME.ECS.Views.IViewModuleBase>.Recycle(ref activeViewProviders);
#endif
}, style);
}
}
private WorldEditor DrawWorlds() {
WorldEditor selectedWorld = null;
var style = EditorStyles.helpBox;
this.scrollPosition = GUILayout.BeginScrollView(this.scrollPosition, style, GUILayout.ExpandHeight(true));
{
if (this.worlds.Count == 0) {
var centeredStyle = new GUIStyle(EditorStyles.centeredGreyMiniLabel);
centeredStyle.stretchHeight = true;
centeredStyle.richText = true;
GUILayout.Label("This is runtime utility to view current running worlds.\nPress <b>Play</b> to start profiling.", centeredStyle);
} else {
foreach (var worldEditor in this.worlds) {
var systems = worldEditor.GetSystems();
var modules = worldEditor.GetModules();
var storage = worldEditor.GetEntitiesStorage();
var filters = worldEditor.GetFilters();
var world = worldEditor.world;
GUILayoutExt.Padding(4f, () => {
if (this.worlds.Count == 1) worldEditor.foldout = true;
GUILayoutExt.FoldOut(ref worldEditor.foldout, $"{worldEditor} (Hash: {worldEditor.world.GetStateHash()})", () => {
GUILayoutExt.Box(2f, 4f, () => {
var inUseCount = filters.GetAllFiltersArchetypeCount();
var max = Archetype.MAX_BIT_INDEX + 1;
var percent = Mathf.FloorToInt(inUseCount / (float)max * 100);
GUILayout.Label($"Components in use: {inUseCount}/{max} ({percent}%)");
var fillColor = new Color32(80, 229, 80, 255);
if (percent >= 99) {
fillColor = new Color32(229, 80, 80, 255);
EditorGUILayout.HelpBox("Seems like you have reached limit of bits for Archetype. Increase size in Initializer Defines.", MessageType.Error);
} else if (percent >= 80) {
fillColor = new Color32(189, 180, 40, 255);
EditorGUILayout.HelpBox("Seems like you are approaching the limit of max bits for Archetype. Increase size in Initializer Defines.", MessageType.Warning);
}
GUILayoutExt.ProgressBar(inUseCount, max, new Color(0f, 0f, 0f, 0.5f), fillColor);
GUILayout.Label($"State Tick: {worldEditor.world.GetStateTick()}");
GUILayout.Label($"Tick: {worldEditor.world.GetCurrentTick()}");
GUILayout.Label($"Tick Time: {worldEditor.world.GetTickTime()}ms.");
GUILayout.Label($"Time: {ME.ECS.MathUtils.SecondsToString(worldEditor.world.GetTimeSinceStart())}");
});
GUILayoutExt.FoldOut(ref worldEditor.foldoutSystems, $"Systems ({systems.Count})", () => {
var cellHeight = 25f;
var padding = 2f;
var margin = 1f;
var col1 = 250f;
var col2 = 50f;
var col3 = 50f;
var tableStyle = (GUIStyle)"Box";
//var dataStyle = new GUIStyle(EditorStyles.label);
GUILayoutExt.Padding(4f, () => {
GUILayout.BeginHorizontal();
{
GUILayoutExt.Box(padding, margin, () => { GUILayoutExt.TableCaption("Caption", EditorStyles.miniBoldLabel); }, tableStyle,
GUILayout.Width(col1),
GUILayout.Height(cellHeight));
GUILayoutExt.Box(padding, margin, () => { GUILayoutExt.TableCaption("Logic", EditorStyles.miniBoldLabel); }, tableStyle,
GUILayout.Width(col2),
GUILayout.Height(cellHeight));
GUILayoutExt.Box(padding, margin, () => { GUILayoutExt.TableCaption("Visual", EditorStyles.miniBoldLabel); }, tableStyle,
GUILayout.Width(col3),
GUILayout.Height(cellHeight));
}
GUILayout.EndHorizontal();
for (int i = 0; i < systems.Length; ++i) {
var group = systems.arr[i];
if (group.runtimeSystem.allSystems == null) continue;
var foldoutObj = group.runtimeSystem.allSystems;
var groupState = worldEditor.IsFoldOutCustom(foldoutObj);
GUILayoutExt.FoldOut(ref groupState, $"{@group.name} ({@group.runtimeSystem.allSystems.Count})", () => {
for (int j = 0; j < group.runtimeSystem.allSystems.Count; ++j) {
var system = group.runtimeSystem.allSystems[j];
GUILayout.BeginHorizontal();
{
GUILayoutExt.Box(padding, margin, () => { GUILayoutExt.TypeLabel(system.GetType()); }, tableStyle, GUILayout.Width(col1),
GUILayout.Height(cellHeight));
}
{ // Logic
GUILayoutExt.Box(padding, margin, () => {
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.FlexibleSpace();
var state = world.IsSystemActive(system, RuntimeSystemFlag.Logic);
this.ToggleMethod(worldEditor, system, "AdvanceTick", ref state);
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
}, tableStyle, GUILayout.Width(col2), GUILayout.Height(cellHeight));
}
{ // Visual
GUILayoutExt.Box(padding, margin, () => {
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.FlexibleSpace();
var state = world.IsSystemActive(system, RuntimeSystemFlag.Visual);
this.ToggleMethod(worldEditor, system, "Update", ref state);
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
}, tableStyle, GUILayout.Width(col3), GUILayout.Height(cellHeight));
}
GUILayout.EndHorizontal();
{
GUILayoutExt.Box(padding, margin, () => {
/*if (system is IGUIEditor systemEditor) {
systemEditor.OnDrawGUI();
}*/
}, tableStyle, GUILayout.ExpandWidth(true));
GUILayout.Space(2f);
}
}
});
worldEditor.SetFoldOutCustom(foldoutObj, groupState);
}
});
});
GUILayoutExt.FoldOut(ref worldEditor.foldoutModules, $"Modules ({modules.Count})", () => {
var cellHeight = 25f;
var padding = 2f;
var margin = 1f;
var col2 = 50f;
var col3 = 50f;
var tableStyle = (GUIStyle)"Box";
var dataStyle = new GUIStyle(EditorStyles.label);
dataStyle.richText = true;
dataStyle.wordWrap = true;
GUILayoutExt.Padding(4f, () => {
GUILayout.BeginHorizontal();
{
GUILayoutExt.Box(padding, margin, () => { GUILayoutExt.TableCaption("Caption", EditorStyles.miniBoldLabel); }, tableStyle,
GUILayout.ExpandWidth(true),
GUILayout.Height(cellHeight));
GUILayoutExt.Box(padding, margin, () => { GUILayoutExt.TableCaption("Logic", EditorStyles.miniBoldLabel); }, tableStyle,
GUILayout.Width(col2),
GUILayout.Height(cellHeight));
GUILayoutExt.Box(padding, margin, () => { GUILayoutExt.TableCaption("Visual", EditorStyles.miniBoldLabel); }, tableStyle,
GUILayout.Width(col3),
GUILayout.Height(cellHeight));
//GUILayoutExt.Box(2f, 1f, () => { GUILayoutExt.TableCaption("Info", EditorStyles.miniBoldLabel); }, tableStyle,
// GUILayout.ExpandWidth(true), GUILayout.Height(cellHeight));
}
GUILayout.EndHorizontal();
foreach (var module in modules) {
GUILayout.BeginHorizontal();
{
GUILayoutExt.Box(padding, margin, () => { GUILayoutExt.TypeLabel(module.GetType()); }, tableStyle, GUILayout.ExpandWidth(true),
GUILayout.Height(cellHeight));
}
{ // Logic
GUILayoutExt.Box(padding, margin, () => {
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.FlexibleSpace();
var flag = world.GetModuleState(module);
var state = (flag & ME.ECS.ModuleState.LogicInactive) == 0;
if (this.ToggleMethod(worldEditor, module, "AdvanceTick", ref state) == true) {
world.SetModuleState(
module, state == false ? flag | ME.ECS.ModuleState.LogicInactive : flag & ~ME.ECS.ModuleState.LogicInactive);
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
}, tableStyle, GUILayout.Width(col2), GUILayout.Height(cellHeight));
}
{ // Visual
GUILayoutExt.Box(padding, margin, () => {
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.FlexibleSpace();
var flag = world.GetModuleState(module);
var state = (flag & ME.ECS.ModuleState.VisualInactive) == 0;
if (this.ToggleMethod(worldEditor, module, "Update", ref state) == true) {
world.SetModuleState(
module, state == false ? flag | ME.ECS.ModuleState.VisualInactive : flag & ~ME.ECS.ModuleState.VisualInactive);
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
}, tableStyle, GUILayout.Width(col3), GUILayout.Height(cellHeight));
}
GUILayout.EndHorizontal();
{
GUILayoutExt.Box(padding, margin, () => {
var editor = WorldsViewerEditor.GetEditor(module);
if (editor != null) editor.OnDrawGUI();
}, tableStyle, GUILayout.ExpandWidth(true));
GUILayout.Space(2f);
}
}
});
});
var entitiesCount = storage.AliveCount;
GUILayoutExt.FoldOut(ref worldEditor.foldoutEntitiesStorage, $"Entities ({entitiesCount})", () => {
var cellHeight = 25f;
var padding = 2f;
var margin = 1f;
//var col1 = 80f;
var tableStyle = (GUIStyle)"Box";
var dataStyle = new GUIStyle(EditorStyles.label);
dataStyle.richText = true;
GUILayoutExt.Padding(4f, () => {
GUILayout.BeginHorizontal();
{
/*GUILayoutExt.Box(padding, margin, () => { GUILayoutExt.TableCaption("Caption", EditorStyles.miniBoldLabel); }, tableStyle,
GUILayout.Width(col1),
GUILayout.Height(cellHeight));*/
GUILayoutExt.Box(padding, margin, () => { GUILayoutExt.TableCaption("Data", EditorStyles.miniBoldLabel); }, tableStyle,
GUILayout.ExpandWidth(true), GUILayout.Height(cellHeight));
}
GUILayout.EndHorizontal();
GUILayout.BeginVertical();
{
GUILayout.BeginHorizontal();
{
GUILayoutExt.Box(
padding,
margin,
() => {
GUILayoutExt.TypeLabel(storage.GetType());
GUILayout.Label(storage.ToString(), dataStyle);
},
tableStyle,
GUILayout.ExpandWidth(true), GUILayout.Height(cellHeight));
}
GUILayout.EndHorizontal();
}
GUILayout.EndVertical();
GUILayout.BeginVertical();
{
GUILayoutExt.DrawHeader("Current");
foreach (var ent in storage.cache) {
GUILayoutExt.DataLabel(ent == Entity.Empty ? Entity.Empty.ToString() : ent.ToString());
}
GUILayoutExt.DrawHeader("Dead");
foreach (var ent in storage.dead) {
GUILayoutExt.DataLabel(ent.ToString());
}
GUILayoutExt.DrawHeader("Dead (Prepared)");
foreach (var ent in storage.deadPrepared) {
GUILayoutExt.DataLabel(ent.ToString());
}
GUILayoutExt.DrawHeader("Alive");
foreach (var ent in storage.alive) {
GUILayoutExt.DataLabel(ent.ToString());
}
}
GUILayout.EndVertical();
});
});
var filtersCount = 0;
var filtersArr = filters.GetData();
for (int f = 0; f < filtersArr.Length; ++f) {
if (filtersArr.arr[f] != null) ++filtersCount;
}
GUILayoutExt.FoldOut(ref worldEditor.foldoutFilters, $"Filters ({filtersCount})", () => {
GUILayoutExt.Padding(4f, () => {
GUILayout.BeginVertical();
for (int f = 0; f < filtersArr.Length; ++f) {
var filter = filtersArr.arr[f];
if (filter == null) continue;
WorldsViewerEditor.DrawFilter(filters, filter);
}
GUILayout.EndVertical();
});
});
});
if (worldEditor.foldout == true) {
selectedWorld = worldEditor;
// Fold in all others
foreach (var wEditor in this.worlds) {
if (wEditor != worldEditor) wEditor.foldout = false;
}
}
});
GUILayoutExt.Separator();
}
}
}
GUILayout.EndScrollView();
return selectedWorld;
}
public static void DrawFilter(FiltersStorage filters, FilterData filter) {
var cellHeight = 25f;
var padding = 2f;
var margin = 1f;
var tableStyle = (GUIStyle)"Box";
var dataStyle = new GUIStyle(EditorStyles.label);
dataStyle.richText = true;
GUILayout.BeginHorizontal();
{
GUILayoutExt.Box(
padding,
margin,
() => {
var names = filter.GetAllNames();
for (int i = 0; i < names.Length; ++i) {
GUILayout.BeginHorizontal();
{
if (GUILayout.Button("Open", EditorStyles.toolbarButton, GUILayout.Width(38f)) == true) {
var file = filter.GetEditorStackTraceFilename(i);
var line = filter.GetEditorStackTraceLineNumber(i);
AssetDatabase.OpenAsset(AssetDatabase.LoadAssetAtPath<MonoScript>(file), line);
}
GUILayoutExt.DataLabel(string.Format("<b>{0}</b>", names.arr[i]), GUILayout.ExpandWidth(false));
}
GUILayout.EndHorizontal();
}
var style = new GUIStyle(EditorStyles.miniLabel);
style.wordWrap = true;
GUILayout.Label(filter.ToEditorTypesString(), style);
GUILayout.Label("Objects count: " + filter.Count.ToString(), dataStyle);
var inUseCount = filter.GetArchetypeContains().Count + filter.GetArchetypeNotContains().Count;
var max = filters.GetAllFiltersArchetypeCount();
GUILayoutExt.ProgressBar(inUseCount, max, drawLabel: true);
},
tableStyle,
GUILayout.ExpandWidth(true), GUILayout.Height(cellHeight));
}
GUILayout.EndHorizontal();
}
private bool ToggleMethod(WorldEditor worldEditor, object instance, string methodName, ref bool state) {
var disabled = !worldEditor.HasMethod(instance, methodName);
if (disabled == true) {
var boxStyle = GUIStyle.none;
//EditorGUI.BeginDisabledGroup(false);
if (GUILayout.Button(new GUIContent(EditorGUIUtility.IconContent("InspectorLock")), boxStyle) == true) {
this.ShowNotification(new GUIContent("Method " + methodName + " implementation is empty."));
}
//EditorGUI.EndDisabledGroup();
} else {
var newState = EditorGUILayout.Toggle(state, "ShurikenCheckMark", GUILayout.Width(10f));
if (state != newState) {
state = newState;
return true;
}
}
return false;
}
}
} | 43.242497 | 217 | 0.398004 | [
"MIT"
] | IgorAtorin/ecs-submodule | ECSEditor/WorldsViewerEditor.cs | 72,044 | C# |
using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Waf.InformationManager.EmailClient.Modules.Presentation")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Waf Information Manager")]
[assembly: Guid("5ebb24a2-43cc-4a9f-96a5-082f9e96636e")]
[assembly: CLSCompliant(true)] | 32.75 | 85 | 0.776081 | [
"MIT"
] | pskpatil/waf | src/System.Waf/Samples/InformationManager/EmailClient.Modules.Presentation/Properties/AssemblyInfo.cs | 395 | C# |
namespace JCUtility.Common
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
/// <summary>
/// Extension methods for <see cref="System.Collections.Generic.IEnumerable{T}"/>
/// </summary>
public static class EnumerableExtensions
{
/// <summary>
/// Performs an action on each value of the enumerable
/// </summary>
/// <typeparam name="T">Element type</typeparam>
/// <param name="enumerable">Sequence on which to perform action</param>
/// <param name="action">Action to perform on every item</param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when given null <paramref name="enumerable"/> or <paramref name="action"/>
/// </exception>
public static void ForEach<T>(this IEnumerable<T> enumerable, Action<T> action)
{
Ensure.Argument.NotNull(enumerable, "enumerable");
Ensure.Argument.NotNull(action, "action");
foreach (T value in enumerable)
{
action(value);
}
}
/// <summary>
/// Convenience method for retrieving a specific page of items within a collection
/// </summary>
/// <typeparam name="T">Type</typeparam>
/// <param name="source">Source</param>
/// <param name="pageIndex">The index of the page to get</param>
/// <param name="pageSize">The size of te pages</param>
/// <returns>Specific page of items within a collection</returns>
public static IEnumerable<T> GetPage<T>(this IEnumerable<T> source, int pageIndex, int pageSize)
{
Ensure.Argument.NotNull(source, "source");
Ensure.Argument.Is(pageIndex >= 0, "The page index cannot be negative.");
Ensure.Argument.Is(pageSize >= 0, "The page size must be greater than zero.");
return source.Skip(pageIndex * pageSize).Take(pageSize);
}
/// <summary>
/// Converts an enumerable into a readonly collection
/// </summary>
/// <typeparam name="T">Type</typeparam>
/// <param name="enumerable">Source</param>
/// <returns>Readonly collection of <paramref name="enumerable"/></returns>
public static IEnumerable<T> ToReadOnlyCollection<T>(this IEnumerable<T> enumerable)
{
return new ReadOnlyCollection<T>(enumerable.ToList());
}
/// <summary>
/// Validates that the <paramref name="enumerable"/> is not null and contains items.
/// </summary>
/// <typeparam name="T">Type</typeparam>
/// <param name="enumerable">Source</param>
/// <returns>true if the <paramref name="enumerable"/> is not null and contains items; otherwise, false</returns>
public static bool IsNotNullOrEmpty<T>(this IEnumerable<T> enumerable)
{
return enumerable != null && enumerable.Any();
}
}
}
| 41.465753 | 121 | 0.603238 | [
"MIT"
] | givemefish/JCUtility | JCUtility.Common/EnumerableExtensions.cs | 3,029 | C# |
//-----------------------------------------------------------------------
// <copyright file="ListFileDirectoryEntry.cs" company="Microsoft">
// Copyright 2013 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-----------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Storage.File.Protocol
{
using System;
/// <summary>
/// Represents a directory item that is returned in the XML response for a file listing operation.
/// </summary>
#if WINDOWS_RT
internal
#else
public
#endif
sealed class ListFileDirectoryEntry : IListFileEntry
{
/// <summary>
/// Initializes a new instance of the <see cref="ListFileDirectoryEntry"/> class.
/// </summary>
/// <param name="name">The name of the directory.</param>
/// <param name="uri">The Uri of the directory.</param>
/// <param name="properties">The directory's properties.</param>
internal ListFileDirectoryEntry(string name, Uri uri, FileDirectoryProperties properties)
{
this.Name = name;
this.Uri = uri;
this.Properties = properties;
}
/// <summary>
/// Gets the name of the directory item.
/// </summary>
/// <value>The name of the directory item.</value>
public string Name
{
get;
internal set;
}
/// <summary>
/// Gets the directory address.
/// </summary>
/// <value>The directory URL.</value>
public Uri Uri
{
get;
internal set;
}
/// <summary>
/// Gets the directory item's properties.
/// </summary>
/// <value>The directory item's properties.</value>
public FileDirectoryProperties Properties
{
get;
internal set;
}
}
}
| 32.723684 | 102 | 0.562927 | [
"Apache-2.0"
] | Hitcents/azure-storage-net | Lib/Common/File/Protocol/ListFileDirectoryEntry.cs | 2,489 | C# |
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;
namespace binance.dex.sdk.noderpc.endpoint
{
/*
Get number of unconfirmed transactions. Query Parameters
Parameter Type Default Required Description
limit int 30 false Maximum number of entries (max: 100)
Return Parameters
// List of mempool txs
type ResultUnconfirmedTxs struct {
N int
Txs []types.Tx
}
*/
/*
{
"jsonrpc": "2.0",
"id": "",
"result": {
"n_txs": "0",
"txs": null
}
}
*/
public class ResultNumUnconfirmedTxs : IEndpointResponse
{
[JsonProperty("n_txs")]
public string NTxs { get; set; }
[JsonExtensionData, JsonProperty("txs")]
public IDictionary<string, JToken> Txs { get; set; }
}
}
| 22.860465 | 67 | 0.540183 | [
"MIT"
] | AYCHEX/aex.cSDK | src/noderpc/endpoint/NumUnconfirmedTxs.cs | 985 | C# |
using UnityEditor;
using UnityEngine;
using XNode;
using XNodeEditor;
namespace Planilo.BT
{
/// <summary>Custom editor for BTBranchNode.</summary>
[CustomNodeEditor(typeof(BTBranchNode))]
public class BTBranchNodeEditor : BTNodeEditor
{
/// <summary>Reference to the branch node.</summary>
BTBranchNode _branch;
/// <summary>Draw node's body GUI.</summary>
public override void OnBodyGUI()
{
base.OnBodyGUI();
_branch = target as BTBranchNode;
// Show parent port only if node is not root.
if (!_branch.IsRoot)
{
GUILayout.BeginHorizontal();
NodePort port = _branch.GetInputPort("_parent");
NodeEditorGUILayout.PortField(port, GUILayout.Width(60));
GUILayout.EndHorizontal();
}
}
}
} | 26.294118 | 73 | 0.588367 | [
"MIT"
] | adambrownmpvr/planilo | BehaviorTree/Base/Editor/BTBranchNodeEditor.cs | 894 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Management.Automation;
using Microsoft.WindowsAzure.Commands.Common.Utilities;
namespace Microsoft.Azure.Commands.Resources.Models.ActiveDirectory
{
public class PSADObject
{
public string DisplayName { get; set; }
public Guid Id { get; set; }
public string Type { get; set; }
}
}
| 37.677419 | 87 | 0.613014 | [
"MIT"
] | DeepakRajendranMsft/azure-sdk-tools | src/ResourceManager/Resources/Commands.Resources/Models.ActiveDirectory/PSADObject.cs | 1,140 | C# |
using Newtonsoft.Json;
namespace Magicodes.Wx.PublicAccount.Sdk.Apis.User.Dtos
{
public class CreateTagApiResult : ApiResultBase
{
[JsonProperty("tag")]
public CreateTagResultInfo Tag { get; set; }
}
public class CreateTagResultInfo
{
/// <summary>
/// 标签id,由微信分配
/// </summary>
[JsonProperty("id")]
public int Id { get; set; }
/// <summary>
/// 标签名,UTF8编码
/// </summary>
[JsonProperty("name")]
public string Name { get; set; }
}
} | 22.2 | 55 | 0.545946 | [
"MIT"
] | CacoCode/Magicodes.Wx.Sdk | src/Magicodes.Wx.PublicAccount.Sdk/Apis/User/Dtos/CreateTagApiResult.cs | 585 | C# |
using Newtonsoft.Json;
using Xunit.Abstractions;
namespace Spinit.Expressions.UnitTests.Infrastructure
{
public class XunitSerializable : IXunitSerializable
{
private static readonly JsonSerializerSettings settings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All
};
public void Deserialize(IXunitSerializationInfo info)
{
JsonConvert.PopulateObject(info.GetValue<string>("json"), this, settings);
}
public void Serialize(IXunitSerializationInfo info)
{
info.AddValue("json", JsonConvert.SerializeObject(this, settings));
}
}
}
| 28.083333 | 92 | 0.673591 | [
"MIT"
] | Spinit-AB/Spinit.Expressions | src/Spinit.Expressions.UnitTests/Infrastructure/XunitSerializable.cs | 676 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
namespace Importer
{
class LeveeLookupDataTable
{
public void ProcessLeveeLookDataTable(DataTable dataTable)
{
LeveeLookupList theFuncList = GlobalVariables.mp_fdaStudy.GetLeveeLookupList();
//Process Each Record (Row) in _dataTable and create new Levee lookup function and Add
for (int irec = 0; irec < dataTable.Rows.Count; irec++)
{
LeveeLookup theFunc = new LeveeLookup();
for (int ifield = 0; ifield < dataTable.Columns.Count; ifield++)
{
//Console.Write($"{_dataTable.Columns[icol].ColumnName.PadRight(12)}");
string colName = dataTable.Columns[ifield].ColumnName;
if (colName == "ID_PLAN")
theFunc._IdPlan = (int)dataTable.Rows[irec][ifield];
else if (colName == "ID_YEAR")
theFunc._IdYear = (int)dataTable.Rows[irec][ifield];
else if (colName == "ID_STREAM")
theFunc._IdStream = (int)dataTable.Rows[irec][ifield];
else if (colName == "ID_IMPAREA")
theFunc._IdReach = (int)dataTable.Rows[irec][ifield];
else if (colName == "ID_LEVEE")
theFunc._IdDataFunc = (int)dataTable.Rows[irec][ifield];
}
theFuncList.Add(theFunc);
}
}
}
}
| 38.357143 | 98 | 0.55059 | [
"MIT"
] | HydrologicEngineeringCenter/HEC-FDA | Importer/Levee/LeveeLookupDataTable.cs | 1,613 | C# |
using Newtonsoft.Json;
namespace Frau.Models
{
public class StoreSettings
{
[JsonProperty("msaCountryCode")]
public string MsaCountryCode { get; set; }
[JsonProperty("id")]
public uint Id { get; set; }
}
} | 19.384615 | 50 | 0.603175 | [
"MIT"
] | mika-sandbox/dotnet-mixier-api-wrapper | Sources/Frau/Models/StoreSettings.cs | 254 | C# |
// <auto-generated>
// THIS (.cs) FILE IS GENERATED BY MPC(MessagePack-CSharp). DO NOT CHANGE IT.
// </auto-generated>
#pragma warning disable 618
#pragma warning disable 612
#pragma warning disable 414
#pragma warning disable 168
#pragma warning disable SA1200 // Using directives should be placed correctly
#pragma warning disable SA1312 // Variable names should begin with lower-case letter
#pragma warning disable SA1649 // File name should match first type name
namespace MessagePack.Resolvers
{
using System;
public class GeneratedResolver : global::MessagePack.IFormatterResolver
{
public static readonly global::MessagePack.IFormatterResolver Instance = new GeneratedResolver();
private GeneratedResolver()
{
}
public global::MessagePack.Formatters.IMessagePackFormatter<T> GetFormatter<T>()
{
return FormatterCache<T>.Formatter;
}
private static class FormatterCache<T>
{
internal static readonly global::MessagePack.Formatters.IMessagePackFormatter<T> Formatter;
static FormatterCache()
{
var f = GeneratedResolverGetFormatterHelper.GetFormatter(typeof(T));
if (f != null)
{
Formatter = (global::MessagePack.Formatters.IMessagePackFormatter<T>)f;
}
}
}
}
internal static class GeneratedResolverGetFormatterHelper
{
private static readonly global::System.Collections.Generic.Dictionary<Type, int> lookup;
static GeneratedResolverGetFormatterHelper()
{
lookup = new global::System.Collections.Generic.Dictionary<Type, int>(2)
{
{ typeof(global::ChatApp.Shared.MessagePackObjects.JoinRequest), 0 },
{ typeof(global::ChatApp.Shared.MessagePackObjects.MessageResponse), 1 },
};
}
internal static object GetFormatter(Type t)
{
int key;
if (!lookup.TryGetValue(t, out key))
{
return null;
}
switch (key)
{
case 0: return new MessagePack.Formatters.ChatApp.Shared.MessagePackObjects.JoinRequestFormatter();
case 1: return new MessagePack.Formatters.ChatApp.Shared.MessagePackObjects.MessageResponseFormatter();
default: return null;
}
}
}
}
#pragma warning restore 168
#pragma warning restore 414
#pragma warning restore 618
#pragma warning restore 612
#pragma warning restore SA1312 // Variable names should begin with lower-case letter
#pragma warning restore SA1200 // Using directives should be placed correctly
#pragma warning restore SA1649 // File name should match first type name
// <auto-generated>
// THIS (.cs) FILE IS GENERATED BY MPC(MessagePack-CSharp). DO NOT CHANGE IT.
// </auto-generated>
#pragma warning disable 618
#pragma warning disable 612
#pragma warning disable 414
#pragma warning disable 168
#pragma warning disable SA1129 // Do not use default value type constructor
#pragma warning disable SA1200 // Using directives should be placed correctly
#pragma warning disable SA1309 // Field names should not begin with underscore
#pragma warning disable SA1312 // Variable names should begin with lower-case letter
#pragma warning disable SA1403 // File may only contain a single namespace
#pragma warning disable SA1649 // File name should match first type name
namespace MessagePack.Formatters.ChatApp.Shared.MessagePackObjects
{
using System;
using System.Buffers;
using MessagePack;
public sealed class JoinRequestFormatter : global::MessagePack.Formatters.IMessagePackFormatter<global::ChatApp.Shared.MessagePackObjects.JoinRequest>
{
public void Serialize(ref MessagePackWriter writer, global::ChatApp.Shared.MessagePackObjects.JoinRequest value, global::MessagePack.MessagePackSerializerOptions options)
{
IFormatterResolver formatterResolver = options.Resolver;
writer.WriteArrayHeader(2);
formatterResolver.GetFormatterWithVerify<string>().Serialize(ref writer, value.RoomName, options);
formatterResolver.GetFormatterWithVerify<string>().Serialize(ref writer, value.UserName, options);
}
public global::ChatApp.Shared.MessagePackObjects.JoinRequest Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options)
{
if (reader.TryReadNil())
{
throw new InvalidOperationException("typecode is null, struct not supported");
}
options.Security.DepthStep(ref reader);
IFormatterResolver formatterResolver = options.Resolver;
var length = reader.ReadArrayHeader();
var __RoomName__ = default(string);
var __UserName__ = default(string);
for (int i = 0; i < length; i++)
{
var key = i;
switch (key)
{
case 0:
__RoomName__ = formatterResolver.GetFormatterWithVerify<string>().Deserialize(ref reader, options);
break;
case 1:
__UserName__ = formatterResolver.GetFormatterWithVerify<string>().Deserialize(ref reader, options);
break;
default:
reader.Skip();
break;
}
}
var ____result = new global::ChatApp.Shared.MessagePackObjects.JoinRequest();
____result.RoomName = __RoomName__;
____result.UserName = __UserName__;
reader.Depth--;
return ____result;
}
}
public sealed class MessageResponseFormatter : global::MessagePack.Formatters.IMessagePackFormatter<global::ChatApp.Shared.MessagePackObjects.MessageResponse>
{
public void Serialize(ref MessagePackWriter writer, global::ChatApp.Shared.MessagePackObjects.MessageResponse value, global::MessagePack.MessagePackSerializerOptions options)
{
IFormatterResolver formatterResolver = options.Resolver;
writer.WriteArrayHeader(2);
formatterResolver.GetFormatterWithVerify<string>().Serialize(ref writer, value.UserName, options);
formatterResolver.GetFormatterWithVerify<string>().Serialize(ref writer, value.Message, options);
}
public global::ChatApp.Shared.MessagePackObjects.MessageResponse Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options)
{
if (reader.TryReadNil())
{
throw new InvalidOperationException("typecode is null, struct not supported");
}
options.Security.DepthStep(ref reader);
IFormatterResolver formatterResolver = options.Resolver;
var length = reader.ReadArrayHeader();
var __UserName__ = default(string);
var __Message__ = default(string);
for (int i = 0; i < length; i++)
{
var key = i;
switch (key)
{
case 0:
__UserName__ = formatterResolver.GetFormatterWithVerify<string>().Deserialize(ref reader, options);
break;
case 1:
__Message__ = formatterResolver.GetFormatterWithVerify<string>().Deserialize(ref reader, options);
break;
default:
reader.Skip();
break;
}
}
var ____result = new global::ChatApp.Shared.MessagePackObjects.MessageResponse();
____result.UserName = __UserName__;
____result.Message = __Message__;
reader.Depth--;
return ____result;
}
}
}
#pragma warning restore 168
#pragma warning restore 414
#pragma warning restore 618
#pragma warning restore 612
#pragma warning restore SA1129 // Do not use default value type constructor
#pragma warning restore SA1200 // Using directives should be placed correctly
#pragma warning restore SA1309 // Field names should not begin with underscore
#pragma warning restore SA1312 // Variable names should begin with lower-case letter
#pragma warning restore SA1403 // File may only contain a single namespace
#pragma warning restore SA1649 // File name should match first type name
| 39.336283 | 183 | 0.629134 | [
"MIT"
] | BearPro/MagicOnion | samples/ChatApp/ChatApp.Unity/Assets/Scripts/Generated/MessagePack.Generated.cs | 8,890 | C# |
using System.Collections.Generic;
using Essensoft.AspNetCore.Payment.Alipay.Response;
namespace Essensoft.AspNetCore.Payment.Alipay.Request
{
/// <summary>
/// AOP API: koubei.craftsman.data.provider.modify
/// </summary>
public class KoubeiCraftsmanDataProviderModifyRequest : IAlipayRequest<KoubeiCraftsmanDataProviderModifyResponse>
{
/// <summary>
/// 修改手艺人信息接口
/// </summary>
public string BizContent { get; set; }
#region IAlipayRequest Members
private bool needEncrypt=false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AlipayObject bizModel;
public void SetNeedEncrypt(bool needEncrypt){
this.needEncrypt=needEncrypt;
}
public bool GetNeedEncrypt(){
return needEncrypt;
}
public void SetNotifyUrl(string notifyUrl){
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl(){
return notifyUrl;
}
public void SetReturnUrl(string returnUrl){
this.returnUrl = returnUrl;
}
public string GetReturnUrl(){
return returnUrl;
}
public void SetTerminalType(string terminalType){
this.terminalType=terminalType;
}
public string GetTerminalType(){
return terminalType;
}
public void SetTerminalInfo(string terminalInfo){
this.terminalInfo=terminalInfo;
}
public string GetTerminalInfo(){
return terminalInfo;
}
public void SetProdCode(string prodCode){
this.prodCode=prodCode;
}
public string GetProdCode(){
return prodCode;
}
public string GetApiName()
{
return "koubei.craftsman.data.provider.modify";
}
public void SetApiVersion(string apiVersion){
this.apiVersion=apiVersion;
}
public string GetApiVersion(){
return apiVersion;
}
public IDictionary<string, string> GetParameters()
{
var parameters = new AlipayDictionary
{
{ "biz_content", BizContent }
};
return parameters;
}
public AlipayObject GetBizModel()
{
return bizModel;
}
public void SetBizModel(AlipayObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 23.709091 | 117 | 0.601227 | [
"MIT"
] | Aosir/Payment | src/Essensoft.AspNetCore.Payment.Alipay/Request/KoubeiCraftsmanDataProviderModifyRequest.cs | 2,626 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Training.DotNetCore.DA;
namespace Training.DotNetCore.DA.Migrations
{
[DbContext(typeof(DotNetCoreTrainingContext))]
[Migration("20180619071415_CreateDbSchema")]
partial class CreateDbSchema
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.1.0-rtm-30799")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Training.DotNetCore.DA.Model.Attendee", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Name");
b.HasKey("Id");
b.ToTable("Attendees");
b.HasData(
new { Id = 1, Name = "Test attendee" },
new { Id = 2, Name = "Test attendee 2" }
);
});
modelBuilder.Entity("Training.DotNetCore.DA.Model.Trainer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Name");
b.HasKey("Id");
b.ToTable("Trainer");
b.HasData(
new { Id = 1, Name = "Test trainer" },
new { Id = 2, Name = "Test trainer 2" }
);
});
modelBuilder.Entity("Training.DotNetCore.DA.Model.Training", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Description");
b.Property<DateTime>("EndDate");
b.Property<string>("Name");
b.Property<DateTime>("StartDate");
b.Property<int>("TrainerId");
b.HasKey("Id");
b.HasIndex("TrainerId");
b.ToTable("Trainings");
b.HasData(
new { Id = 1, Description = "Description", EndDate = new DateTime(2018, 4, 8, 0, 0, 0, 0, DateTimeKind.Unspecified), Name = "Test training", StartDate = new DateTime(2018, 4, 7, 0, 0, 0, 0, DateTimeKind.Unspecified), TrainerId = 1 },
new { Id = 2, Description = "Description", EndDate = new DateTime(2018, 4, 8, 0, 0, 0, 0, DateTimeKind.Unspecified), Name = "Test training 2", StartDate = new DateTime(2018, 4, 7, 0, 0, 0, 0, DateTimeKind.Unspecified), TrainerId = 2 }
);
});
modelBuilder.Entity("Training.DotNetCore.DA.Model.TrainingAttendee", b =>
{
b.Property<int>("TrainingId");
b.Property<int>("AttendeeId");
b.HasKey("TrainingId", "AttendeeId");
b.HasIndex("AttendeeId");
b.ToTable("TrainingAttendee");
b.HasData(
new { TrainingId = 1, AttendeeId = 1 },
new { TrainingId = 1, AttendeeId = 2 }
);
});
modelBuilder.Entity("Training.DotNetCore.DA.Model.Training", b =>
{
b.HasOne("Training.DotNetCore.DA.Model.Trainer", "Trainer")
.WithMany("Trainings")
.HasForeignKey("TrainerId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Training.DotNetCore.DA.Model.TrainingAttendee", b =>
{
b.HasOne("Training.DotNetCore.DA.Model.Attendee", "Attendee")
.WithMany("TrainingAttendees")
.HasForeignKey("AttendeeId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Training.DotNetCore.DA.Model.Training", "Training")
.WithMany("TrainingAttendees")
.HasForeignKey("TrainingId")
.OnDelete(DeleteBehavior.Cascade);
});
#pragma warning restore 612, 618
}
}
}
| 40.084615 | 259 | 0.503166 | [
"MIT"
] | lukaszkepa/Training.DotNetCore | Training.DotNetCore.DA/Migrations/20180619071415_CreateDbSchema.Designer.cs | 5,213 | C# |
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace Xml2WinForms
{
public sealed class GroupBoxControlHolder : IControlHolder
{
private readonly TunableGroupBox _control;
public string Name { get; }
public Label Label => null;
public Control Control => _control;
public GroupBoxControlHolder(string name, TunableGroupBox control)
{
Name = name;
_control = control ?? throw new ArgumentNullException(nameof(control));
}
public IEnumerable<IControlHolder> CollectNamedControlHolders()
{
var result = new List<IControlHolder>();
if (null != Name)
result.Add(this);
foreach (var controlHolder in _control.ControlHolders)
{
if (null != controlHolder.Name)
result.Add(controlHolder);
var groupBoxControlHolder = controlHolder as GroupBoxControlHolder;
if (null != groupBoxControlHolder)
result.AddRange(groupBoxControlHolder.CollectNamedControlHolders());
}
return result;
}
public void ApplyValue(object value)
{
throw new NotSupportedException();
}
public void ApplyBehavior(IDictionary<string, IControlHolder> namedControlHolders)
{
if (null == namedControlHolders)
throw new ArgumentNullException(nameof(namedControlHolders));
foreach (var controlControlHolder in _control.ControlHolders)
{
controlControlHolder.ApplyBehavior(namedControlHolders);
}
}
public void InitControl()
{
foreach (var controlControlHolder in _control.ControlHolders)
{
controlControlHolder.InitControl();
}
}
public void SetErrorProvider(ErrorProvider errorProvider)
{
if (null == errorProvider)
throw new ArgumentNullException(nameof(errorProvider));
foreach (var controlControlHolder in _control.ControlHolders)
{
controlControlHolder.SetErrorProvider(errorProvider);
}
}
public IEnumerable<InspectionReport> Inspect(IDictionary<string, IControlHolder> namedControlHolders)
{
if (null == namedControlHolders)
throw new ArgumentNullException(nameof(namedControlHolders));
if (!Control.Enabled || !Control.Visible)
return new List<InspectionReport>();
var inspectionReports = new List<InspectionReport>();
foreach (var controlHolder in _control.ControlHolders)
{
inspectionReports.AddRange(controlHolder.Inspect(namedControlHolders));
}
return inspectionReports;
}
public object ObtainValue()
{
var value = new List<object>();
foreach (var controlHolder in _control.ControlHolders)
{
value.Add(controlHolder.ObtainValue());
}
return value;
}
public IEnumerable<object> SelectValues()
{
var values = new List<object>();
foreach (var controlHolder in _control.ControlHolders)
{
values.AddRange(controlHolder.SelectValues());
}
return values;
}
}
} | 29.330579 | 109 | 0.582418 | [
"MIT"
] | MarketKernel/webmoney-business-tools | Ext/Xml2WinForms/ControlHolders/GroupBoxControlHolder.cs | 3,551 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace TencentCloud.As.V20180419.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class DescribeAutoScalingActivitiesResponse : AbstractModel
{
/// <summary>
/// 符合条件的伸缩活动数量。
/// </summary>
[JsonProperty("TotalCount")]
public ulong? TotalCount{ get; set; }
/// <summary>
/// 符合条件的伸缩活动信息集合。
/// </summary>
[JsonProperty("ActivitySet")]
public Activity[] ActivitySet{ get; set; }
/// <summary>
/// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
/// </summary>
[JsonProperty("RequestId")]
public string RequestId{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
internal override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "TotalCount", this.TotalCount);
this.SetParamArrayObj(map, prefix + "ActivitySet.", this.ActivitySet);
this.SetParamSimple(map, prefix + "RequestId", this.RequestId);
}
}
}
| 31.431034 | 83 | 0.636314 | [
"Apache-2.0"
] | ImEdisonJiang/tencentcloud-sdk-dotnet | TencentCloud/As/V20180419/Models/DescribeAutoScalingActivitiesResponse.cs | 1,933 | C# |
using DotVVM.Framework.Configuration;
using DotVVM.Framework.Hosting;
using DotVVM.Framework.ResourceManagement;
using DotvvmAcademy.Web.Hosting;
using DotvvmAcademy.Web.Pages.Error;
using DotvvmAcademy.Web.Pages.Step;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.Extensions.DependencyInjection;
using System;
namespace DotvvmAcademy.Web
{
public class DotvvmStartup : IDotvvmStartup, IDotvvmServiceConfigurator
{
public const string EnglishCulture = "en";
public const string CzechCulture = "cs";
public const string RussianCulture = "ru";
public const string DefaultCulture = EnglishCulture;
public static string[] EnabledCultures = {
EnglishCulture,
CzechCulture,
//RussianCulture // TODO: Uncomment when the translations are ready
};
public void Configure(DotvvmConfiguration config, string applicationPath)
{
// cause god knows what sort of culture is set on the machine
config.DefaultCulture = EnglishCulture;
// in debug I want to see the exception pages rather that the unspecific error pages
if (!config.Debug)
{
var telemetryConfig = config.ServiceProvider.GetRequiredService<TelemetryConfiguration>();
config.Runtime.GlobalFilters.Add(new ErrorRedirectingFilter(telemetryConfig));
}
config.Markup.AddMarkupControl("cc",
"LanguageSwitch",
"Pages/LanguageSwitch.dotcontrol");
config.Markup.AddMarkupControl("cc",
"DiagnosticList",
"Pages/Step/DiagnosticList.dotcontrol");
config.Markup.AddMarkupControl("cc",
"FinishDialog",
"Pages/Step/FinishDialog.dotcontrol");
config.Markup.AddCodeControls("cc", typeof(MonacoEditor));
config.Markup.AddMarkupControl("cc",
"Nav",
"Controls/Nav/Nav.dotcontrol");
config.Markup.AddMarkupControl("cc",
"DotvvmSticker",
"Controls/Nav/DotvvmSticker.dotcontrol");
config.Markup.AddMarkupControl("cc",
"Icon",
"Controls/Icons/Icon.dotcontrol");
config.Markup.AddMarkupControl("cc",
"IconSet",
"Controls/Icons/IconSet.dotcontrol");
config.Markup.AddMarkupControl("cc",
"Footer",
"Controls/Footer/Footer.dotcontrol");
if (config.Debug)
{
config.RouteTable.Add(
routeName: "Test",
url: "test/{LessonMoniker}/{VariantMoniker}/{StepMoniker}",
virtualPath: "Pages/Test/Test.dothtml",
defaultValues: new
{
LessonMoniker = "010_concepts",
VariantMoniker = "en",
StepMoniker = "10_viewmodel"
});
}
config.RouteTable.Add(
routeName: "Default",
url: "{Language}",
virtualPath: "Pages/Default/default.dothtml",
defaultValues: new { Language = "en" },
presenterFactory: LocalizablePresenter.BasedOnParameter("Language"));
config.RouteTable.Add(
routeName: "Error",
url: "{Language}/error/{ErrorCode}",
virtualPath: "Pages/Error/Error.dothtml",
defaultValues: new { Language = "en", ErrorCode = 500 },
presenterFactory: LocalizablePresenter.BasedOnParameter("Language"));
config.RouteTable.Add(
routeName: "Step",
url: "{Language}/{Lesson}/{Step}",
virtualPath: "Pages/Step/step.dothtml",
defaultValues: new { Language = "en" },
presenterFactory: LocalizablePresenter.BasedOnParameter("Language"));
config.RouteTable.Add(
routeName: "EmbeddedView",
url: "embeddedView/{Language}/{Lesson}/{Step}",
presenterType: typeof(EmbeddedViewPresenter));
config.RouteTable.Add(
routeName: "Archive",
url: "archive/{Language}/{Lesson}/{Step}",
presenterType: typeof(ArchivePresenter));
config.Resources.Register(
name: "MonacoLoader",
resource: new ScriptResource(new FileResourceLocation("~/wwwroot/libs/monaco-editor/min/vs/loader.js")));
config.Resources.Register(
name: "AppJS",
resource: new ScriptResource(new FileResourceLocation("~/wwwroot/scripts/app.js"))
{
Dependencies = new[] { "MonacoLoader" }
});
config.Resources.Register(
name: "StyleCSS",
resource: new StylesheetResource(new FileResourceLocation("~/wwwroot/css/style.css")));
}
public void ConfigureServices(IDotvvmServiceCollection options)
{
options.AddDefaultTempStorages("temp");
}
}
}
| 41.952 | 121 | 0.569794 | [
"Apache-2.0"
] | riganti/dotvvm-samples-academy | src/DotvvmAcademy.Web/DotvvmStartup.cs | 5,246 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Multiverse.Controls
{
public delegate bool ImageGridDragFinished(bool cancelled, Point location, object arg);
public partial class ImageGrid : Panel
{
#region Member Variables
/// <summary>
/// Number of horizontal cells in the grid
/// </summary>
protected int widthCells = 0;
/// <summary>
/// Number of vertical cells in the grid
/// </summary>
protected int heightCells = 0;
/// <summary>
/// The size of each cell in pixels
/// </summary>
protected int cellSize = 32;
/// <summary>
/// Width of the border in pixels
/// </summary>
protected int cellBorderWidth = 3;
/// <summary>
/// computed value of cellSize + cellBorderWidth
/// </summary>
protected int cellIncr;
/// <summary>
/// whether to draw labels on cells.
/// </summary>
protected bool labelCells = true;
/// <summary>
/// The color of the border drawn around selected cells
/// </summary>
protected Color selectionBorderColor = Color.Black;
/// <summary>
/// The width of the border drawn around selected cells
/// </summary>
protected int selectionBorderWidth = 2;
/// <summary>
/// The brush to use when drawing an empty cell
/// </summary>
protected Brush emptyCellBrush = Brushes.Blue;
/// <summary>
/// This dictionary holds all the currently active cells.
/// </summary>
protected Dictionary<Point, ImageGridCell> cells;
/// <summary>
/// The cell coordinates of the cells that are currently visible.
/// </summary>
protected Rectangle visibleCoords;
/// <summary>
/// This dictionary keeps track of the currently selected cells.
/// Only keys are used. The values are ignored.
/// </summary>
protected Dictionary<Point, int> selectedCells;
protected Pen selectionPen;
// drag support
protected bool dragging = false;
protected Size dragSize;
protected Pen dragPen;
protected Color dragOutlineColor = Color.Black;
protected ImageGridDragFinished dragFinished;
protected object dragArg;
#endregion Member Variables
#region Events
/// <summary>
/// VisibleCellsChange event occurs whenever the visible cells change, which occurs
/// when the control is enabled, when the control is resized, or when it is scrolled.
/// </summary>
public event VisibleCellsChangeEvent VisibleCellsChange;
public event UserSelectionChangeEvent UserSelectionChange;
#endregion Events
public ImageGrid()
{
cellIncr = cellSize + cellBorderWidth;
this.DoubleBuffered = true;
AutoScroll = true;
InitializeComponent();
UpdateSize();
cells = new Dictionary<Point, ImageGridCell>();
selectedCells = new Dictionary<Point, int>();
UpdateSelectionPen();
// create drag pen
dragPen = new Pen(dragOutlineColor, selectionBorderWidth);
dragPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
}
public ImageGridCell GetCell(int x, int y)
{
Point key = new Point(x, y);
ImageGridCell cell;
cells.TryGetValue(key, out cell);
//if (cell == null)
//{
// cell = CreateCell(x, y);
//}
return cell;
}
public ImageGridCell CreateCell(int x, int y)
{
Point key = new Point(x, y);
ImageGridCell cell = new ImageGridCell(x, y);
cells.Add(key, cell);
return cell;
}
public void FreeCell(ImageGridCell cell)
{
cells.Remove(new Point(cell.X, cell.Y));
}
public void ClearCells()
{
cells.Clear();
Invalidate();
}
protected void UpdateSize()
{
int w = cellSize * widthCells + cellBorderWidth * (widthCells + 1);
int h = cellSize * heightCells + cellBorderWidth * (heightCells + 1);
AutoScrollMinSize = new Size(w, h);
UpdateVisibleCoords();
Invalidate();
}
protected void UpdateSelectionPen()
{
if (selectionPen != null)
{
selectionPen.Dispose();
}
selectionPen = new Pen(selectionBorderColor, selectionBorderWidth);
}
protected void PaintCell(Graphics g, int x, int y)
{
ImageGridCell cell;
Point cellCoord = new Point(x,y);
bool gotCell = cells.TryGetValue(cellCoord, out cell);
Rectangle r = new Rectangle(x * cellIncr + cellBorderWidth + AutoScrollPosition.X,
y * cellIncr + cellBorderWidth + AutoScrollPosition.Y, cellSize, cellSize);
Brush brush = emptyCellBrush;
string labelString;
ImageGridCellType type;
if ((cell == null) || (cell.Type == ImageGridCellType.None))
{
labelString = String.Format("{0}, {1}", x, y);
type = ImageGridCellType.None;
}
else
{
type = cell.Type;
labelString = cell.Label;
if (type == ImageGridCellType.Color)
{
brush = new SolidBrush(cell.Color);
}
}
if (type == ImageGridCellType.Image)
{
g.DrawImageUnscaled(cell.Image, r);
}
else
{
g.FillRectangle(brush, r);
}
if (labelCells)
{
StringFormat stringFormat = new StringFormat();
stringFormat.Alignment = StringAlignment.Center;
stringFormat.LineAlignment = StringAlignment.Center;
g.DrawString(labelString, this.Font, Brushes.White, r, stringFormat);
}
if (selectedCells.ContainsKey(cellCoord))
{
g.DrawRectangle(selectionPen, r);
}
if (dragging)
{
if ((x >= lastMouseCell.X) && (x < (lastMouseCell.X + dragSize.Width)) &&
(y >= lastMouseCell.Y) && (y < (lastMouseCell.Y + dragSize.Height)))
{
g.DrawRectangle(dragPen, r);
}
}
}
protected void PaintGrid(Graphics g, int cellX, int cellY, int w, int h)
{
int cellIncr = cellSize + cellBorderWidth;
int maxX = cellX + w;
int maxY = cellY + h;
if (maxX >= widthCells)
{
maxX = widthCells;
}
if (maxY >= heightCells)
{
maxY = heightCells;
}
for (int x = cellX; x < maxX; x++)
{
for (int y = cellY; y < maxY; y++)
{
PaintCell(g, x, y);
}
}
}
public void ClearSelection()
{
selectedCells.Clear();
Invalidate();
}
public void AddSelectedCell(int x, int y)
{
selectedCells.Add(new Point(x, y), 0);
Invalidate();
}
#region Properties
public int WidthCells
{
get
{
return widthCells;
}
set
{
widthCells = value;
UpdateSize();
}
}
public int HeightCells
{
get
{
return heightCells;
}
set
{
heightCells = value;
UpdateSize();
}
}
public int CellBorderWidth
{
get
{
return cellBorderWidth;
}
set
{
cellBorderWidth = value;
cellIncr = cellSize + cellBorderWidth;
UpdateSize();
}
}
public int CellSize
{
get
{
return cellSize;
}
set
{
cellSize = value;
cellIncr = cellSize + cellBorderWidth;
UpdateSize();
}
}
public bool LabelCells
{
get
{
return labelCells;
}
set
{
labelCells = value;
Invalidate();
}
}
public Rectangle VisibleCoords
{
get
{
return visibleCoords;
}
}
public int SelectionBorderWidth
{
get
{
return selectionBorderWidth;
}
set
{
selectionBorderWidth = value;
UpdateSelectionPen();
}
}
public Color SelectionBorderColor
{
get
{
return selectionBorderColor;
}
set
{
selectionBorderColor = value;
UpdateSelectionPen();
}
}
public List<Point> SelectedCells
{
get
{
return new List<Point>(selectedCells.Keys);
}
}
#endregion Properties
public void BeginDrag(Size dragSize, ImageGridDragFinished callback, object arg)
{
if (dragging)
{
throw new ArgumentException("already dragging");
}
dragFinished = callback;
this.dragSize = dragSize;
dragging = true;
dragArg = arg;
Invalidate();
}
protected Rectangle PixelToCellCoords(Rectangle pixCoords)
{
int px = pixCoords.X - AutoScrollPosition.X;
int py = pixCoords.Y - AutoScrollPosition.Y;
int x = px / cellIncr;
int y = py / cellIncr;
int x2 = (px + pixCoords.Width + cellBorderWidth) / cellIncr;
int y2 = (py + pixCoords.Height + cellBorderWidth) / cellIncr;
return new Rectangle(x, y, x2 - x + 1, y2 - y + 1);
}
protected override void OnPaint(PaintEventArgs pe)
{
if (Enabled)
{
Rectangle gridCoords = PixelToCellCoords(pe.ClipRectangle);
PaintGrid(pe.Graphics, gridCoords.X, gridCoords.Y, gridCoords.Width, gridCoords.Height);
}
// Calling the base class OnPaint
base.OnPaint(pe);
}
protected ImageGridCell lastToolTipCell = null;
protected Point lastMouseLoc;
protected Point lastMouseCell;
protected override void OnMouseMove(MouseEventArgs e)
{
// compute cell coord of event location
int gridX = e.Location.X - AutoScrollPosition.X;
int gridY = e.Location.Y - AutoScrollPosition.Y;
Point CellCoord = new Point(gridX / cellIncr, gridY / cellIncr);
if (dragging && (CellCoord != lastMouseCell))
{
// Might want to optimize
Invalidate();
}
// save mouse location
lastMouseLoc = e.Location;
lastMouseCell = CellCoord;
// get the cell
ImageGridCell cell;
cells.TryGetValue(CellCoord, out cell);
// hide or show the tooltip
if ((cell != null) && (cell.ToolTipText != null))
{
if (cell != lastToolTipCell)
{
Point pt = e.Location;
pt.Y += cellSize / 2;
toolTip.Show(cell.ToolTipText, this, pt);
lastToolTipCell = cell;
}
}
else
{
toolTip.Hide(base.FindForm());
}
base.OnMouseMove(e);
}
protected Point lastSelectedCell = Point.Empty;
protected override void OnMouseClick(MouseEventArgs e)
{
// get state of modifier keys
bool shift = (ModifierKeys == Keys.Shift);
bool ctrl = (ModifierKeys == Keys.Control);
// compute cell coordiate
int gridX = e.Location.X - AutoScrollPosition.X;
int gridY = e.Location.Y - AutoScrollPosition.Y;
Point cellCoord = new Point(gridX / cellIncr, gridY / cellIncr);
if (dragging)
{
bool cancelled;
cancelled = (e.Button == MouseButtons.Right);
bool finish = dragFinished(cancelled, cellCoord, dragArg);
if (finish)
{
dragging = false;
Invalidate();
}
}
else if (shift)
{ // handle shift-click
if (lastSelectedCell == Point.Empty)
{
lastSelectedCell = cellCoord;
}
// clear current selection
selectedCells.Clear();
// sort coordinates for selection rectangle
int x1, x2, y1, y2;
if (lastSelectedCell.X < cellCoord.X)
{
x1 = lastSelectedCell.X;
x2 = cellCoord.X;
}
else
{
x1 = cellCoord.X;
x2 = lastSelectedCell.X;
}
if (lastSelectedCell.Y < cellCoord.Y)
{
y1 = lastSelectedCell.Y;
y2 = cellCoord.Y;
}
else
{
y1 = cellCoord.Y;
y2 = lastSelectedCell.Y;
}
// add all cells in selection rectangle to current selection
for (int y = y1; y <= y2; y++)
{
for (int x = x1; x <= x2; x++)
{
selectedCells.Add(new Point(x, y), 0);
}
}
OnUserSelectionChange();
}
else if (ctrl)
{ // handle ctrl-click
// toggle cell
if (selectedCells.ContainsKey(cellCoord))
{
selectedCells.Remove(cellCoord);
}
else
{
selectedCells.Add(cellCoord, 0);
}
// save as last selected cell
lastSelectedCell = cellCoord;
OnUserSelectionChange();
}
else
{ // handle regular click
// reset selected cell
selectedCells.Clear();
selectedCells.Add(cellCoord, 0);
// save as last selected cell
lastSelectedCell = cellCoord;
OnUserSelectionChange();
}
Invalidate();
base.OnMouseClick(e);
}
protected virtual void OnUserSelectionChange()
{
UserSelectionChangeEvent handler = UserSelectionChange;
if (handler != null)
{
handler(this, new EventArgs());
}
}
protected virtual void OnVisibleCellsChange()
{
VisibleCellsChangeEvent handler = VisibleCellsChange;
if (handler != null)
{
VisibleCellsChangeEventArgs args = new VisibleCellsChangeEventArgs(this.VisibleCoords);
handler(this, args);
}
}
protected void UpdateVisibleCoords()
{
Rectangle newCoords = PixelToCellCoords(new Rectangle(0, 0, ClientRectangle.Width, ClientRectangle.Height));
if (visibleCoords != newCoords)
{
visibleCoords = newCoords;
OnVisibleCellsChange();
}
}
protected override void OnScroll(ScrollEventArgs se)
{
UpdateVisibleCoords();
base.OnScroll(se);
}
}
#region Event Arg Classes
public class VisibleCellsChangeEventArgs : EventArgs
{
protected Rectangle cellsVisible;
public VisibleCellsChangeEventArgs(Rectangle visibleRect)
{
cellsVisible = visibleRect;
}
public Rectangle CellsVisible
{
get
{
return cellsVisible;
}
}
}
#endregion Event Arg Classes
#region Event Delegates
public delegate void VisibleCellsChangeEvent(object sender, VisibleCellsChangeEventArgs args);
public delegate void UserSelectionChangeEvent(object sender, EventArgs args);
#endregion Event Delegates
}
| 27.085758 | 120 | 0.481031 | [
"MIT"
] | AustralianDisabilityLimited/MultiversePlatform | lib/ImageGrid/ImageGrid.cs | 17,687 | C# |
using System;
using System.Text;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
using SFA.DAS.WebTemplateSourceName.Web.Extensions;
namespace SFA.DAS.WebTemplateSourceName.Web.Helpers
{
public class FlagsUnorderedListTagHelper : TagHelper
{
[HtmlAttributeName("asp-for")]
public ModelExpression Property { get; set; }
[HtmlAttributeName("class")]
public string Class { get; set; }
[HtmlAttributeName("item-class")]
public string ItemClass { get; set; }
[ViewContext]
[HtmlAttributeNotBound]
public ViewContext ViewContext { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "";
var content = new StringBuilder();
content.Append(!string.IsNullOrWhiteSpace(Class) ? $"<ul class=\"{Class}\">" : $"<ul>");
var modelType = Nullable.GetUnderlyingType(Property.Metadata.ModelType) ?? Property.Model.GetType();
var zeroValue = Enum.Parse(modelType, "0");
var modelValue = Property.Model as Enum;
foreach (Enum enumValue in Enum.GetValues(modelType))
{
if (enumValue.Equals(zeroValue)) continue;
var isChecked = modelValue != null && modelValue.HasFlag(enumValue);
if (isChecked)
{
content.Append($"<li");
if (!string.IsNullOrWhiteSpace(ItemClass))
{
content.Append($" class=\"{ItemClass}\"");
}
content.Append(">");
content.Append($"{enumValue.GetDisplayName()}");
content.Append("</li>");
}
}
content.Append("</ul>");
output.PostContent.SetHtmlContent(content.ToString());
output.Attributes.Clear();
}
}
}
| 33.112903 | 112 | 0.571359 | [
"MIT"
] | SkillsFundingAgency/das-dotnet-templates | src/working/templates/Web/src/SFA.DAS.WebTemplateSourceName.Web/Helpers/FlagsUnorderedListTagHelper.cs | 2,055 | C# |
// <auto-generated />
using System;
using FrontDesk.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace FrontDesk.Infrastructure.Data.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20210330205816_DateTimeOffset")]
partial class DateTimeOffset
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("ProductVersion", "5.0.4")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("FrontDesk.Core.Aggregates.Appointment", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<int>("AppointmentTypeId")
.HasColumnType("int");
b.Property<int>("ClientId")
.HasColumnType("int");
b.Property<DateTimeOffset>("DateTimeConfirmed")
.HasColumnType("datetimeoffset");
b.Property<int>("DoctorId")
.HasColumnType("int");
b.Property<bool>("IsPotentiallyConflicting")
.HasColumnType("bit");
b.Property<int>("PatientId")
.HasColumnType("int");
b.Property<int>("RoomId")
.HasColumnType("int");
b.Property<Guid>("ScheduleId")
.HasColumnType("uniqueidentifier");
b.Property<string>("Title")
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.HasKey("Id");
b.HasIndex("ScheduleId");
b.ToTable("Appointments");
});
modelBuilder.Entity("FrontDesk.Core.Aggregates.AppointmentType", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Code")
.HasColumnType("nvarchar(max)");
b.Property<int>("Duration")
.HasColumnType("int");
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("AppointmentTypes");
});
modelBuilder.Entity("FrontDesk.Core.Aggregates.Client", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("EmailAddress")
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.Property<string>("FullName")
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.Property<int>("PreferredDoctorId")
.HasColumnType("int");
b.Property<string>("PreferredName")
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.Property<string>("Salutation")
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.HasKey("Id");
b.ToTable("Clients");
});
modelBuilder.Entity("FrontDesk.Core.Aggregates.Doctor", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Name")
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.HasKey("Id");
b.ToTable("Doctors");
});
modelBuilder.Entity("FrontDesk.Core.Aggregates.Patient", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("ClientId")
.HasColumnType("int");
b.Property<string>("Name")
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.Property<int?>("PreferredDoctorId")
.HasColumnType("int");
b.Property<string>("Sex")
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.HasKey("Id");
b.HasIndex("ClientId");
b.ToTable("Patients");
});
modelBuilder.Entity("FrontDesk.Core.Aggregates.Room", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Name")
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.HasKey("Id");
b.ToTable("Rooms");
});
modelBuilder.Entity("FrontDesk.Core.Aggregates.Schedule", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<int>("ClinicId")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Schedules");
});
modelBuilder.Entity("FrontDesk.Core.Aggregates.Appointment", b =>
{
b.HasOne("FrontDesk.Core.Aggregates.Schedule", null)
.WithMany("Appointments")
.HasForeignKey("ScheduleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.OwnsOne("PluralsightDdd.SharedKernel.DateTimeOffsetRange", "TimeRange", b1 =>
{
b1.Property<Guid>("AppointmentId")
.HasColumnType("uniqueidentifier");
b1.Property<DateTimeOffset>("End")
.HasColumnType("datetimeoffset")
.HasColumnName("TimeRange_End");
b1.Property<DateTimeOffset>("Start")
.HasColumnType("datetimeoffset")
.HasColumnName("TimeRange_Start");
b1.HasKey("AppointmentId");
b1.ToTable("Appointments");
b1.WithOwner()
.HasForeignKey("AppointmentId");
});
b.Navigation("TimeRange");
});
modelBuilder.Entity("FrontDesk.Core.Aggregates.Patient", b =>
{
b.HasOne("FrontDesk.Core.Aggregates.Client", null)
.WithMany("Patients")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.OwnsOne("FrontDesk.Core.ValueObjects.AnimalType", "AnimalType", b1 =>
{
b1.Property<int>("PatientId")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b1.Property<string>("Breed")
.HasMaxLength(50)
.HasColumnType("nvarchar(50)")
.HasColumnName("AnimalType_Breed");
b1.Property<string>("Species")
.HasMaxLength(50)
.HasColumnType("nvarchar(50)")
.HasColumnName("AnimalType_Species");
b1.HasKey("PatientId");
b1.ToTable("Patients");
b1.WithOwner()
.HasForeignKey("PatientId");
});
b.Navigation("AnimalType");
});
modelBuilder.Entity("FrontDesk.Core.Aggregates.Client", b =>
{
b.Navigation("Patients");
});
modelBuilder.Entity("FrontDesk.Core.Aggregates.Schedule", b =>
{
b.Navigation("Appointments");
});
#pragma warning restore 612, 618
}
}
}
| 37.238971 | 133 | 0.454931 | [
"MIT"
] | KunalChoudhary521/pluralsight-ddd-fundamentals | FrontDesk/src/FrontDesk.Infrastructure/Data/Migrations/20210330205816_DateTimeOffset.Designer.cs | 10,131 | C# |
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
namespace Pomelo.EntityFrameworkCore.MySql.IntegrationTests.Models
{
public static class PeopleMeta
{
public static void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<PersonKid>(entity =>
{
// index the Discriminator to prevent full table scan
entity.Property("Discriminator")
.HasMaxLength(63);
entity.HasIndex("Discriminator");
entity.HasOne(m => m.Teacher)
.WithMany(m => m.Students)
.HasForeignKey(m => m.TeacherId)
.HasPrincipalKey(m => m.Id)
.OnDelete(DeleteBehavior.Restrict);
});
}
}
public abstract class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int? TeacherId { get; set; }
public PersonFamily Family { get; set; }
}
public class PersonKid : Person
{
public int Grade { get; set; }
public PersonTeacher Teacher { get; set; }
}
public class PersonTeacher : Person
{
public ICollection<PersonKid> Students { get; set; }
}
public class PersonParent : Person
{
public string Occupation { get; set; }
public bool OnPta { get; set; }
}
public class PersonFamily
{
public int Id { get; set; }
public string LastName { get; set; }
public ICollection<Person> Members { get; set; }
}
}
| 19.80597 | 66 | 0.683497 | [
"MIT"
] | Artrilogic/Pomelo.EntityFrameworkCore.MySql | test/EFCore.MySql.IntegrationTests/Models/People.cs | 1,329 | C# |
// Developed by Softeq Development Corporation
// http://www.softeq.com
using System;
using NSubstitute;
using Softeq.XToolkit.WhiteLabel.Navigation;
using Softeq.XToolkit.WhiteLabel.Tests.Stubs;
using Xunit;
namespace Softeq.XToolkit.WhiteLabel.Tests.Navigation.DialogsServiceExtensionsTests
{
public class DialogsServiceExtensionsTests
{
[Fact]
public void For_WhenCalledOnNull_ThrowsCorrectException()
{
IDialogsService dialogsService = null;
Assert.Throws<ArgumentNullException>(() => dialogsService.For<DialogViewModelStub>());
}
[Fact]
public void For_WhenCalledOnNonNull_CreatesFluentNavigator()
{
var dialogsService = Substitute.For<IDialogsService>();
var fluentNavigator = dialogsService.For<DialogViewModelStub>();
Assert.NotNull(fluentNavigator);
}
}
}
| 27.515152 | 98 | 0.697137 | [
"MIT"
] | Softeq/XToolkit.WhiteLabel | Softeq.XToolkit.WhiteLabel.Tests/Navigation/DialogsServiceExtensionsTests/DialogsServiceExtensionsTests.cs | 910 | 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("VirtualizingUtils.Test.NetFW")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("VirtualizingUtils.Test.NetFW")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[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("0e84a0ce-be28-49c2-a9b6-dba8b2aa0a5f")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.486486 | 84 | 0.750702 | [
"MIT"
] | flavourous/VVStackPanel | VirtualizingUtils.Test.NetFW/Properties/AssemblyInfo.cs | 1,427 | C# |
using System;
namespace _02._10._Shopping
{
class Program
{
static void Main(string[] args)
{
double budget = double.Parse(Console.ReadLine());
int videoCardsNumber = int.Parse(Console.ReadLine());
int processorsNumber = int.Parse(Console.ReadLine());
int ramNumber = int.Parse(Console.ReadLine());
double videoCardsPrice = 250.0 * videoCardsNumber;
double processorPrice = videoCardsPrice * 0.35 * processorsNumber;
double ramPrice = videoCardsPrice * 0.10 * ramNumber;
double total = videoCardsPrice + processorPrice + ramPrice;
if (videoCardsNumber > processorsNumber)
{
total = total * 0.85;
}
else
{
total = total * 1.0;
}
if (budget >= total)
{
double difference = budget - total;
Console.WriteLine($"You have {difference:F2} leva left!");
}
else
{
double difference = total - budget;
Console.WriteLine($"Not enough money! You need {difference:F2} leva more!");
}
}
}
}
| 29.857143 | 92 | 0.515152 | [
"MIT"
] | GeorgiGradev/SoftUni | 01. Programming Basics/03.4. EXAM - Conditional Statements/02.10. Shopping/Program.cs | 1,256 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.InputSystem;
namespace MicroUniverse {
public class KaleidoPainter : MonoBehaviour {
// Inspector:
[Header("Ref")]
public GameObject outerMask;
public GameObject canvas;
public GameObject innerMask;
// outerMask -> canvas -> innerMask can be considered as a successful draw.
[Header("Process")]
public LayerMask useLayer;
[Header("Painter Settings")]
public Color penColor = Color.red;
public int penWidth = 3;
public LayerMask drawingLayers;
public float innerRadius; // in metrics
public float outerRadius; // in metrics
public bool resetCanvasOnPlay = true;
public bool resetCanvasOnDraw = true;
public Color canvasClearColor = new Color(0, 0, 0, 0); // By default, reset the canvas to be transparent
[Header("Kaleido Specifics")]
public int kaleidoParts = 5;
public bool mirror = true;
// Inspector END
public UnityEvent OnDrawFinished;
public UnityEvent OnDrawFailed;
public delegate void BrushFunc(Vector2 world_position);
// This is the function called when a left click happens
// Pass in your own custom one to change the brush type
// Set the default function in the Awake method
public BrushFunc CurrentBrush;
// MUST HAVE READ/WRITE enabled set in the file editor of Unity
Sprite drawableSprite;
Texture2D drawableTex;
Vector2 firstDragPosition;
Vector2 prevMousePosPS;
Color[] initColors;
Color32[] currColors;
// inputs:
Vector2 pointerPosPS;
bool pointerHeldDown = false;
bool failedTriggeredLastFrame = false;
// New input system handler:
public void OnPointerMove(InputAction.CallbackContext context) {
pointerPosPS = context.ReadValue<Vector2>();
}
public void OnPointerHeldDown(InputAction.CallbackContext context) {
pointerHeldDown = context.performed;
}
// New input system handler END:
public enum State {
Idle, InnerMask, Drawing, OuterMask
}
public State currState = State.Idle; // public for debug.
public Texture2D GetTexture() {
return drawableTex;
}
//////////////////////////////////////////////////////////////////////////////
// BRUSH TYPES. Implement your own here
// When you want to make your own type of brush effects,
// Copy, paste and rename this function.
// Go through each step
/*
public void BrushTemplate(Vector2 world_position) {
// 1. Change world position to pixel coordinates
Vector2 pixelPosition = WorldToPixelCoordinates(world_position);
// 2. Make sure our variable for pixel array is updated in this frame
cur_colors = drawableTex.GetPixels32();
////////////////////////////////////////////////////////////////
// FILL IN CODE BELOW HERE
// Do we care about the user left clicking and dragging?
// If you don't, simply set the below if statement to be:
//if (true)
// If you do care about dragging, use the below if/else structure
if (previous_drag_position == Vector2.zero) {
// THIS IS THE FIRST CLICK
// FILL IN WHATEVER YOU WANT TO DO HERE
// Maybe mark multiple pixels to colour?
MarkPixelsToColour(pixelPosition, penWidth, penColor);
} else {
// THE USER IS DRAGGING
// Should we do stuff between the previous mouse position and the current one?
ColourBetween(previous_drag_position, pixelPosition, penWidth, penColor);
}
////////////////////////////////////////////////////////////////
// 3. Actually apply the changes we marked earlier
// Done here to be more efficient
ApplyMarkedPixelChanges();
// 4. If dragging, update where we were previously
previous_drag_position = pixelPosition;
}
// Default brush type. Has width and colour.
// Pass in a point in WORLD coordinates
// Changes the surrounding pixels of the world_point to the static pen_colour
public void PenBrush(Vector2 pointWS) {
Vector2 pointPS = WorldToPixelCoordinates(pointWS);
currColors = drawableTex.GetPixels32();
if (prevMousePosPS == Vector2.zero) {
// If this is the first time we've ever dragged on this image, simply colour the pixels at our mouse position
if (resetCanvasOnDraw) {
ResetCanvas();
}
MarkPixelsToColour(pointPS, penWidth, penColor);
} else {
// Colour in a line from where we were on the last update call
ColourBetween(prevMousePosPS, pointPS, penWidth, penColor);
}
ApplyMarkedPixelChanges();
//Debug.Log("Dimensions: " + pixelWidth + "," + pixelHeight + ". Units to pixels: " + unitsToPixels + ". Pixel pos: " + pixel_pos);
prevMousePosPS = pointPS;
}
*/
// Used in MicroUnivese to draw kaleido pattern
public void KaleidoBrush(Vector2 pointWS) {
Vector2 pointPS = WorldToCanvasPixelCoordinates(pointWS);
Vector2 centerPS = WorldToCanvasPixelCoordinates(drawableSprite.bounds.center);
currColors = drawableTex.GetPixels32();
if (prevMousePosPS == Vector2.zero) {
// If this is the first time we've ever dragged on this image, simply colour the pixels at our mouse position
for (int i = 0; i < kaleidoParts; ++i) {
Vector2 rotatedPixel = GetRotatedPixel(pointPS, centerPS, 360f / kaleidoParts * i);
MarkPixelsToColour(rotatedPixel, penWidth, penColor);
firstDragPosition = pointPS;
}
} else {
// Colour in a line from where we were on the last update call
for (int i = 0; i < kaleidoParts; ++i) {
Vector2 lastRotatedPixel = GetRotatedPixel(prevMousePosPS, centerPS, 360f / kaleidoParts * i);
Vector2 rotatedPixel = GetRotatedPixel(pointPS, centerPS, 360f / kaleidoParts * i);
ColourBetween(lastRotatedPixel, rotatedPixel, penWidth, penColor);
if (mirror) {
Vector2 mirrorDir = (firstDragPosition - centerPS).normalized;
ColourBetween(lastRotatedPixel.Mirror(centerPS, mirrorDir), rotatedPixel.Mirror(centerPS, mirrorDir), penWidth, penColor);
}
}
}
ApplyMarkedPixelChanges();
//Debug.Log("Dimensions: " + pixelWidth + "," + pixelHeight + ". Units to pixels: " + unitsToPixels + ". Pixel pos: " + pixel_pos);
prevMousePosPS = pointPS;
}
//////////////////////////////////////////////////////////////////////////////
public Vector2 GetRotatedPixel(Vector2 originalPos, Vector2 centerPos, float rotateDegree) {
Vector2 dir = originalPos - centerPos;
dir = dir.Rotate(rotateDegree);
return dir + centerPos;
}
// This is where the magic happens.
// Detects when user is left clicking, which then call the appropriate function
void Update() {
bool shouldTriggerFailed = false;
if (pointerHeldDown) {
Ray ray = Camera.main.ScreenPointToRay(pointerPosPS);
RaycastHit2D hit = Physics2D.GetRayIntersection(ray, useLayer);
if (hit.transform != null) {
if (hit.transform.gameObject == innerMask) {
if (currState == State.Idle || currState == State.InnerMask) {
currState = State.InnerMask;
} else {
DrawingFailed();
}
} else if (hit.transform.gameObject == canvas) {
if (currState == State.InnerMask && resetCanvasOnDraw) {
ResetCanvas();
}
if (currState == State.InnerMask) {
Vector2 mousePosWS = hit.point;
Vector2 canvasPosWS = new Vector2(canvas.transform.position.x, canvas.transform.position.y);
Vector2 dir = (mousePosWS - canvasPosWS).normalized;
mousePosWS = dir * innerRadius; // to prevent seam
CurrentBrush(mousePosWS);
currState = State.Drawing;
} else if (currState == State.Drawing) {
Vector2 mousePosWS = hit.point;
CurrentBrush(mousePosWS);
} else {
shouldTriggerFailed = true;
}
} else if (hit.transform.gameObject == outerMask) {
if (currState == State.Drawing) {
Vector2 mousePosWS = hit.point;
Vector2 canvasPosWS = new Vector2(canvas.transform.position.x, canvas.transform.position.y);
Vector2 dir = (mousePosWS - canvasPosWS).normalized;
mousePosWS = dir * outerRadius; // to prevent seam
CurrentBrush(mousePosWS); // last point
currState = State.OuterMask;
} else if (currState == State.OuterMask) {
// Do nothing
} else {
shouldTriggerFailed = true;
}
}
} else {
if (currState != State.Idle) {
shouldTriggerFailed = true;
}
}
} else {
if (currState != State.Idle) {
if (currState == State.OuterMask) {
DrawingSuccess();
} else {
shouldTriggerFailed = true;
}
}
}
if (shouldTriggerFailed) {
if (!failedTriggeredLastFrame) {
DrawingFailed();
failedTriggeredLastFrame = true;
}
} else {
failedTriggeredLastFrame = false;
}
}
void DrawingFailed() {
currState = State.Idle;
print("Failed.");
OnDrawFailed.Invoke();
prevMousePosPS = Vector2.zero;
}
void DrawingSuccess() {
currState = State.Idle;
print("Done.");
OnDrawFinished.Invoke();
prevMousePosPS = Vector2.zero;
}
// Set the colour of pixels in a straight line from start_point all the way to end_point, to ensure everything inbetween is coloured
void ColourBetween(Vector2 start_point, Vector2 end_point, int width, Color color) {
// Get the distance from start to finish
float distance = Vector2.Distance(start_point, end_point);
Vector2 direction = (start_point - end_point).normalized;
Vector2 cur_position = start_point;
// Calculate how many times we should interpolate between start_point and end_point based on the amount of time that has passed since the last update
float lerp_steps = 1 / distance;
for (float lerp = 0; lerp <= 1; lerp += lerp_steps) {
cur_position = Vector2.Lerp(start_point, end_point, lerp);
MarkPixelsToColour(cur_position, width, color);
}
}
void MarkPixelsToColour(Vector2 pixel, int penThickness, Color color) {
// Figure out how many pixels we need to colour in each direction (x and y)
int center_x = (int)pixel.x;
int center_y = (int)pixel.y;
//int extra_radius = Mathf.Min(0, pen_thickness - 2);
// penThickness represents a SQUARE.
for (int x = center_x - penThickness; x <= center_x + penThickness; x++) {
// Check if the X wraps around the image, so we don't draw pixels on the other side of the image
if (x >= (int)drawableSprite.rect.width || x < 0)
continue;
for (int y = center_y - penThickness; y <= center_y + penThickness; y++) {
MarkPixelToChange(x, y, color);
}
}
}
void MarkPixelToChange(int x, int y, Color color) {
// Need to transform x and y coordinates to flat coordinates of array
int array_pos = y * (int)drawableSprite.rect.width + x;
// Check if this is a valid position
if (array_pos > currColors.Length || array_pos < 0)
return;
currColors[array_pos] = color;
}
void ApplyMarkedPixelChanges() {
drawableTex.SetPixels32(currColors);
drawableTex.Apply();
}
Vector2 WorldToCanvasPixelCoordinates(Vector2 world_position) {
// Change coordinates to local coordinates of this image
Vector3 local_pos = canvas.transform.InverseTransformPoint(world_position);
// Change these to coordinates of pixels
float pixelWidth = drawableSprite.rect.width;
float pixelHeight = drawableSprite.rect.height;
float unitsToPixels = pixelWidth / drawableSprite.bounds.size.x * canvas.transform.localScale.x;
// Need to center our coordinates
float centered_x = local_pos.x * unitsToPixels + pixelWidth / 2;
float centered_y = local_pos.y * unitsToPixels + pixelHeight / 2;
// Round current mouse position to nearest pixel
Vector2 pixel_pos = new Vector2(Mathf.RoundToInt(centered_x), Mathf.RoundToInt(centered_y));
return pixel_pos;
}
// Changes every pixel to be the reset colour
public void ResetCanvas() {
print("Reset");
// Initialize clean pixels to use
initColors = new Color[(int)drawableSprite.rect.width * (int)drawableSprite.rect.height];
for (int x = 0; x < initColors.Length; x++) {
initColors[x] = canvasClearColor;
}
drawableTex.SetPixels(initColors);
drawableTex.Apply();
}
void Start() {
Init();
}
public void Init() {
// DEFAULT BRUSH SET HERE
CurrentBrush = KaleidoBrush;
drawableSprite = canvas.GetComponent<SpriteRenderer>().sprite;
drawableTex = drawableSprite.texture;
// Should we reset our canvas image when we hit play in the editor?
if (resetCanvasOnPlay) {
ResetCanvas();
}
}
}
} | 39.742347 | 161 | 0.544515 | [
"Unlicense"
] | GavinKG/MicroUniverse | Assets/Scripts/KaleidoPainter.cs | 15,581 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RethinkDb
{
public enum Conflict
{
Error,
Replace,
Update
}
}
| 14.125 | 33 | 0.659292 | [
"Apache-2.0"
] | DotNetUz/rethinkdb-net | rethinkdb-net/Conflict.cs | 228 | 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 budgets-2016-10-20.normal.json service model.
*/
using System;
using Amazon.Runtime;
using Amazon.Util.Internal;
namespace Amazon.Budgets
{
/// <summary>
/// Configuration for accessing Amazon Budgets service
/// </summary>
public partial class AmazonBudgetsConfig : ClientConfig
{
private static readonly string UserAgentString =
InternalSDKUtils.BuildUserAgentString("3.3.101.50");
private string _userAgent = UserAgentString;
/// <summary>
/// Default constructor
/// </summary>
public AmazonBudgetsConfig()
{
this.AuthenticationServiceName = "budgets";
}
/// <summary>
/// The constant used to lookup in the region hash the endpoint.
/// </summary>
public override string RegionEndpointServiceName
{
get
{
return "budgets";
}
}
/// <summary>
/// Gets the ServiceVersion property.
/// </summary>
public override string ServiceVersion
{
get
{
return "2016-10-20";
}
}
/// <summary>
/// Gets the value of UserAgent property.
/// </summary>
public override string UserAgent
{
get
{
return _userAgent;
}
}
}
} | 26.0375 | 105 | 0.585694 | [
"Apache-2.0"
] | jiabiao/aws-sdk-net | sdk/src/Services/Budgets/Generated/AmazonBudgetsConfig.cs | 2,083 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace DbLogger.Extensions
{
internal static class StringExtensions
{
/// <summary>
/// Removes non alpha numeric characters.
/// </summary>D:\Repositories\DbLogger\DbLogger.Lib\Extensions\StringExtensions.cs
/// <param name="s">The s.</param>
/// <returns></returns>
public static string ExceptNonAlphaNumeric(this string s)
=> new Regex("[^a-zA-Z0-9 -]").Replace(s, string.Empty);
/// <summary>
/// Gets the string that appears after the first found string.
/// Returns null if none are found.
/// </summary>
/// <param name="s">The string to convert.</param>
/// <param name="searches">The searches.</param>
/// <returns></returns>
public static string AfterOrDefault(this string s, IEnumerable<string> searches)
{
if (s == null)
return null;
foreach (var search in searches)
{
var index = s.IndexOf(search);
if (index != -1)
return s.Substring(index + search.Length, s.Length - search.Length + index);
}
return null;
}
/// <summary>
/// Gets a value indicating whether the string starts with any of the specified valus.
/// </summary>
/// <param name="s">The string to check.</param>
/// <param name="search">The start string to check.</param>
/// <returns></returns>
public static bool StartsWithAny(this string s, IEnumerable<string> search)
=> search
.Any(x => s.StartsWith(x));
/// <summary>
/// Gets the string that appears after the first found string.
/// Returns null if none are found.
/// </summary>
/// <param name="s">The string to convert.</param>
/// <param name="searches">The searches.</param>
/// <returns></returns>
public static string AfterOrDefault(this string s, string search)
{
if (s == null)
return null;
var index = s.IndexOf(search);
if (index != -1)
return s.Substring(index + search.Length, s.Length - search.Length + index);
return null;
}
/// <summary>
/// Gets the string that appears after the first found string.
/// Returns null if none are found.
/// </summary>
/// <param name="s">The string to convert.</param>
/// <param name="searches">The searches.</param>
/// <returns></returns>
public static string BeforeOrDefault(this string s, string search)
{
if (s == null)
return null;
var index = s.IndexOf(search);
if (index != -1)
return s.Substring(0, index);
return null;
}
/// <summary>
/// Tries to convert the string to a DateTime.
/// </summary>
/// <param name="s">The string to convert.</param>
/// <returns></returns>
public static DateTime? AsDateTime(this string s)
=> DateTime.TryParse(s, out var value)
? value
: default(DateTime?);
/// <summary>
/// Tries to convert the string to an Integer.
/// </summary>
/// <param name="s">The string to convert.</param>
/// <returns></returns>
public static int? AsInteger(this string s)
=> int.TryParse(s, out var value)
? value
: default(int?);
/// <summary>
/// Splits the string into it's lines.
/// </summary>
/// <param name="s">The s.</param>
/// <returns></returns>
public static string[] SplitToLines(this string s)
=> s.Split(new string[] { "\r\n" }, StringSplitOptions.None);
/// <summary>
/// Splits the string into it's lines, removes empty lines.
/// </summary>
/// <param name="s">The s.</param>
/// <returns></returns>
public static string[] SplitToLinesExceptEmpty(this string s)
=> s.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
/// <summary>
/// Joins the lines with a NewLine separator.
/// </summary>
/// <param name="lines">The lines.</param>
/// <returns></returns>
public static string JoinLines(this IEnumerable<string> lines)
=> string.Join(Environment.NewLine, lines);
}
}
| 35.338346 | 97 | 0.537872 | [
"MIT"
] | sirphilliptubell/DbLogger | DbLogger.Lib/Extensions/StringExtensions.cs | 4,702 | C# |
using System;
using System.Collections.Generic;
namespace SimpleLibMessages.RabbitMQ
{
public interface ISubscriber : IDisposable
{
void Subscribe(Func<string, IDictionary<string, object>, bool> callback);
}
} | 23.1 | 81 | 0.731602 | [
"MIT"
] | ranierecosta/simple-lib-messages-rabbitmq | SimpleLibMessages.RabbitMQ/ISubscriber.cs | 233 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Dragon.Context.Exceptions
{
public class UserKeyAlreadyExistsForThisServiceException : Exception
{
}
}
| 17.833333 | 73 | 0.771028 | [
"MIT"
] | aduggleby/dragon | proj/CPR/src/Dragon.Context/Exceptions/UserKeyAlreadyExistsForThisServiceException.cs | 216 | C# |
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osuTK;
namespace Qsor.Game.Graphics.UserInterface.Overlays.Settings
{
public abstract class SettingsCategoryContainer : FillFlowContainer
{
public new abstract string Name { get; }
public abstract IconUsage Icon { get; }
public SettingsCategoryContainer()
{
Spacing = new Vector2(0, 25f);
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
}
}
} | 27.5 | 71 | 0.667273 | [
"MIT"
] | jmir1/Qsor | Qsor.Game/Graphics/UserInterface/Overlays/Settings/SettingsCategoryContainer.cs | 552 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
namespace TestWebAPI
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
/*
* As well, we�ve turned off the JWT claim type mapping
* to allow well-known claims (e.g. �sub� and �idp�) to flow through unmolested:
* JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
*/
/*
* Authentication with an additional AddIdentityServerJwt helper method that configures the app to validate JWT tokens produced by IdentityServer:
services.AddAuthentication()
.AddIdentityServerJwt();
*/
// accepts any access token issued by identity server
services
.AddAuthentication("JWTBearerToken") // custom scheme name
.AddJwtBearer("JWTBearerToken",
options =>
{
options.Authority = "https://localhost:5001";
//options.Audience = "api1";
options.RequireHttpsMetadata = false;
options.TokenValidationParameters =
new TokenValidationParameters
{
ValidateAudience = false
};
});
// adds an authorization policy to make sure the token is for scope 'api1'
services
.AddAuthorization(options =>
{
options
.AddPolicy("AuthorizeByApiScope",
policy =>
{
policy.RequireAuthenticatedUser();
policy.RequireClaim("scope", "api1");
});
options
.AddPolicy("UserSecure",
policy => policy.RequireClaim("userRole", "endUser"));
options
.AddPolicy("AdminSecure",
policy =>
policy.RequireClaim("userRole", "clientAdmin"));
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
/*
In some cases, the call to AddAuthentication is automatically made by other extension methods. For example, when using ASP.NET Core Identity, AddAuthentication is called internally.
Identity is enabled by calling UseAuthentication. UseAuthentication adds authentication middleware to the request pipeline.
*/
app.UseAuthentication();
app.UseAuthorization();
app
.UseEndpoints(endpoints =>
{
endpoints
.MapControllers()
// auth policy name
/*
* You can now enforce this policy at various levels, e.g.
* globally
* for all API endpoints
* for specific controllers/actions using [Authorize] attribute
* Typically you setup the policy for all API endpoints in the routing system:
*/
.RequireAuthorization("AuthorizeByApiScope");
});
}
}
}
| 37.965812 | 197 | 0.541873 | [
"MIT"
] | RahulParmarRP/IdentityAuthServer | TestWebAPI/Startup.cs | 4,452 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class setHeightToWidth : MonoBehaviour
{
// Start is called before the first frame update
RectTransform rect;
void Awake()
{
rect = GetComponent<RectTransform>();
}
private void Start()
{
rect.sizeDelta = Vector2.one * rect.rect.height;
rect.offsetMin = new Vector2(rect.offsetMin.x, 0);
rect.offsetMax = new Vector2(rect.offsetMax.x, 0);
}
// Update is called once per frame
void Update()
{
}
}
| 21.296296 | 58 | 0.634783 | [
"MIT"
] | AI3SW/CNY_ASR_Frontend | Assets/AICubePlugins/UnityQuickScripts/setHeightToWidth.cs | 577 | C# |
////////////////////////////////////////////////////////////////////////
// Copyright (c) 2011-2013 by Rob Jellinghaus. //
// Licensed under the Microsoft Public License (MS-PL). //
////////////////////////////////////////////////////////////////////////
using Holofunk.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using Un4seen.Bass;
using Un4seen.Bass.AddOn.Mix;
using Un4seen.Bass.Misc;
using Un4seen.BassAsio;
// This is in the Holofunk namespace rather than Holofunk.Bass, as the latter's Bass suffix
// collides with the Bass.NET's Bass namespace.
namespace Holofunk
{
/// <summary>A series of Samples, with functionality for creating and feeding BASS streams.</summary>
public abstract class Track<T>
{
/// <summary>list of samples</summary>
readonly List<Sample<T>> m_samples = new List<Sample<T>>();
/// <summary>total length of all samples (not timepoints!) appended with Append</summary>
long m_totalAppendedLengthSamples;
/// <summary>HolofunkBass we were created on</summary>
HolofunkBass m_holofunkBass;
/// <summary>ID of the track (also gets used as user data in track callback)</summary>
readonly int m_id;
/// <summary>SYNCPROC to push more data into this stream</summary>
readonly SYNCPROC m_syncProc;
/// <summary>The BassStream we are using (and reserving).</summary>
BassStream m_bassStream;
/// <summary>handle of the synchronizer attached to m_trackHStream</summary>
StreamHandle m_trackHSync;
/// <summary>Master clock, for time spam.</summary>
Clock m_clock;
/// <summary>Time at last sync.</summary>
Moment m_lastSyncTime;
/// <summary>The beat time at which we started recording.
/// This is needed later to get the proper phase.</summary>
int m_initialBeat;
/// <summary>How many timepoints should we skip when we first start playing?
/// This is simply so we can avoid running late by the amount that we
/// missed our target timepoint count.</summary>
int m_initialTimepointAdvance;
/// <summary>Peak level meter.</summary>
DSP_PeakLevelMeter m_plmTrack;
int m_levelL;
int m_levelR;
/// <summary>Index of sample last pushed to stream</summary>
int m_index;
/// <summary>Parameters of the track's effects</summary>
ParameterMap m_parameters;
/// <summary>Is the track muted?</summary>
bool m_isMuted;
/// <summary>Create a Track.</summary>
/// <param name="bass">The BASS helper object; for coordination on disposal.</param>
/// <param name="id">Unique ID of this track.</param>
/// <param name="clock">ASIO-driven clock.</param>
/// <param name="now">ASIO time.</param>
/// <param name="startingParameters">A starting set of parameters, which must have been already copied (unshared).</param>
public Track(HolofunkBass bass, int id, Clock clock, Moment now, ParameterMap startingParameters)
{
m_holofunkBass = bass;
m_id = id;
m_syncProc = new SYNCPROC(SyncProc);
m_clock = clock;
m_initialBeat = now.CompleteBeats;
m_parameters = AllEffects.CreateParameterMap();
m_parameters.ShareAll(startingParameters);
}
/// <summary>The number of discrete Sample<typeparam name="T"/> instances in this Track.</summary>
/// <remarks>This should really be named Sample<typeparamref name="T"/>Count -- this is not the
/// number of individual data points in this Track, but rather the number of disjoint
/// Sample<typeparamref name="T"/> instances in this Track.</remarks>
public int SampleCount { get { return m_samples.Count; } }
/// <summary>The number of data points (e.g. total number of <typeparam name="T"/>'s) in this Track.</summary>
/// <remarks>We maintain two fields for this, to avoid races between the ASIO thread (incrementing
/// m_totalAppendedLengthSamples) and the UI thread (possibly updating m_initiallyEmptyLengthSamples).</remarks>
public long TotalLengthSamples
{
get { return m_totalAppendedLengthSamples; }
}
/// <summary>On what beat (since the beginning of time) did we start being recorded?</summary>
public int InitialBeat
{
get { return m_initialBeat; }
}
/// <summary>Total number of recorded Timepoints in this Track.</summary>
public long TotalLengthTimepoints
{
get { return TotalLengthSamples / HolofunkBassAsio.InputChannelCount; }
}
/// <summary>Get the length of this Track as a Moment, enabling all kinds of useful conversions.</summary>
public Moment LengthAsMoment
{
get { return m_clock.Time(TotalLengthTimepoints); }
}
/// <summary>Get one of the Sample<typeparamref name="T"/>'s in this track, by index.</summary>
public Sample<T> this[int i] { get { return m_samples[i]; } }
/// <summary>The Parameters of this track.</summary>
public ParameterMap Parameters { get { return m_parameters; } }
/// <summary>Copy all of the given sample's data to the stream.</summary>
/// <remarks>The lengthSamples argument permits us to adjust (shorten) a sample's length while
/// pushing it. We use this for the clock drift adjustment, to keep the playback of
/// this Track perfectly in sync with the input ASIOPROC.</remarks>
/// <param name="sample">The sample to copy data from</param>
/// <param name="lengthSamples">The number of samples to push.</param>
/// <param name="last">Is this the last sample in the stream?</param>
protected abstract void PushSampleToStream(Sample<T> sample, int lengthSamples);
/// <summary>Append a sample that has been populated with new data for the track.</summary>
public void Append(Sample<T> sample)
{
if (m_samples.Count == 0) {
m_samples.Add(sample);
Spam.Audio.WriteLine("Track #" + m_id + ": setting initial sample " + sample.AsString());
}
else if (m_samples[m_samples.Count - 1].AdjacentTo(sample)) {
// coalesce adjacent samples
m_samples[m_samples.Count - 1] = m_samples[m_samples.Count - 1].MergeWith(sample);
// Spam.Audio.WriteLine("Track #" + m_id + ": merged into tail sample " + m_samples[m_samples.Count - 1].AsString());
}
else {
Spam.Audio.WriteLine("Track #" + m_id + ": completed tail sample " + m_samples[m_samples.Count - 1].AsString());
Spam.Audio.WriteLine("Track #" + m_id + ": appending next sample " + sample.AsString());
m_samples.Add(sample);
}
m_totalAppendedLengthSamples += sample.Length;
}
/// <summary>ASIO sync callback.</summary>
/// <remarks>[AsioThread]</remarks>
void SyncProc(int handle, int channel, int data, IntPtr user)
{
// push the next sample to the stream
if (data == 0) { // means "stalled"
Moment now = m_clock.Now;
Spam.Audio.WriteLine("Track #" + m_id + " SyncProc: now: " + m_clock.Now + "; ");
PushNextSampleToStream();
}
}
void PushNextSampleToStream()
{
HoloDebug.Assert(m_index >= 0);
HoloDebug.Assert(m_index < m_samples.Count);
Spam.Audio.WriteLine("pushing sample #" + m_index);
PushSampleToStream(
m_samples[m_index],
m_samples[m_index].Length); // - (m_loopLagLengthTimepoints * HolofunkBassAsio.InputChannelCount)); // let's see if this is still critical...
m_index++;
if (m_index >= m_samples.Count) {
m_index = 0;
}
}
/// <summary>If we want to skip some samples at the beginning, set this.</summary>
public int InitialTimepointAdvance
{
set { m_initialTimepointAdvance = value; }
}
/// <summary>Start playing this track.</summary>
/// <remarks>[MainThread] but we have seen no troubles from the cross-thread operations here --
/// the key point is that m_syncProc is ready to go as soon as the ChannelSetSync happens.</remarks>
public void StartPlaying(BassStreamPool pool, Moment now)
{
Spam.Audio.WriteLine("Starting playing; total track length is now " + m_totalAppendedLengthSamples);
m_bassStream = pool.Reserve();
m_bassStream.Effects.Apply(Parameters, now);
m_holofunkBass.AddStreamToMixer(StreamHandle);
m_trackHSync = (StreamHandle)BassMix.BASS_Mixer_ChannelSetSync(
(int)StreamHandle,
BASSSync.BASS_SYNC_MIXTIME | BASSSync.BASS_SYNC_END,
0, // ignored
m_syncProc,
new IntPtr(0));
// connect peak level meter to input push stream
m_plmTrack = new DSP_PeakLevelMeter((int)StreamHandle, 0);
m_plmTrack.Notification += new EventHandler(Plm_Track_Notification);
// we want to set the clock LATER in this case
m_lastSyncTime = m_clock.Now.EarlierByTimepoints(-m_initialTimepointAdvance);
// and push the first sample
Spam.Audio.WriteLine("Track #" + m_id + ": starting; ");
PushNextSampleToStream();
}
/// <summary>Effects use this property to invoke the appropriate channel attribute setting, etc.</summary>
internal StreamHandle StreamHandle { get { return m_bassStream.PushStream; } }
/// <summary>Set whether the track is muted or not.</summary>
/// <param name="vol"></param>
public void SetMuted(bool isMuted)
{
m_isMuted = isMuted;
// TODO: make this handle time properly in the muting; Moment.Start is pure hack here
Bass.BASS_ChannelSetAttribute(
(int)StreamHandle,
BASSAttribute.BASS_ATTRIB_VOL,
isMuted ? 0f : m_parameters[VolumeEffect.Volume].GetInterpolatedValue(Moment.Start));
}
void Plm_Track_Notification(object sender, EventArgs e)
{
if (m_plmTrack != null) {
m_levelL = m_plmTrack.LevelL;
m_levelR = m_plmTrack.LevelR;
}
}
public float LevelRatio
{
get { return m_holofunkBass.CalculateLevelRatio(m_levelL, m_levelR); }
}
/// <summary>Trim the given number of samples from the start.</summary>
/// <remarks>This really is samples, not timepoints.</remarks>
public void TrimFromStart(int lengthSamples)
{
Trim(lengthSamples, false);
}
/// <summary>Trim the given number of samples from the end.</summary>
/// <remarks>This really is samples, not timepoints.</remarks>
public void TrimFromEnd(int lengthSamples)
{
Trim(lengthSamples, true);
}
void Trim(int lengthSamples, bool fromEnd)
{
// <= is perfectly possible here
HoloDebug.Assert(lengthSamples <= TotalLengthSamples);
m_totalAppendedLengthSamples -= lengthSamples;
int index = fromEnd ? m_samples.Count - 1 : 0;
while (m_samples[index].Length <= lengthSamples) {
lengthSamples -= m_samples[index].Length;
m_samples.RemoveAt(index);
// have to update index because m_samples.Count changed
index = fromEnd ? m_samples.Count - 1 : 0;
}
if (lengthSamples == 0) {
return;
}
// trim last sample -- this really must be < here
HoloDebug.Assert(lengthSamples < m_samples[index].Length);
m_samples[index] = new Sample<T>(
m_samples[index].Chunk,
fromEnd ? m_samples[index].Index : m_samples[index].Index + lengthSamples,
m_samples[index].Length - lengthSamples);
}
/// <summary>Update all effects applied to this track.</summary>
/// <remarks>[MainThread]
///
/// This should arguably be on the ASIO thread, but it doesn't seem likely that we can afford
/// the ASIO speed hit.</remarks>
public void UpdateEffects(Moment now)
{
m_bassStream.Effects.Apply(Parameters, now);
}
public void ResetEffects(Moment now)
{
Parameters.ResetToDefault();
UpdateEffects(now);
}
public void Dispose(Moment now)
{
Parameters.ResetToDefault();
m_bassStream.Effects.Apply(Parameters, now);
m_holofunkBass.RemoveStreamFromMixer(StreamHandle);
m_holofunkBass.Free(m_bassStream);
}
}
public class FloatTrack : Track<float>
{
public FloatTrack(HolofunkBass bass, int id, Clock clock, Moment now, ParameterMap startingParameters)
: base(bass, id, clock, now, startingParameters)
{
}
protected unsafe override void PushSampleToStream(Sample<float> sample, int lengthSamples)
{
float[] samples = sample.Chunk.Storage;
// reset stream position so no longer ended.
// this is as per http://www.un4seen.com/forum/?topic=12965.msg90332#msg90332
Bass.BASS_ChannelSetPosition((int)StreamHandle, 0, BASSMode.BASS_POS_BYTES);
// per http://www.un4seen.com/forum/?topic=12912.msg89978#msg89978
fixed (float* p = &samples[sample.Index]) {
byte* b = (byte*)p;
// we ignore the return value from StreamPutData since it queues anything in excess,
// so we don't need to track any underflows
Bass.BASS_StreamPutData(
(int)StreamHandle,
new IntPtr(p),
(lengthSamples * sizeof(float)) | (int)BASSStreamProc.BASS_STREAMPROC_END);
}
}
}
}
| 40.459834 | 158 | 0.599343 | [
"MIT"
] | RobJellinghaus/Holofunk0 | sourceCode/holofunk/HoloFunk/HolofunkBass/Track.cs | 14,608 | C# |
namespace Zilon.Core.World
{
public enum SectorResourceType
{
Undefined,
Iron,
Stones,
Silver,
Gold,
Copper,
Aurihulk,
CherryBrushes,
WaterPuddles
}
} | 10.565217 | 34 | 0.489712 | [
"MIT"
] | kreghek/Zilon_Roguelike | Zilon.Core/Zilon.Core/World/SectorResourceType.cs | 245 | C# |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Dialogflow.Cx.V3Beta1.Snippets
{
using Google.Cloud.Dialogflow.Cx.V3Beta1;
public sealed partial class GeneratedExperimentsClientStandaloneSnippets
{
/// <summary>Snippet for GetExperiment</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public void GetExperimentRequestObject()
{
// Create client
ExperimentsClient experimentsClient = ExperimentsClient.Create();
// Initialize request argument(s)
GetExperimentRequest request = new GetExperimentRequest
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
};
// Make the request
Experiment response = experimentsClient.GetExperiment(request);
}
}
}
| 39.785714 | 165 | 0.682825 | [
"Apache-2.0"
] | googleapis/googleapis-gen | google/cloud/dialogflow/cx/v3beta1/google-cloud-dialogflow-cx-v3beta1-csharp/Google.Cloud.Dialogflow.Cx.V3Beta1.StandaloneSnippets/ExperimentsClient.GetExperimentRequestObjectSnippet.g.cs | 1,671 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Print_Part_Of_ASCII_Table
{
class Program
{
static void Main(string[] args)
{
int firstChar = int.Parse(Console.ReadLine());
int secondChar = int.Parse(Console.ReadLine());
for (int counter = firstChar; counter <= secondChar; counter++)
{
Console.Write((char)counter + " ");
}
}
}
}
| 22.782609 | 75 | 0.582061 | [
"MIT"
] | Koceto/SoftUni | Old Code/Programming Fundamentals/Data Types and Variables - Exercises/Print Part Of ASCII Table/Print Part Of ASCII Table/Program.cs | 526 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AdventOfCode.Solutions.Year2020.Day17.Models;
namespace AdventOfCode.Solutions.Year2020
{
class Day17Solution : ASolution
{
private const int CYCLES = 6;
private HashSet<(int X, int Y, int Z)> _pocketDimensionCubes;
private HashSet<(int X, int Y, int Z, int W)> _pocketDimensionHyperCubes;
public Day17Solution() : base(17, 2020, "")
{
//base.DebugInput = ".#.\n..#\n###";
ParseInput();
}
protected override string SolvePartOne()
{
HashSet<(int X, int Y, int Z)> temporaryPocketDimension = new HashSet<(int X, int Y, int Z)>();
for (var i = 0; i < CYCLES; i++)
{
temporaryPocketDimension.Clear();
var borders = GetCubeBorders();
for (var x = borders.X.Min; x <= borders.X.Max; x++)
{
for (var y = borders.Y.Min; y <= borders.Y.Max; y++)
{
for (var z = borders.Z.Min; z <= borders.Z.Max; z++)
{
var currentCube = (x, y, z);
var activeNeighbourCount = CountActiveNeighboursForCube(currentCube);
if (activeNeighbourCount == 3)
{
temporaryPocketDimension.Add(currentCube);
}
else if (activeNeighbourCount == 2 && _pocketDimensionCubes.Contains(currentCube))
{
temporaryPocketDimension.Add(currentCube);
}
}
}
}
_pocketDimensionCubes = new HashSet<(int X, int Y, int Z)>(temporaryPocketDimension);
}
return _pocketDimensionCubes.Count.ToString();
}
private int CountActiveNeighboursForCube((int X, int Y, int Z) cube)
{
var count = 0;
for (var x = -1; x <= 1; x++)
{
for (var y = -1; y <= 1; y++)
{
for (var z = -1; z <= 1; z++)
{
if (x == 0 && y == 0 && z == 0)
{
continue;
}
var cubeToCheck = (cube.X + x, cube.Y + y, cube.Z + z);
if (_pocketDimensionCubes.Contains(cubeToCheck))
{
count++;
}
}
}
}
return count;
}
private (MinMax X, MinMax Y, MinMax Z) GetCubeBorders()
{
MinMax x = new MinMax(), y = new MinMax(), z = new MinMax();
foreach (var cube in _pocketDimensionCubes)
{
UpdateMinMax(ref x, cube.X);
UpdateMinMax(ref y, cube.Y);
UpdateMinMax(ref z, cube.Z);
}
// Update the borders to add a +1
// This forces a check to extra cubes which may become active
x.Min--;
x.Max++;
y.Min--;
y.Max++;
z.Min--;
z.Max++;
return (x, y, z);
}
protected override string SolvePartTwo()
{
HashSet<(int X, int Y, int Z, int W)> temporaryPocketDimension = new HashSet<(int X, int Y, int Z, int W)>();
for (var i = 0; i < CYCLES; i++)
{
temporaryPocketDimension.Clear();
var borders = GetHyperCubeBorders();
for (var x = borders.X.Min; x <= borders.X.Max; x++)
{
for (var y = borders.Y.Min; y <= borders.Y.Max; y++)
{
for (var z = borders.Z.Min; z <= borders.Z.Max; z++)
{
for (var w = borders.W.Min; w <= borders.W.Max; w++)
{
var currentCube = (x, y, z, w);
var activeNeighbourCount = CountActiveNeighboursForHyperCube(currentCube);
if (activeNeighbourCount == 3)
{
temporaryPocketDimension.Add(currentCube);
}
else if (activeNeighbourCount == 2 && _pocketDimensionHyperCubes.Contains(currentCube))
{
temporaryPocketDimension.Add(currentCube);
}
}
}
}
}
_pocketDimensionHyperCubes = new HashSet<(int X, int Y, int Z, int W)>(temporaryPocketDimension);
}
return _pocketDimensionHyperCubes.Count.ToString();
}
private int CountActiveNeighboursForHyperCube((int X, int Y, int Z, int W) cube)
{
var count = 0;
for (var x = -1; x <= 1; x++)
{
for (var y = -1; y <= 1; y++)
{
for (var z = -1; z <= 1; z++)
{
for (var w = -1; w <= 1; w++)
{
if (x == 0 && y == 0 && z == 0 && w == 0)
{
continue;
}
var cubeToCheck = (cube.X + x, cube.Y + y, cube.Z + z, cube.W + w);
if (_pocketDimensionHyperCubes.Contains(cubeToCheck))
{
count++;
}
}
}
}
}
return count;
}
private (MinMax X, MinMax Y, MinMax Z, MinMax W) GetHyperCubeBorders()
{
MinMax x = new MinMax(), y = new MinMax(), z = new MinMax(), w = new MinMax();
foreach (var cube in _pocketDimensionHyperCubes)
{
UpdateMinMax(ref x, cube.X);
UpdateMinMax(ref y, cube.Y);
UpdateMinMax(ref z, cube.Z);
UpdateMinMax(ref w, cube.W);
}
// Update the borders to add a +1
// This forces a check to extra cubes which may become active
x.Min--;
x.Max++;
y.Min--;
y.Max++;
z.Min--;
z.Max++;
w.Min--;
w.Max++;
return (x, y, z, w);
}
private void UpdateMinMax(ref MinMax minMax, int value)
{
if(value < minMax.Min)
{
minMax.Min = value;
}
if(value > minMax.Max)
{
minMax.Max = value;
}
}
private void ParseInput()
{
_pocketDimensionCubes = base.Input.SplitByNewline()
.SelectMany((line, y) =>
line.Select((cube, x) => (X: x, Y: y, IsActive: cube == '#'))
)
.Where(cube => cube.IsActive)
.Select(cube => (cube.X, cube.Y, Z: 0))
.ToHashSet();
_pocketDimensionHyperCubes = _pocketDimensionCubes.Select(cube => (cube.X, cube.Y, cube.Z, 0)).ToHashSet();
}
}
}
| 36.15493 | 121 | 0.39813 | [
"MIT"
] | YBijen/advent-of-code-2020 | AdventOfCode/Solutions/Year2020/Day17/Solution.cs | 7,701 | C# |
namespace Geodan.Geomagine
{
public class ExtrudeAttribute
{
}
} | 12.833333 | 33 | 0.662338 | [
"MIT"
] | aiunderstand/JRC-EU-JiriDemo | Assets/Scripts/ShapeImporter/ExtrudeAttribute.cs | 79 | 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("ConsumeMessages")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ConsumeMessages")]
[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("9a9f74ea-f7b8-4755-8608-972c4d425cf5")]
// 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.783784 | 84 | 0.748927 | [
"MIT"
] | emrekenci/azure-servicebus-sample | ConsumeMessages/Properties/AssemblyInfo.cs | 1,401 | C# |
namespace CollectorHub.Web.Tests
{
using System;
using System.Linq;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using Xunit;
public class SeleniumTests : IClassFixture<SeleniumServerFactory<Startup>>, IDisposable
{
private readonly SeleniumServerFactory<Startup> server;
private readonly IWebDriver browser;
public SeleniumTests(SeleniumServerFactory<Startup> server)
{
this.server = server;
server.CreateClient();
var opts = new ChromeOptions();
opts.AddArguments("--headless");
opts.AcceptInsecureCertificates = true;
this.browser = new ChromeDriver(opts);
}
[Fact(Skip = "Example test. Disabled for CI.")]
public void FooterOfThePageContainsPrivacyLink()
{
this.browser.Navigate().GoToUrl(this.server.RootUri);
Assert.EndsWith(
"/Home/Privacy",
this.browser.FindElements(By.CssSelector("footer a")).First().GetAttribute("href"));
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
this.server?.Dispose();
this.browser?.Dispose();
}
}
}
}
| 27.843137 | 100 | 0.571831 | [
"MIT"
] | itIsEazy/CollectorHub | Tests/CollectorHub.Web.Tests/SeleniumTests.cs | 1,422 | C# |
using System;
class NumbersOneToN
{
static void Main()
{
Console.Write("Enter \"n\" = ");
int n = int.Parse(Console.ReadLine());
for (int i = 1; i <= n; i++)
{
Console.WriteLine(i);
}
}
} | 17 | 46 | 0.454902 | [
"MIT"
] | beBoss/SoftUni | SoftUni-CSharp/Console Input Output Homework/8. Numbers from 1 to n/NumbersOneToN.cs | 257 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.