content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using Solnet.Rpc.Utilities; using Solnet.Wallet; using Solnet.Wallet.Utilities; using System; using System.Collections.Generic; using System.IO; namespace Solnet.Rpc.Models { /// <summary> /// The message header. /// </summary> public class MessageHeader { #region Layout /// <summary> /// Represents the layout of the <see cref="MessageHeader"/> encoded values. /// </summary> internal static class Layout { /// <summary> /// The offset at which the byte that defines the number of required signatures begins. /// </summary> internal const int RequiredSignaturesOffset = 0; /// <summary> /// The offset at which the byte that defines the number of read-only signer accounts begins. /// </summary> internal const int ReadOnlySignedAccountsOffset = 1; /// <summary> /// The offset at which the byte that defines the number of read-only non-signer accounts begins. /// </summary> internal const int ReadOnlyUnsignedAccountsOffset = 2; /// <summary> /// The message header length. /// </summary> internal const int HeaderLength = 3; } #endregion Layout /// <summary> /// The number of required signatures. /// </summary> public byte RequiredSignatures { get; set; } /// <summary> /// The number of read-only signed accounts. /// </summary> public byte ReadOnlySignedAccounts { get; set; } /// <summary> /// The number of read-only non-signed accounts. /// </summary> public byte ReadOnlyUnsignedAccounts { get; set; } /// <summary> /// Convert the message header to byte array format. /// </summary> /// <returns>The byte array.</returns> internal byte[] ToBytes() { return new[] { RequiredSignatures, ReadOnlySignedAccounts, ReadOnlyUnsignedAccounts }; } } /// <summary> /// Represents the Message of a Solana <see cref="Transaction"/>. /// </summary> public class Message { /// <summary> /// The header of the <see cref="Message"/>. /// </summary> public MessageHeader Header { get; set; } /// <summary> /// The list of account <see cref="PublicKey"/>s present in the transaction. /// </summary> public IList<PublicKey> AccountKeys { get; set; } /// <summary> /// The list of <see cref="TransactionInstruction"/>s present in the transaction. /// </summary> public IList<CompiledInstruction> Instructions { get; set; } /// <summary> /// The recent block hash for the transaction. /// </summary> public string RecentBlockhash { get; set; } /// <summary> /// Check whether an account is writable. /// </summary> /// <param name="index">The index of the account in the account keys.</param> /// <returns>true if the account is writable, false otherwise.</returns> public bool IsAccountWritable(int index) => index < Header.RequiredSignatures - Header.ReadOnlySignedAccounts || (index >= Header.RequiredSignatures && index < AccountKeys.Count - Header.ReadOnlyUnsignedAccounts); /// <summary> /// Check whether an account is a signer. /// </summary> /// <param name="index">The index of the account in the account keys.</param> /// <returns>true if the account is an expected signer, false otherwise.</returns> public bool IsAccountSigner(int index) => index < Header.RequiredSignatures; /// <summary> /// Serialize the message into the wire format. /// </summary> /// <returns>A byte array corresponding to the serialized message.</returns> public byte[] Serialize() { byte[] accountAddressesLength = ShortVectorEncoding.EncodeLength(AccountKeys.Count); byte[] instructionsLength = ShortVectorEncoding.EncodeLength(Instructions.Count); int accountKeysBufferSize = AccountKeys.Count * 32; MemoryStream accountKeysBuffer = new(accountKeysBufferSize); foreach (PublicKey key in AccountKeys) { accountKeysBuffer.Write(key.KeyBytes); } int messageBufferSize = MessageHeader.Layout.HeaderLength + PublicKey.PublicKeyLength + accountAddressesLength.Length + +instructionsLength.Length + Instructions.Count + accountKeysBufferSize; MemoryStream buffer = new(messageBufferSize); buffer.Write(Header.ToBytes()); buffer.Write(accountAddressesLength); buffer.Write(accountKeysBuffer.ToArray()); buffer.Write(Encoders.Base58.DecodeData(RecentBlockhash)); buffer.Write(instructionsLength); foreach (CompiledInstruction compiledInstruction in Instructions) { buffer.WriteByte(compiledInstruction.ProgramIdIndex); buffer.Write(compiledInstruction.KeyIndicesCount); buffer.Write(compiledInstruction.KeyIndices); buffer.Write(compiledInstruction.DataLength); buffer.Write(compiledInstruction.Data); } return buffer.ToArray(); } /// <summary> /// Deserialize a compiled message into a Message object. /// </summary> /// <param name="data">The data to deserialize into the Message object.</param> /// <returns>The Message object instance.</returns> public static Message Deserialize(ReadOnlySpan<byte> data) { // Read message header byte numRequiredSignatures = data[MessageHeader.Layout.RequiredSignaturesOffset]; byte numReadOnlySignedAccounts = data[MessageHeader.Layout.ReadOnlySignedAccountsOffset]; byte numReadOnlyUnsignedAccounts = data[MessageHeader.Layout.ReadOnlyUnsignedAccountsOffset]; // Read account keys (int accountAddressLength, int accountAddressLengthEncodedLength) = ShortVectorEncoding.DecodeLength(data.Slice(MessageHeader.Layout.HeaderLength, ShortVectorEncoding.SpanLength)); List<PublicKey> accountKeys = new(accountAddressLength); for (int i = 0; i < accountAddressLength; i++) { ReadOnlySpan<byte> keyBytes = data.Slice( MessageHeader.Layout.HeaderLength + accountAddressLengthEncodedLength + i * PublicKey.PublicKeyLength, PublicKey.PublicKeyLength); accountKeys.Add(new PublicKey(keyBytes)); } // Read block hash string blockHash = Encoders.Base58.EncodeData(data.Slice( MessageHeader.Layout.HeaderLength + accountAddressLengthEncodedLength + accountAddressLength * PublicKey.PublicKeyLength, PublicKey.PublicKeyLength).ToArray()); // Read the number of instructions in the message (int instructionsLength, int instructionsLengthEncodedLength) = ShortVectorEncoding.DecodeLength( data.Slice( MessageHeader.Layout.HeaderLength + accountAddressLengthEncodedLength + (accountAddressLength * PublicKey.PublicKeyLength) + PublicKey.PublicKeyLength, ShortVectorEncoding.SpanLength)); List<CompiledInstruction> instructions = new(instructionsLength); int instructionsOffset = MessageHeader.Layout.HeaderLength + accountAddressLengthEncodedLength + (accountAddressLength * PublicKey.PublicKeyLength) + PublicKey.PublicKeyLength + instructionsLengthEncodedLength; ReadOnlySpan<byte> instructionsData = data[instructionsOffset..]; // Read the instructions in the message for (int i = 0; i < instructionsLength; i++) { (CompiledInstruction compiledInstruction, int instructionLength) = CompiledInstruction.Deserialize(instructionsData); instructions.Add(compiledInstruction); instructionsData = instructionsData[instructionLength..]; } return new Message { Header = new MessageHeader { RequiredSignatures = numRequiredSignatures, ReadOnlySignedAccounts = numReadOnlySignedAccounts, ReadOnlyUnsignedAccounts = numReadOnlyUnsignedAccounts }, RecentBlockhash = blockHash, AccountKeys = accountKeys, Instructions = instructions, }; } /// <summary> /// Deserialize a compiled message encoded as base-64 into a Message object. /// </summary> /// <param name="data">The data to deserialize into the Message object.</param> /// <returns>The Transaction object.</returns> /// <exception cref="ArgumentNullException">Thrown when the given string is null.</exception> public static Message Deserialize(string data) { if (data == null) throw new ArgumentNullException(nameof(data)); byte[] decodedBytes; try { decodedBytes = Convert.FromBase64String(data); } catch (Exception ex) { throw new Exception("could not decode message data from base64", ex); } return Deserialize(decodedBytes); } } }
42.253061
121
0.575734
[ "MIT" ]
IgorBelinsky/Solnet
src/Solnet.Rpc/Models/Message.cs
10,352
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: Templates\CSharp\Model\EntityType.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; using Newtonsoft.Json; /// <summary> /// The type Secure Score. /// </summary> [JsonObject(MemberSerialization = MemberSerialization.OptIn)] public partial class SecureScore : Entity { ///<summary> /// The SecureScore constructor ///</summary> public SecureScore() { this.ODataType = "microsoft.graph.secureScore"; } /// <summary> /// Gets or sets active user count. /// Active user count of the given tenant. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "activeUserCount", Required = Newtonsoft.Json.Required.Default)] public Int32? ActiveUserCount { get; set; } /// <summary> /// Gets or sets average comparative scores. /// Average score by different scopes (for example, average by industry, average by seating) and control category (Identity, Data, Device, Apps, Infrastructure) within the scope. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "averageComparativeScores", Required = Newtonsoft.Json.Required.Default)] public IEnumerable<AverageComparativeScore> AverageComparativeScores { get; set; } /// <summary> /// Gets or sets azure tenant id. /// GUID string for tenant ID. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "azureTenantId", Required = Newtonsoft.Json.Required.Default)] public string AzureTenantId { get; set; } /// <summary> /// Gets or sets control scores. /// Contains tenant scores for a set of controls. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "controlScores", Required = Newtonsoft.Json.Required.Default)] public IEnumerable<ControlScore> ControlScores { get; set; } /// <summary> /// Gets or sets created date time. /// The date when the entity is created. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "createdDateTime", Required = Newtonsoft.Json.Required.Default)] public DateTimeOffset? CreatedDateTime { get; set; } /// <summary> /// Gets or sets current score. /// Tenant current attained score on specified date. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "currentScore", Required = Newtonsoft.Json.Required.Default)] public double? CurrentScore { get; set; } /// <summary> /// Gets or sets enabled services. /// Microsoft-provided services for the tenant (for example, Exchange online, Skype, Sharepoint). /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "enabledServices", Required = Newtonsoft.Json.Required.Default)] public IEnumerable<string> EnabledServices { get; set; } /// <summary> /// Gets or sets licensed user count. /// Licensed user count of the given tenant. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "licensedUserCount", Required = Newtonsoft.Json.Required.Default)] public Int32? LicensedUserCount { get; set; } /// <summary> /// Gets or sets max score. /// Tenant maximum possible score on specified date. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "maxScore", Required = Newtonsoft.Json.Required.Default)] public double? MaxScore { get; set; } /// <summary> /// Gets or sets vendor information. /// Complex type containing details about the security product/service vendor, provider, and subprovider (for example, vendor=Microsoft; provider=SecureScore). Required. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "vendorInformation", Required = Newtonsoft.Json.Required.Default)] public SecurityVendorInformation VendorInformation { get; set; } } }
46.235849
186
0.638033
[ "MIT" ]
OfficeGlobal/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Models/Generated/SecureScore.cs
4,901
C#
namespace Owin.Scim.Model.Groups { using System; using Configuration; public class MemberDefinition : ScimTypeDefinitionBuilder<Member> { public MemberDefinition(ScimServerConfiguration serverConfiguration) : base(serverConfiguration) { For(p => p.Value) .SetDescription("Identifier of the member of this group.") .SetMutability(Mutability.Immutable); For(p => p.Ref) .SetDescription("The URI corresponding to a SCIM resource that is a member of this group.") .SetMutability(Mutability.Immutable) .SetReferenceTypes(ScimConstants.ResourceTypes.User, ScimConstants.ResourceTypes.Group) .AddCanonicalizationRule((uri, definition) => Canonicalization.Canonicalization.EnforceScimUri(uri, definition, ServerConfiguration)); For(p => p.Type) .SetCanonicalValues(new [] { ScimConstants.ResourceTypes.User, ScimConstants.ResourceTypes.Group }, StringComparer.OrdinalIgnoreCase) .SetDescription("A label indicating the type of resource, e.g., 'User' or 'Group'.") .SetMutability(Mutability.Immutable) .AddCanonicalizationRule(type => char.ToUpper(type[0]) + type.Substring(1)); } } }
45.896552
150
0.649887
[ "MIT" ]
Mysonemo/Owin.Scim
source/Owin.Scim/Model/Groups/MemberDefinition.cs
1,331
C#
using BuildingGraph.Client.Introspection; public class ClientMapping { public ClientMapping(string mappingJSON) { var clienMapping = new BuildingGraphMapping(mappingJSON); } }
15.461538
65
0.726368
[ "MIT" ]
menome/BuildingGraph-Client-Revit
BuildingGraph.Integration.Dynamo/ClientMapping.cs
203
C#
using UnityEngine; using System.Collections; public class ManagesAI : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
12.875
40
0.679612
[ "MIT" ]
skoam/fumiko-ai
ManagesAI.cs
208
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Linq; using Microsoft.ApplicationInsights; using Microsoft.ApplicationInsights.Extensibility; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Bot.Builder; using Microsoft.Bot.Builder.AI.Luis; using Microsoft.Bot.Builder.BotFramework; using Microsoft.Bot.Builder.Integration; using Microsoft.Bot.Builder.Integration.AspNet.Core; using Microsoft.Bot.Configuration; using Microsoft.Bot.Connector.Authentication; using Microsoft.BotBuilderSamples.AppInsights; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace Microsoft.BotBuilderSamples { public class Startup { private ILoggerFactory _loggerFactory; private bool _isProduction = false; public Startup(IHostingEnvironment env) { _isProduction = env.IsProduction(); var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfiguration Configuration { get; } /// <summary> /// This method gets called by the runtime. Use this method to add services to the container. /// </summary> /// <param name="services">Specifies the contract for a <see cref="IServiceCollection"/> of service descriptors.</param> /// <seealso cref="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.1"/> public void ConfigureServices(IServiceCollection services) { var secretKey = Configuration.GetSection("botFileSecret")?.Value; var botFilePath = Configuration.GetSection("botFilePath")?.Value; // Loads .bot configuration file and adds a singleton that your Bot can access through dependency injection. var botConfig = BotConfiguration.Load(botFilePath ?? @".\<YOUR BOT CONFIGURATION>.bot", secretKey); services.AddSingleton(sp => botConfig ?? throw new InvalidOperationException($"The .bot configuration file could not be loaded. botFilePath: {botFilePath}")); // Retrieve current endpoint. var environment = _isProduction ? "production" : "development"; var service = botConfig.Services.FirstOrDefault(s => s.Type == "endpoint" && s.Name == environment); if (!(service is EndpointService endpointService)) { throw new InvalidOperationException($"The .bot file does not contain an endpoint with name '{environment}'."); } var connectedServices = InitBotServices(botConfig); services.AddSingleton(sp => connectedServices); services.AddBot<LuisBot>(options => { options.CredentialProvider = new SimpleCredentialProvider(endpointService.AppId, endpointService.AppPassword); // Add MyAppInsightsLoggerMiddleware (logs activity messages into Application Insights) var appInsightsLogger = new MyAppInsightsLoggerMiddleware(connectedServices.TelemetryClient.InstrumentationKey, logUserName: true, logOriginalMessage: true); options.Middleware.Add(appInsightsLogger); // Creates a logger for the application to use. ILogger logger = _loggerFactory.CreateLogger<LuisBot>(); // Catches any errors that occur during a conversation turn and logs them. options.OnTurnError = async (context, exception) => { logger.LogError($"Exception caught : {exception}"); await context.SendActivityAsync("Sorry, it looks like something went wrong."); }; // The Memory Storage used here is for local bot debugging only. When the bot // is restarted, everything stored in memory will be gone. IStorage dataStore = new MemoryStorage(); // For production bots use the Azure Blob or // Azure CosmosDB storage providers. For the Azure // based storage providers, add the Microsoft.Bot.Builder.Azure // Nuget package to your solution. That package is found at: // https://www.nuget.org/packages/Microsoft.Bot.Builder.Azure/ // Uncomment the following lines to use Azure Blob Storage // //Storage configuration name or ID from the .bot file. // const string StorageConfigurationId = "<STORAGE-NAME-OR-ID-FROM-BOT-FILE>"; // var blobConfig = botConfig.FindServiceByNameOrId(StorageConfigurationId); // if (!(blobConfig is BlobStorageService blobStorageConfig)) // { // throw new InvalidOperationException($"The .bot file does not contain an blob storage with name '{StorageConfigurationId}'."); // } // // Default container name. // const string DefaultBotContainer = "<DEFAULT-CONTAINER>"; // var storageContainer = string.IsNullOrWhiteSpace(blobStorageConfig.Container) ? DefaultBotContainer : blobStorageConfig.Container; // IStorage dataStore = new Microsoft.Bot.Builder.Azure.AzureBlobStorage(blobStorageConfig.ConnectionString, storageContainer); // Create Conversation State object. // The Conversation State object is where we persist anything at the conversation-scope. var conversationState = new ConversationState(dataStore); options.State.Add(conversationState); }); } /// <summary> /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. /// </summary> /// <param name="app">The application builder. This provides the mechanisms to configure the application request pipeline.</param> /// <param name="env">Provides information about the web hosting environment.</param> public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { _loggerFactory = loggerFactory; app.UseDefaultFiles() .UseStaticFiles() .UseBotFramework(); } /// <summary> /// Initialize the bot's references to external services. /// /// For example, Application Insights and LUIS services /// are created here. These external services are configured /// using the <see cref="BotConfiguration"/> class (based on the contents of your ".bot" file). /// </summary> /// <param name="config">The <see cref="BotConfiguration"/> object based on your ".bot" file.</param> /// <returns>A <see cref="BotServices"/> representing client objects to access external services the bot uses.</returns> /// <seealso cref="BotConfiguration"/> /// <seealso cref="LuisRecognizer"/> private static BotServices InitBotServices(BotConfiguration config) { TelemetryClient telemetryClient = null; var luisServices = new Dictionary<string, LuisRecognizer>(); foreach (var service in config.Services) { switch (service.Type) { case ServiceTypes.Luis: { var luis = (LuisService)service; if (luis == null) { throw new InvalidOperationException("The Luis service is not configured correctly in your '.bot' file."); } if (string.IsNullOrWhiteSpace(luis.AppId)) { throw new InvalidOperationException("The Luis Model Application Id ('appId') is required to run this sample. Please update your '.bot' file."); } if (string.IsNullOrWhiteSpace(luis.AuthoringKey)) { throw new InvalidOperationException("The Luis Authoring Key ('authoringKey') is required to run this sample. Please update your '.bot' file."); } if (string.IsNullOrWhiteSpace(luis.SubscriptionKey)) { throw new InvalidOperationException("The Subscription Key ('subscriptionKey') is required to run this sample. Please update your '.bot' file."); } if (string.IsNullOrWhiteSpace(luis.Region)) { throw new InvalidOperationException("The Region ('region') is required to run this sample. Please update your '.bot' file."); } var app = new LuisApplication(luis.AppId, luis.SubscriptionKey, luis.GetEndpoint()); var recognizer = new MyAppInsightLuisRecognizer(app); luisServices.Add(LuisBot.LuisKey, recognizer); break; } case ServiceTypes.AppInsights: { var appInsights = (AppInsightsService)service; if (appInsights == null) { throw new InvalidOperationException("The Application Insights is not configured correctly in your '.bot' file."); } if (string.IsNullOrWhiteSpace(appInsights.InstrumentationKey)) { throw new InvalidOperationException("The Application Insights Instrumentation Key ('instrumentationKey') is required to run this sample. Please update your '.bot' file."); } var telemetryConfig = new TelemetryConfiguration(appInsights.InstrumentationKey); telemetryClient = new TelemetryClient(telemetryConfig) { InstrumentationKey = appInsights.InstrumentationKey, }; break; } } } var connectedServices = new BotServices(telemetryClient, luisServices); return connectedServices; } } }
51.616822
204
0.595419
[ "MIT" ]
amr-elsehemy/BotBuilder-Samples
samples/csharp_dotnetcore/21.luis-with-appinsights/Startup.cs
11,048
C#
namespace MARC.HI.EHRS.CR.Core.Configuration { partial class ucServiceSettings { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.txtUserName = new System.Windows.Forms.TextBox(); this.txtPassword = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.cbxStartMode = new System.Windows.Forms.ComboBox(); this.rdoLocalService = new System.Windows.Forms.RadioButton(); this.rdoAccount = new System.Windows.Forms.RadioButton(); this.label6 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // label1 // this.label1.BackColor = System.Drawing.SystemColors.ControlDarkDark; this.label1.Dock = System.Windows.Forms.DockStyle.Top; this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.label1.Location = new System.Drawing.Point(0, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(307, 20); this.label1.TabIndex = 25; this.label1.Text = "Service Credentials"; this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(32, 105); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(72, 13); this.label2.TabIndex = 26; this.label2.Text = "User Account"; // // txtUserName // this.txtUserName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtUserName.Enabled = false; this.txtUserName.Location = new System.Drawing.Point(110, 102); this.txtUserName.Name = "txtUserName"; this.txtUserName.Size = new System.Drawing.Size(184, 20); this.txtUserName.TabIndex = 3; // // txtPassword // this.txtPassword.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtPassword.Enabled = false; this.txtPassword.Location = new System.Drawing.Point(110, 128); this.txtPassword.Name = "txtPassword"; this.txtPassword.PasswordChar = '*'; this.txtPassword.Size = new System.Drawing.Size(184, 20); this.txtPassword.TabIndex = 4; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(32, 131); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(53, 13); this.label3.TabIndex = 28; this.label3.Text = "Password"; // // label4 // this.label4.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.label4.BackColor = System.Drawing.SystemColors.ControlDarkDark; this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label4.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.label4.Location = new System.Drawing.Point(0, 163); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(307, 20); this.label4.TabIndex = 30; this.label4.Text = "Service Instance"; this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(3, 198); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(71, 13); this.label5.TabIndex = 31; this.label5.Text = "Startup Mode"; // // cbxStartMode // this.cbxStartMode.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbxStartMode.FormattingEnabled = true; this.cbxStartMode.Items.AddRange(new object[] { "Automatic", "Manual", "Disabled"}); this.cbxStartMode.Location = new System.Drawing.Point(80, 195); this.cbxStartMode.Name = "cbxStartMode"; this.cbxStartMode.Size = new System.Drawing.Size(185, 21); this.cbxStartMode.TabIndex = 5; // // rdoLocalService // this.rdoLocalService.AutoSize = true; this.rdoLocalService.Checked = true; this.rdoLocalService.Location = new System.Drawing.Point(6, 27); this.rdoLocalService.Name = "rdoLocalService"; this.rdoLocalService.Size = new System.Drawing.Size(172, 17); this.rdoLocalService.TabIndex = 1; this.rdoLocalService.TabStop = true; this.rdoLocalService.Text = "Start as Local Service Account"; this.rdoLocalService.UseVisualStyleBackColor = true; this.rdoLocalService.CheckedChanged += new System.EventHandler(this.rdoLocalService_CheckedChanged); // // rdoAccount // this.rdoAccount.AutoSize = true; this.rdoAccount.Location = new System.Drawing.Point(6, 47); this.rdoAccount.Name = "rdoAccount"; this.rdoAccount.Size = new System.Drawing.Size(166, 17); this.rdoAccount.TabIndex = 2; this.rdoAccount.Text = "Use Windows User Credential"; this.rdoAccount.UseVisualStyleBackColor = true; this.rdoAccount.CheckedChanged += new System.EventHandler(this.rdoAccount_CheckedChanged); // // label6 // this.label6.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.label6.Location = new System.Drawing.Point(23, 67); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(271, 32); this.label6.TabIndex = 32; this.label6.Text = "This user must already have been granted \'Log On as a Service\' right"; // // ucServiceSettings // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.label6); this.Controls.Add(this.rdoAccount); this.Controls.Add(this.rdoLocalService); this.Controls.Add(this.cbxStartMode); this.Controls.Add(this.label5); this.Controls.Add(this.label4); this.Controls.Add(this.txtPassword); this.Controls.Add(this.label3); this.Controls.Add(this.txtUserName); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Name = "ucServiceSettings"; this.Size = new System.Drawing.Size(307, 237); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox txtUserName; private System.Windows.Forms.TextBox txtPassword; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label5; private System.Windows.Forms.ComboBox cbxStartMode; private System.Windows.Forms.RadioButton rdoLocalService; private System.Windows.Forms.RadioButton rdoAccount; private System.Windows.Forms.Label label6; } }
47.660099
165
0.595762
[ "Apache-2.0" ]
MohawkMEDIC/openiz
OpenIZ.Core/Configuration/UI/ucServiceSettings.designer.cs
9,677
C#
using Innovator.Client; using System; namespace Innovator.Client.Model { ///<summary>Class for the item type fr_RepType_Characteristic </summary> [ArasName("fr_RepType_Characteristic")] public class fr_RepType_Characteristic : Item, INullRelationship<fr_RepresentationType>, IRelationship<xPropertyDefinition> { protected fr_RepType_Characteristic() { } public fr_RepType_Characteristic(ElementFactory amlContext, params object[] content) : base(amlContext, content) { } static fr_RepType_Characteristic() { Innovator.Client.Item.AddNullItem<fr_RepType_Characteristic>(new fr_RepType_Characteristic { _attr = ElementAttributes.ReadOnly | ElementAttributes.Null }); } /// <summary>Retrieve the <c>behavior</c> property of the item</summary> [ArasName("behavior")] public IProperty_Text Behavior() { return this.Property("behavior"); } /// <summary>Retrieve the <c>sort_order</c> property of the item</summary> [ArasName("sort_order")] public IProperty_Number SortOrder() { return this.Property("sort_order"); } } }
40.333333
199
0.741965
[ "MIT" ]
GCAE/Innovator.Client
src/Innovator.Client/Aml/Model/fr_RepType_Characteristic.cs
1,089
C#
#nullable enable using System; using System.Collections.Generic; namespace DotVVM.Framework.Hosting { public class CustomResponsePropertiesManager { private readonly Dictionary<string, object> properties = new Dictionary<string, object>(); public bool PropertiesSerialized { get; internal set; } public IReadOnlyDictionary<string, object> Properties => properties; public void Add(string key, object value) { if (PropertiesSerialized) { throw new InvalidOperationException("Cannot add new custom property. The properties have already been serialized into the response."); } if (properties.ContainsKey(key)) { throw new InvalidOperationException($"Custom property {key} already exists."); } properties[key] = value; } } }
33.333333
150
0.637778
[ "Apache-2.0" ]
AMBULATUR/dotvvm
src/DotVVM.Framework/Hosting/CustomResponsePropertiesManager.cs
902
C#
// // DefaultAuthenticationModuleCas.cs // - CAS unit tests for System.Web.Security.DefaultAuthenticationModule // // Author: // Sebastien Pouliot <sebastien@ximian.com> // // Copyright (C) 2005 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using NUnit.Framework; using System; using System.Reflection; using System.Security; using System.Security.Permissions; using System.Web; using System.Web.Security; namespace MonoCasTests.System.Web.Security { [TestFixture] [Category ("CAS")] public class DefaultAuthenticationModuleCas : AspNetHostingMinimal { private HttpApplication app; private DefaultAuthenticationModule module; [TestFixtureSetUp] public void FixtureSetUp () { app = new HttpApplication (); module = new DefaultAuthenticationModule (); } [Test] [SecurityPermission (SecurityAction.Deny, UnmanagedCode = true)] [ExpectedException (typeof (SecurityException))] public void Constructor_Deny_UnmanagedCode () { new DefaultAuthenticationModule (); } [Test] [SecurityPermission (SecurityAction.PermitOnly, UnmanagedCode = true)] public void Constructor_PermitOnly_UnmanagedCode () { new DefaultAuthenticationModule (); } private void Authenticate (object sender, DefaultAuthenticationEventArgs e) { } [Test] [PermissionSet (SecurityAction.Deny, Unrestricted = true)] public void Module () { // only the ctor requires UnmanagedCode module.Init (app); module.Authenticate += new DefaultAuthenticationEventHandler (Authenticate); module.Authenticate -= new DefaultAuthenticationEventHandler (Authenticate); module.Dispose (); // but doesn't implement IDisposable } // LinkDemand [SecurityPermission (SecurityAction.Assert, UnmanagedCode = true)] public override object CreateControl (SecurityAction action, AspNetHostingPermissionLevel level) { return base.CreateControl (action, level); } public override Type Type { get { return typeof (DefaultAuthenticationModule); } } } }
31.336735
98
0.755454
[ "Apache-2.0" ]
121468615/mono
mcs/class/System.Web/Test/System.Web.Security/DefaultAuthenticationModuleCas.cs
3,071
C#
using Earth.Core; namespace Earth.Renderer { public abstract class VertexArray : Disposable { public virtual VertexBufferAttributes Attributes { get { return null; } } public virtual IndexBuffer IndexBuffer { get { return null; } set { } } public bool DisposeBuffers { get; set; } } }
18.714286
56
0.547074
[ "MIT" ]
Shakenbake158/Earth
Assets/Scripts/Renderer/VertexArray/VertexArray.cs
395
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; using System.Reflection; using System.Threading; using System.Threading.Tasks; namespace Hinode.Editors { /// <summary> /// /// </summary> public abstract class GameTheoryEditor<TGame, TNode> : ManualEditorBase where TGame : GameTheory where TNode : class, GameTheory.INode { /// <summary> /// /// </summary> /// <param name="fieldInfo"></param> /// <param name="style"></param> /// <param name="options"></param> /// <returns></returns> protected abstract bool DrawInspector(TGame target, FieldInfo fieldInfo = null); protected virtual bool DrawAdditiveParamters() { return false; } public delegate void OnTraverseSteppedDelegate(GameTheoryEditor<TGame, TNode> self, IReadOnlyList<TNode> results, int stackCount); public delegate void OnTraversedDelegate(GameTheoryEditor<TGame, TNode> self, IReadOnlyList<TNode> results); SmartDelegate<OnTraverseSteppedDelegate> _onTraverseStepped = new SmartDelegate<OnTraverseSteppedDelegate>(); public NotInvokableDelegate<OnTraverseSteppedDelegate> OnTraverseStepped { get => _onTraverseStepped; } SmartDelegate<OnTraversedDelegate> _onTraversed = new SmartDelegate<OnTraversedDelegate>(); public NotInvokableDelegate<OnTraversedDelegate> OnTraversed { get => _onTraversed; } public int TraversingDepth { get; set; } = 3; public int BufferNodeCount { get; set; } = 5; public Vector2Int TraversingDepthRange { get; set; } = new Vector2Int(1, 10); public Vector2Int BufferNodeCountRange { get; set; } = new Vector2Int(5, 100); CancellationTokenSource _traverseTaskCancellationTokenSrc; Task _traverseTask; public bool IsComplete { get; private set; } = true; public double TraversingTimer { get; private set; } public int TraversingStackCount { get; private set; } public int TraversedResultCount { get; private set; } public bool DoChanged { get; set; } public GameTheoryEditor(OwnerEditor owner) : base(owner, new GUIContent("GameTheory")) { } public GameTheoryEditor(OwnerEditor owner, GUIContent rootLabel) : base(owner, rootLabel) {} public bool Draw(TGame target, FieldInfo fieldInfo = null) { DoChanged = false; RootFoldout = EditorGUILayout.Foldout(RootFoldout, RootLabel); if (!RootFoldout) return false; using (var indent = new EditorGUI.IndentLevelScope()) { EditorGUILayout.DoubleField("Execute Time(s)", TraversingTimer, GUILayout.ExpandWidth(false)); EditorGUILayout.IntField("Results Count", TraversedResultCount, GUILayout.ExpandWidth(false)); EditorGUILayout.IntField("Stack Count", TraversingStackCount, GUILayout.ExpandWidth(false)); var newTraversingDepth = EditorGUILayout.IntSlider("TraversingDepth", TraversingDepth, TraversingDepthRange.x, TraversingDepthRange.y); var newBufferNodeCount = EditorGUILayout.IntSlider("Buffer Node Count", BufferNodeCount, BufferNodeCountRange.x, BufferNodeCountRange.y); DoChanged |= DrawAdditiveParamters(); if (IsComplete) { TraversingDepth = newTraversingDepth; BufferNodeCount = newBufferNodeCount; DoChanged |= DrawInspector(target, fieldInfo); if (GUILayout.Button("Start to Traverse Game")) { if (IsComplete) { StartTraverseWithMultiThread(); } } } else { EditorGUILayout.Space(); EditorGUILayout.Space(); EditorGUILayout.LabelField("Now Calculate Game..."); EditorGUILayout.Space(); EditorGUILayout.Space(); if (GUILayout.Button("Cancel Caluculation?")) { StopCalculate(); } } } return DoChanged; } abstract protected TGame CreateGameInstance(); abstract protected TNode CreateNodeInstance(); void Traverse() { if (!IsComplete) return; IsComplete = false; var checker = CreateGameInstance(); var timer = System.DateTime.Now; TraversedResultCount = 0; TraversingStackCount = 0; var startNode = CreateNodeInstance(); var results = checker.EvaluateUntilTerminal<TNode>(checker.CurrentNode as TNode, TraversingDepth, BufferNodeCount, OnStepped); var timer2 = System.DateTime.Now; var timespan = new System.TimeSpan(timer2.Ticks - timer.Ticks); TraversingTimer = timespan.TotalSeconds; _onTraversed.SafeDynamicInvoke(this, results, () => "Fail in Traverse()..."); IsComplete = true; Owner.RepaintOwner(); } void OnStepped(IReadOnlyList<TNode> results, int stackCount) { TraversedResultCount = results.Count; TraversingStackCount = stackCount; _onTraverseStepped.SafeDynamicInvoke(this, results, stackCount, () => "Fail in OnStepped..."); } void StartTraverseWithMultiThread() { if (!IsComplete) return; if (_traverseTask != null) { StopCalculate(); } _traverseTaskCancellationTokenSrc = new CancellationTokenSource(); _traverseTask = Task.Run(() => { Traverse(); if (_traverseTaskCancellationTokenSrc != null) { _traverseTaskCancellationTokenSrc.Dispose(); _traverseTaskCancellationTokenSrc = null; } if (_traverseTask != null) { _traverseTask = null; } }, _traverseTaskCancellationTokenSrc.Token); } public void StopCalculate() { if (_traverseTaskCancellationTokenSrc != null) { _traverseTaskCancellationTokenSrc.Cancel(); _traverseTaskCancellationTokenSrc.Dispose(); } _traverseTaskCancellationTokenSrc = null; _traverseTask = null; IsComplete = true; } } }
36.5
153
0.587863
[ "Apache-2.0" ]
tositeru/hinode
Editor/AI/GameTheoryEditor.cs
6,791
C#
using Alabo.Domains.Entities; using Alabo.Extensions; using Alabo.Framework.Core.WebApis.Filter; using Microsoft.AspNetCore.Mvc; using System; using System.ComponentModel.DataAnnotations; using ZKCloud.Open.ApiBase.Models; namespace Alabo.Framework.Core.WebApis.Controller { public abstract class ApiDeleteController<TEntity, TKey> : ApiByIdController<TEntity, TKey> where TEntity : class, IAggregateRoot<TEntity, TKey> { #region 动态删除 /// <summary> /// 动态删除,删除单条记录,因为安全部分实体不支持,如需支持请在程序代码中配置 /// </summary> [HttpDelete] [Display(Description = "删除单条记录")] [ApiAuth] public ApiResult QueryDelete([FromBody] TEntity entity) { var checkResult = RelationCheck(entity); if (!checkResult.Succeeded) { return ApiResult.Failure(checkResult.ToString()); } var find = BaseService.GetSingle(entity.Id); if (find == null) { return ApiResult.Failure($"删除的数据不存在,Id:{entity.Id}"); } var result = BaseService.Delete(entity.Id); if (result) { return ApiResult.Success("删除成功"); } return ApiResult.Failure("删除失败"); } #endregion 动态删除 #region 动态删除 /// <summary> /// 动态删除,删除单条记录,因为安全部分实体不支持,如需支持请在程序代码中配置 /// </summary> [HttpDelete] [Display(Description = "删除单条记录")] [ApiAuth] public ApiResult QueryUserDelete([FromBody] TEntity entity) { var checkResult = RelationCheck(entity); if (!checkResult.Succeeded) { return ApiResult.Failure(checkResult.ToString()); } var find = BaseService.GetSingle(entity.Id); if (find == null) { return ApiResult.Failure($"删除的数据不存在,Id:{entity.Id}"); } var dynamicFind = (dynamic)find; if (Convert.ToInt64(dynamicFind.UserId) != AutoModel.BasicUser && AutoModel.BasicUser.Id > 0) { return ApiResult.Failure("您无权删除该数据"); } var result = BaseService.Delete(entity.Id); if (result) { return ApiResult.Success("删除成功"); } return ApiResult.Failure("删除失败"); } #endregion 动态删除 #region 批量删除 /// <summary> /// 批量删除,因为安全部分实体不支持,注意:body参数需要添加引号,"'1,2,3'"而不是"1,2,3" /// </summary> /// <param name="ids">Id标识列表</param> [HttpPost] [Display(Description = "删除单条记录")] [ApiAuth] public ApiResult BatchDelete([FromBody] string ids) { return ApiResult.Failure("改类型不支持api 接口删除"); } #endregion 批量删除 /// <summary> /// 删除前判断级联数据 /// </summary> /// <param name="entity"></param> /// <returns></returns> private ServiceResult RelationCheck(TEntity entity) { if (entity.Id.IsNullOrEmpty()) { return ServiceResult.FailedWithMessage($"{typeof(TEntity).Name}Id不能为空"); } var deleteAttribute = typeof(TEntity).FullName.GetAutoDeleteAttribute(); if (deleteAttribute == null) { return ServiceResult.FailedWithMessage($"{typeof(TEntity).Name}未配置删除特性,不能删除"); } if (deleteAttribute.IsAuto && deleteAttribute.EntityType == null) { return ServiceResult.Success; } if (deleteAttribute.EntityType == null) { return ServiceResult.FailedWithMessage($"{typeof(TEntity).Name}未配置删除级联,不能删除"); } if (deleteAttribute.RelationId.IsNullOrEmpty()) { return ServiceResult.FailedWithMessage($"{typeof(TEntity).Name}未配置RelationId,不能删除"); } var entityRelation = // var lambda= Lambda.Equal<>() Dynamics.DynamicService.ResolveMethod(deleteAttribute.EntityType.Name, "GetSingle", deleteAttribute.RelationId, entity.Id); if (!entityRelation.Item1.Succeeded) { return ServiceResult.FailedWithMessage(entityRelation.Item1.ToString()); } if (entityRelation.Item2 != null) { return ServiceResult.FailedWithMessage("有关联数据不能删除"); } return ServiceResult.Success; } } }
33.007407
107
0.56351
[ "MIT" ]
tongxin3267/alabo
src/01.framework/02-Alabo.Framework.Core/WebApis/Controller/ApiDeleteController.cs
4,964
C#
using System; using NtfsSharp.Contracts; namespace NtfsSharp.Drivers { public abstract class BaseDiskDriver : IDiskDriver, IDisposable { /// <summary> /// Guessed sectors per cluster /// </summary> /// <remarks>Since we don't know the size of a cluster yet (cause that info is in the boot sector) to do a read, we can only guess that so we can read the bootsector.</remarks> public virtual uint DefaultSectorsPerCluster => 8; /// <summary> /// Guessed bytes per sector /// </summary> /// <remarks>Since we don't know the size of a sector yet (cause that info is in the boot sector) to do a read, we can only guess that so we can read the bootsector.</remarks> public virtual ushort DefaultBytesPerSector => 512; /// <summary> /// Moves to a position inside the NTFS file system /// </summary> /// <param name="offset">Offset in the NTFS to move to</param> /// <param name="moveMethod">Whether the <paramref name="offset"/> is from the beginning, current position or end of the NTFS</param> /// <returns></returns> public abstract long Move(long offset, MoveMethod moveMethod = MoveMethod.Begin); public long MoveFromBeginning(long offset) { return Move(offset, MoveMethod.Begin); } public long MoveFromCurrent(long offset) { return Move(offset, MoveMethod.Current); } public long MoveFromEnd(long offset) { return Move(offset, MoveMethod.End); } /// <summary> /// Reads the number of bytes from inside the NTFS /// </summary> /// <param name="bytesToRead">Number of bytes to read</param> /// <remarks> /// Expect the <paramref name="bytesToRead"/> to be a multiple of the NTFS sector size (usually 512 bytes). /// The position the read (set by <seealso cref="Move"/>) occurs at the start of a sector in the NTFS /// </remarks> /// <returns>Bytes read as array</returns> public abstract byte[] ReadSectorBytes(uint bytesToRead); /// <summary> /// Allows for bytes to be read outside of the bounds of the sector size /// </summary> /// <param name="bytesToRead">Number of bytes to read</param> /// <remarks> /// Unlike <seealso cref="ReadSectorBytes"/>, the position and <paramref name="bytesToRead"/> may not be a multiple of the sector size. /// </remarks> /// <returns>Bytes read as array</returns> public abstract byte[] ReadInsideSectorBytes(uint bytesToRead); public enum MoveMethod : uint { Begin = 0, Current = 1, End = 2 } public abstract void Dispose(); } }
39.191781
184
0.601538
[ "Unlicense", "MIT" ]
little-apps/NtfsSharp
NtfsSharp.Drivers/BaseDiskDriver.cs
2,863
C#
using System; using System.Collections.Generic; using System.Text; namespace OpenTK.Platform.MacOS { using Graphics; class MacOSGraphicsMode : IGraphicsMode { #region IGraphicsMode Members public GraphicsMode SelectGraphicsMode(ColorFormat color, int depth, int stencil, int samples, ColorFormat accum, int buffers, bool stereo) { GraphicsMode gfx = new GraphicsMode((IntPtr)1, color, depth, stencil, samples, accum, buffers, stereo); System.Diagnostics.Debug.Print("Created dummy graphics mode."); return gfx; } #endregion } }
30.5
147
0.627422
[ "MIT" ]
PaintLab/PixelFarm.External
src/OpenTK.PlatformMini/Platform/MacOS/MacOSGraphicsMode.cs
671
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Models.Common { public class OrganizationSummary : Organization { public OrganizationSummary() { } public int QARolesCount { get; set; } public List<string> Subjects { get; set; } public CodeItemResult NaicsResults { get; set; } public CodeItemResult IndustryOtherResults { get; set; } public CodeItemResult OwnedByResults { get; set; } public CodeItemResult OfferedByResults { get; set; } public CodeItemResult AsmtsOwnedByResults { get; set; } public CodeItemResult LoppsOwnedByResults { get; set; } public CodeItemResult AccreditedByResults { get; set; } public CodeItemResult ApprovedByResults { get; set; } //Should be gone? //public CredentialConnectionsResult OwnedByResults { get; set; } //public CredentialConnectionsResult OfferedByResults { get; set; } public AgentRelationshipResult QualityAssurance { get; set; } = new AgentRelationshipResult(); public AgentRelationshipResult AgentAndRoles { get; set; } public int AssertionsTotal { get; set; } public List<string> ChildOrganizationsList { get; set; } = new List<string>(); } }
32.538462
102
0.721828
[ "Apache-2.0" ]
CredentialEngine/CredentialFinderEditor
Models/Common/OrganizationSummary.cs
1,271
C#
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT // 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.Threading.Tasks; namespace NakedObjects.Async { /// <summary> /// Interface representation of the AsyncService class (in NakedObjects.Core.dll) - /// for injection into domain code. /// </summary> public interface IAsyncService { /// <summary> /// Domain programmers must take care to ensure thread safety. /// The action passed in must not include any references to stateful objects (e.g. persistent domain objects). /// Typically the action should be on a (stateless) service; it may include primitive references /// such as object Ids that can be used within the called method to retrieve and action on specific /// object instances. /// </summary> /// <param name="toRun"></param> Task RunAsync(Action<IDomainObjectContainer> toRun); } }
56.074074
136
0.698811
[ "Apache-2.0" ]
NakedObjectsGroup/NakedObjectsFramework
Programming Model/NakedObjects/NakedObjects.Types/Async/IAsyncService.cs
1,516
C#
/***************************************************************************** Copyright 2018 The TensorFlow.NET Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ******************************************************************************/ using static Tensorflow.Binding; namespace Tensorflow { public class string_ops { /// <summary> /// Return substrings from `Tensor` of strings. /// </summary> /// <param name="input"></param> /// <param name="pos"></param> /// <param name="len"></param> /// <param name="name"></param> /// <param name="uint"></param> /// <returns></returns> public Tensor substr<T>(T input, int pos, int len, string @uint = "BYTE", string name = null) { if (tf.Context.executing_eagerly()) { var input_tensor = tf.constant(input); var results = tf.Runner.TFE_FastPathExecute(tf.Context, tf.Context.DeviceName, "Substr", name, null, input, pos, len, "unit", @uint); return results[0]; } var _op = tf.OpDefLib._apply_op_helper("Substr", name: name, args: new { input, pos, len, unit = @uint }); return _op.output; } } }
33.661017
94
0.509063
[ "Apache-2.0" ]
Aangbaeck/TensorFlow.NET
src/TensorFlowNET.Core/Operations/string_ops.cs
1,988
C#
using Domain.Entities; using Microsoft.EntityFrameworkCore; namespace Domain.Data { public partial class ExampleContext : DbContext { public virtual DbSet<Country> Countries { get; set; } public virtual DbSet<User> Users { get; set; } public virtual DbSet<UserLog> UserLogs { get; set; } public virtual DbSet<MailTemplate> MailTemplates { get; set; } public ExampleContext() { } public ExampleContext(DbContextOptions<ExampleContext> options) : base(options) { } } }
25
71
0.627826
[ "Apache-2.0" ]
AlexScigalszky/angular-dotnet-code
backend/src/Domain/Data/ExampleContext.cs
577
C#
#region Copyright /*Copyright (C) 2015 Wosad Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Wosad.Common.Entities; using Wosad.Common.Section.Interfaces; using Wosad.Steel.AISC.Interfaces; namespace Wosad.Steel.AISC.Interfaces { public interface IDesignElement { } }
25.416667
75
0.743169
[ "Apache-2.0" ]
Wosad/Wosad.Design
Wosad.Steel/AISC/Interfaces/IDesignElement.cs
915
C#
namespace NewsAPI.Dtos { public class CreateNewsDto { public string Title { get; set; } public string Description { get; set; } } }
19.875
47
0.603774
[ "MIT" ]
kira001/NewsAPI
Dtos/CreateNewsDto.cs
159
C#
/* SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to * this file be licensed under the Apache-2.0 license or a * compatible open source license. * * Modifications Copyright OpenSearch Contributors. See * GitHub history for details. * * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. 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 OpenSearch.Net.Utf8Json; namespace OpenSearch.Client { [JsonFormatter(typeof(MinimumShouldMatchFormatter))] public class MinimumShouldMatch : Union<int?, string> { public MinimumShouldMatch(int count) : base(count) { } public MinimumShouldMatch(string percentage) : base(percentage) { } public static MinimumShouldMatch Fixed(int count) => count; public static MinimumShouldMatch Percentage(double percentage) => $"{percentage}%"; public static implicit operator MinimumShouldMatch(string first) => new MinimumShouldMatch(first); public static implicit operator MinimumShouldMatch(int second) => new MinimumShouldMatch(second); public static implicit operator MinimumShouldMatch(double second) => Percentage(second); } }
36.5
100
0.772603
[ "Apache-2.0" ]
opensearch-project/opensearch-net
src/OpenSearch.Client/CommonOptions/MinimumShouldMatch/MinimumShouldMatch.cs
1,825
C#
using System; using System.Collections.Generic; using System.Linq; namespace NSubstitute.Core { public class CallActions : ICallActions { static readonly Action<CallInfo> EmptyAction = x => { }; readonly ICallInfoFactory _callInfoFactory; readonly List<CallAction> _actions = new List<CallAction>(); public CallActions(ICallInfoFactory callInfoFactory) { _callInfoFactory = callInfoFactory; } public void Add(ICallSpecification callSpecification, Action<CallInfo> action) { _actions.Add(new CallAction(callSpecification, action)); } public void Add(ICallSpecification callSpecification) { _actions.Add(new CallAction(callSpecification, EmptyAction)); } public void MoveActionsForSpecToNewSpec(ICallSpecification oldCallSpecification, ICallSpecification newCallSpecification) { foreach (var action in _actions.Where(x => x.IsFor(oldCallSpecification))) { action.UpdateCallSpecification(newCallSpecification); } } public void Clear() { _actions.Clear(); } public void InvokeMatchingActions(ICall call) { CallInfo callInfo = null; foreach (var action in _actions) { if (!action.IsSatisfiedBy(call)) continue; // Optimization. Initialize call lazily, as most of times there are no callbacks. if (callInfo == null) { callInfo = _callInfoFactory.Create(call); } action.Invoke(callInfo); } } class CallAction { public CallAction(ICallSpecification callSpecification, Action<CallInfo> action) { _callSpecification = callSpecification; _action = action; } private ICallSpecification _callSpecification; private readonly Action<CallInfo> _action; public bool IsSatisfiedBy(ICall call) { return _callSpecification.IsSatisfiedBy(call); } public void Invoke(CallInfo callInfo) { _action(callInfo); _callSpecification.InvokePerArgumentActions(callInfo); } public bool IsFor(ICallSpecification spec) { return _callSpecification == spec; } public void UpdateCallSpecification(ICallSpecification spec) { _callSpecification = spec; } } } }
32.725
129
0.595111
[ "BSD-3-Clause" ]
dtchepak/NSubstitute
src/NSubstitute/Core/CallActions.cs
2,620
C#
//====================================================================== // // Copyright © 2016 - 2020 NetInfo Technologies Ltd. // All rights reserved // guid1: 3d12c792-f5db-4907-9cc0-10317c76f4aa // CLR Version: 4.0.30319.42000 // Name: DateItem // Computer: DESKTOP-5OJRDKD // Organization: NetInfo // Namespace: ShiShiCai.Models // File Name: DateItem // // Created by Charley at 2019/8/23 9:29:51 // http://www.netinfo.com // //====================================================================== using System.ComponentModel; namespace ShiShiCai.Models { public class DateItem:INotifyPropertyChanged { private int mDate; public int Date { get { return mDate; } set { mDate = value; OnPropertyChanged("Date"); } } public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string property) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(property)); } } } }
29.045455
78
0.462441
[ "MIT" ]
cqssc/ssc
ShiShiCai/Models/DateItem.cs
1,281
C#
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using Stride.Core.Serialization; namespace Stride.Core.IO { [DataSerializerGlobal(typeof(UDirectorySerializer))] internal class UDirectorySerializer : DataSerializer<UDirectory> { /// <inheritdoc/> public override void Serialize(ref UDirectory obj, ArchiveMode mode, SerializationStream stream) { if (mode == ArchiveMode.Serialize) { var path = obj?.FullPath; stream.Serialize(ref path); } else if (mode == ArchiveMode.Deserialize) { string path = null; stream.Serialize(ref path); obj = new UDirectory(path); } } } }
36.555556
163
0.611955
[ "MIT" ]
Alan-love/xenko
sources/core/Stride.Core.Design/IO/UDirectorySerializer.cs
987
C#
using FluentValidation; using Microsoft.Extensions.Logging; using Ordering.API.Application.Commands; namespace Ordering.API.Application.Validations { public class CancelOrderCommandValidator : AbstractValidator<CancelOrderCommand> { public CancelOrderCommandValidator(ILogger<CancelOrderCommandValidator> logger) { RuleFor(order => order.OrderNumber).NotEmpty().WithMessage("No orderId found"); logger.LogTrace("----- INSTANCE CREATED - {ClassName}", GetType().Name); } } }
33.5
91
0.718284
[ "MIT" ]
1448376744/eShopOnContainers
src/Services/Ordering/Ordering.API/Application/Validations/CancelOrderCommandValidator.cs
538
C#
namespace DesignPatternsInCSharp.Behavioral.State.Conceptual; public class Context { public State State { get; set; } public Context(State state) { State = state ?? throw new ArgumentNullException(nameof(state)); } public void Request() => State.Handle(this); }
20.928571
72
0.686007
[ "MIT" ]
adamradocz/DesignPatternsInCSharp
DesignPatternsInCSharp/Behavioral/State/Conceptual/Context.cs
293
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.Serialization; using System.Threading; namespace DynamicCRUD.Emit { public class DynamicClassFactory { private AppDomain _appDomain; private AssemblyBuilder _assemblyBuilder; private ModuleBuilder _moduleBuilder; private TypeBuilder _typeBuilder; private string _assemblyName; public DynamicClassFactory() : this("Dynamic.Objects") { } public DynamicClassFactory(string assemblyName) { _appDomain = Thread.GetDomain(); _assemblyName = assemblyName; } /// <summary> /// This is the normal entry point and just return the Type generated at runtime /// </summary> /// <typeparam name="T"></typeparam> /// <param name="name"></param> /// <param name="properties"></param> /// <returns></returns> public Type CreateDynamicType<T>(string name, Dictionary<string, Type> properties) where T : class { var tb = CreateDynamicTypeBuilder<T>(name, properties); return tb.CreateType(); } /// <summary> /// Exposes a TypeBuilder that can be returned and created outside of the class /// </summary> /// <typeparam name="T"></typeparam> /// <param name="name"></param> /// <param name="properties"></param> /// <returns></returns> public TypeBuilder CreateDynamicTypeBuilder<T>(string name, Dictionary<string, Type> properties) where T : class { if (_assemblyBuilder == null) _assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(_assemblyName), AssemblyBuilderAccess.RunAndCollect); //vital to ensure the namespace of the assembly is the same as the module name, else IL inspectors will fail if (_moduleBuilder == null) _moduleBuilder = _assemblyBuilder.DefineDynamicModule(_assemblyName + ".dll"); //typeof(T) is for the base class, can be omitted if not needed _typeBuilder = _moduleBuilder.DefineType(_assemblyName + "." + name, TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.AutoClass | TypeAttributes.AnsiClass | TypeAttributes.Serializable | TypeAttributes.BeforeFieldInit, typeof(T)); //if there is a property on the base class and also in the dictionary, remove them from the dictionary var pis = typeof(T).GetProperties(); foreach (var pi in pis) { properties.Remove(pi.Name); } //get the OnPropertyChanged method from the base class var propertyChangedMethod = typeof(T).GetMethod("OnPropertyChanged", BindingFlags.Instance | BindingFlags.NonPublic); CreateProperties(properties, propertyChangedMethod); return _typeBuilder; } public void CreateProperties(Dictionary<string, Type> properties, MethodInfo raisePropertyChanged) { properties.ToList().ForEach(p => CreateFieldForType(p.Value, p.Key, raisePropertyChanged)); } public void CreatePropertiesForTypeBuilder(TypeBuilder typeBuilder, Dictionary<string, Type> properties, MethodInfo raisePropertyChanged) { properties.ToList().ForEach(p => CreateFieldForTypeBuilder(typeBuilder, p.Value, p.Key, raisePropertyChanged)); } private void CreateFieldForTypeBuilder(TypeBuilder typeBuilder, Type type, String name, MethodInfo raisePropertyChanged) { FieldBuilder fieldBuilder = typeBuilder.DefineField("_" + name.ToLowerInvariant(), type, FieldAttributes.Private); PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(name, PropertyAttributes.HasDefault, type, null); MethodAttributes getterAndSetterAttributes = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;// | MethodAttributes.Virtual; //creates the Get Method for the property propertyBuilder.SetGetMethod(CreateGetMethodForTypeBuilder(typeBuilder, getterAndSetterAttributes, name, type, fieldBuilder)); //creates the Set Method for the property and also adds the invocation of the property change propertyBuilder.SetSetMethod(CreateSetMethodForTypeBuilder(typeBuilder, getterAndSetterAttributes, name, type, fieldBuilder, raisePropertyChanged)); } private void CreateFieldForType(Type type, String name, MethodInfo raisePropertyChanged) { FieldBuilder fieldBuilder = _typeBuilder.DefineField("_" + name.ToLowerInvariant(), type, FieldAttributes.Private); PropertyBuilder propertyBuilder = _typeBuilder.DefineProperty(name, PropertyAttributes.HasDefault, type, null); //add the various WCF and EF attributes to the property AddDataMemberAttribute(propertyBuilder); MethodAttributes getterAndSetterAttributes = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;// | MethodAttributes.Virtual; //creates the Get Method for the property propertyBuilder.SetGetMethod(CreateGetMethod(getterAndSetterAttributes, name, type, fieldBuilder)); //creates the Set Method for the property and also adds the invocation of the property change propertyBuilder.SetSetMethod(CreateSetMethod(getterAndSetterAttributes, name, type, fieldBuilder, raisePropertyChanged)); } private void AddDataMemberAttribute(PropertyBuilder propertyBuilder) { Type attrType = typeof(DataMemberAttribute); var attr = new CustomAttributeBuilder(attrType.GetConstructor(Type.EmptyTypes), new object[] { }); propertyBuilder.SetCustomAttribute(attr); } private MethodBuilder CreateGetMethod(MethodAttributes attr, string name, Type type, FieldBuilder fieldBuilder) { var getMethodBuilder = _typeBuilder.DefineMethod("get_" + name, attr, type, Type.EmptyTypes); var getMethodILGenerator = getMethodBuilder.GetILGenerator(); getMethodILGenerator.Emit(OpCodes.Ldarg_0); getMethodILGenerator.Emit(OpCodes.Ldfld, fieldBuilder); getMethodILGenerator.Emit(OpCodes.Ret); return getMethodBuilder; } private MethodBuilder CreateGetMethodForTypeBuilder(TypeBuilder typeBuilder, MethodAttributes attr, string name, Type type, FieldBuilder fieldBuilder) { var getMethodBuilder = typeBuilder.DefineMethod("get_" + name, attr, type, Type.EmptyTypes); var getMethodILGenerator = getMethodBuilder.GetILGenerator(); getMethodILGenerator.Emit(OpCodes.Ldarg_0); getMethodILGenerator.Emit(OpCodes.Ldfld, fieldBuilder); getMethodILGenerator.Emit(OpCodes.Ret); return getMethodBuilder; } private MethodBuilder CreateSetMethod(MethodAttributes attr, string name, Type type, FieldBuilder fieldBuilder, MethodInfo raisePropertyChanged) { var setMethodBuilder = _typeBuilder.DefineMethod("set_" + name, attr, null, new Type[] { type }); var setMethodILGenerator = setMethodBuilder.GetILGenerator(); setMethodILGenerator.Emit(OpCodes.Ldarg_0); setMethodILGenerator.Emit(OpCodes.Ldarg_1); setMethodILGenerator.Emit(OpCodes.Stfld, fieldBuilder); if (raisePropertyChanged != null) { setMethodILGenerator.Emit(OpCodes.Ldarg_0); setMethodILGenerator.Emit(OpCodes.Ldstr, name); setMethodILGenerator.EmitCall(OpCodes.Call, raisePropertyChanged, null); } setMethodILGenerator.Emit(OpCodes.Ret); return setMethodBuilder; } private MethodBuilder CreateSetMethodForTypeBuilder(TypeBuilder typeBuilder, MethodAttributes attr, string name, Type type, FieldBuilder fieldBuilder, MethodInfo raisePropertyChanged) { var setMethodBuilder = typeBuilder.DefineMethod("set_" + name, attr, null, new Type[] { type }); var setMethodILGenerator = setMethodBuilder.GetILGenerator(); setMethodILGenerator.Emit(OpCodes.Ldarg_0); setMethodILGenerator.Emit(OpCodes.Ldarg_1); setMethodILGenerator.Emit(OpCodes.Stfld, fieldBuilder); if (raisePropertyChanged != null) { setMethodILGenerator.Emit(OpCodes.Ldarg_0); setMethodILGenerator.Emit(OpCodes.Ldstr, name); setMethodILGenerator.EmitCall(OpCodes.Call, raisePropertyChanged, null); } setMethodILGenerator.Emit(OpCodes.Ret); return setMethodBuilder; } } }
45.871921
191
0.655284
[ "MIT" ]
Behnam-Emamian/DynamicCRUD
DynamicCRUD.Emit/DynamicClassFactory.cs
9,314
C#
namespace ClassLib089 { public class Class044 { public static string Property => "ClassLib089"; } }
15
55
0.633333
[ "MIT" ]
333fred/performance
src/scenarios/weblarge2.0/src/ClassLib089/Class044.cs
120
C#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Allocation; using osu.Framework.Configuration; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Graphics; using osu.Game.Graphics.Sprites; namespace osu.Game.Screens.Play.Break { public class BreakInfoLine<T> : Container where T : struct { private const int margin = 2; public Bindable<T> Current = new Bindable<T>(); private readonly OsuSpriteText text; private readonly OsuSpriteText valueText; private readonly string prefix; public BreakInfoLine(string name, string prefix = @"") { this.prefix = prefix; AutoSizeAxes = Axes.Y; Children = new Drawable[] { text = new OsuSpriteText { Anchor = Anchor.Centre, Origin = Anchor.CentreRight, Text = name, TextSize = 17, Margin = new MarginPadding { Right = margin } }, valueText = new OsuSpriteText { Anchor = Anchor.Centre, Origin = Anchor.CentreLeft, Text = prefix + @"-", TextSize = 17, Font = "Exo2.0-Bold", Margin = new MarginPadding { Left = margin } } }; Current.ValueChanged += currentValueChanged; } private void currentValueChanged(T newValue) { var newText = prefix + Format(newValue); if (valueText.Text == newText) return; valueText.Text = newText; } protected virtual string Format(T count) => count.ToString(); [BackgroundDependencyLoader] private void load(OsuColour colours) { text.Colour = colours.Yellow; valueText.Colour = colours.YellowLight; } } public class PercentageBreakInfoLine : BreakInfoLine<double> { public PercentageBreakInfoLine(string name, string prefix = "") : base(name, prefix) { } protected override string Format(double count) => $@"{count:P2}"; } }
30.096386
93
0.528823
[ "MIT" ]
AtomCrafty/osu
osu.Game/Screens/Play/Break/BreakInfoLine.cs
2,418
C#
using System; using System.Collections.Generic; namespace EGO.Util { public static class EventDispatcher { private static Dictionary<int,Action<object>> mRegisteredEvents = new Dictionary<int, Action<object>>(); public static void Register<T>(T key,Action<object> onEvent) where T : IConvertible { int intKey = key.ToInt32(null); Action<object> registerdEvent; if (!mRegisteredEvents.TryGetValue(intKey, out registerdEvent)) { registerdEvent = (_) => { }; registerdEvent += onEvent; mRegisteredEvents.Add(intKey, registerdEvent); } else { mRegisteredEvents[intKey] += onEvent; } } public static void UnRegister<T>(T key,Action<object> onEvent) where T : IConvertible { int intKey = key.ToInt32(null); Action<object> registerdEvent; if (!mRegisteredEvents.TryGetValue(intKey, out registerdEvent)) { } else { registerdEvent -= onEvent; } } public static void UnRegisterAll<T>(T key) where T : IConvertible { int intKey = key.ToInt32(null); mRegisteredEvents.Remove(intKey); } public static void Send<T>(T key,object arg = null) where T : IConvertible { int intKey = key.ToInt32(null); Action<object> registeredEvent; if (mRegisteredEvents.TryGetValue(intKey,out registeredEvent)) { registeredEvent.Invoke(arg); } } } }
29.576271
112
0.534097
[ "MIT" ]
Zlogn/QFramework
Assets/QFramework/Framework/0.Core/Editor/0.EditorKit/Framework/Util/EventDispatcher.cs
1,745
C#
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Serialization; using OpenSim.Framework.Serialization.External; using OpenSim.Region.CoreModules.World.Archiver; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Scenes.Serialization; using OpenSim.Services.Interfaces; using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Reflection; using System.Text; using System.Xml.Linq; namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver { public class InventoryArchiveReadRequest { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// The maximum major version of archive that we can read. Minor versions shouldn't need a max number since version /// bumps here should be compatible. /// </summary> public static int MAX_MAJOR_VERSION = 1; protected TarArchiveReader archive; private UserAccount m_userInfo; private string m_invPath; /// <summary> /// Do we want to merge this load with existing inventory? /// </summary> protected bool m_merge; protected IInventoryService m_InventoryService; protected IAssetService m_AssetService; protected IUserAccountService m_UserAccountService; /// <value> /// The stream from which the inventory archive will be loaded. /// </value> private Stream m_loadStream; /// <summary> /// Has the control file been loaded for this archive? /// </summary> public bool ControlFileLoaded { get; private set; } /// <summary> /// Do we want to enforce the check. IAR versions before 0.2 and 1.1 do not guarantee this order, so we can't /// enforce. /// </summary> public bool EnforceControlFileCheck { get; private set; } protected bool m_assetsLoaded; protected bool m_inventoryNodesLoaded; protected int m_successfulAssetRestores; protected int m_failedAssetRestores; protected int m_successfulItemRestores; /// <summary> /// Root destination folder for the IAR load. /// </summary> protected InventoryFolderBase m_rootDestinationFolder; /// <summary> /// Inventory nodes loaded from the iar. /// </summary> protected HashSet<InventoryNodeBase> m_loadedNodes = new HashSet<InventoryNodeBase>(); /// <summary> /// In order to load identically named folders, we need to keep track of the folders that we have already /// resolved. /// </summary> Dictionary <string, InventoryFolderBase> m_resolvedFolders = new Dictionary<string, InventoryFolderBase>(); /// <summary> /// Record the creator id that should be associated with an asset. This is used to adjust asset creator ids /// after OSP resolution (since OSP creators are only stored in the item /// </summary> protected Dictionary<UUID, UUID> m_creatorIdForAssetId = new Dictionary<UUID, UUID>(); public InventoryArchiveReadRequest( IInventoryService inv, IAssetService assets, IUserAccountService uacc, UserAccount userInfo, string invPath, string loadPath, bool merge) : this( inv, assets, uacc, userInfo, invPath, new GZipStream(ArchiveHelpers.GetStream(loadPath), CompressionMode.Decompress), merge) { } public InventoryArchiveReadRequest( IInventoryService inv, IAssetService assets, IUserAccountService uacc, UserAccount userInfo, string invPath, Stream loadStream, bool merge) { m_InventoryService = inv; m_AssetService = assets; m_UserAccountService = uacc; m_merge = merge; m_userInfo = userInfo; m_invPath = invPath; m_loadStream = loadStream; // FIXME: Do not perform this check since older versions of OpenSim do save the control file after other things // (I thought they weren't). We will need to bump the version number and perform this check on all // subsequent IAR versions only ControlFileLoaded = true; } /// <summary> /// Execute the request /// </summary> /// <remarks> /// Only call this once. To load another IAR, construct another request object. /// </remarks> /// <returns> /// A list of the inventory nodes loaded. If folders were loaded then only the root folders are /// returned /// </returns> /// <exception cref="System.Exception">Thrown if load fails.</exception> public HashSet<InventoryNodeBase> Execute() { try { string filePath = "ERROR"; List<InventoryFolderBase> folderCandidates = InventoryArchiveUtils.FindFoldersByPath( m_InventoryService, m_userInfo.PrincipalID, m_invPath); if (folderCandidates.Count == 0) { // Possibly provide an option later on to automatically create this folder if it does not exist m_log.ErrorFormat("[INVENTORY ARCHIVER]: Inventory path {0} does not exist", m_invPath); return m_loadedNodes; } m_rootDestinationFolder = folderCandidates[0]; archive = new TarArchiveReader(m_loadStream); byte[] data; TarArchiveReader.TarEntryType entryType; while ((data = archive.ReadEntry(out filePath, out entryType)) != null) { if (filePath == ArchiveConstants.CONTROL_FILE_PATH) { LoadControlFile(filePath, data); } else if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH)) { LoadAssetFile(filePath, data); } else if (filePath.StartsWith(ArchiveConstants.INVENTORY_PATH)) { LoadInventoryFile(filePath, entryType, data); } } archive.Close(); m_log.DebugFormat( "[INVENTORY ARCHIVER]: Successfully loaded {0} assets with {1} failures", m_successfulAssetRestores, m_failedAssetRestores); m_log.InfoFormat("[INVENTORY ARCHIVER]: Successfully loaded {0} items", m_successfulItemRestores); return m_loadedNodes; } finally { m_loadStream.Close(); } } public void Close() { if (m_loadStream != null) m_loadStream.Close(); } /// <summary> /// Replicate the inventory paths in the archive to the user's inventory as necessary. /// </summary> /// <param name="iarPath">The item archive path to replicate</param> /// <param name="rootDestinationFolder">The root folder for the inventory load</param> /// <param name="resolvedFolders"> /// The folders that we have resolved so far for a given archive path. /// This method will add more folders if necessary /// </param> /// <param name="loadedNodes"> /// Track the inventory nodes created. /// </param> /// <returns>The last user inventory folder created or found for the archive path</returns> public InventoryFolderBase ReplicateArchivePathToUserInventory( string iarPath, InventoryFolderBase rootDestFolder, Dictionary <string, InventoryFolderBase> resolvedFolders, HashSet<InventoryNodeBase> loadedNodes) { string iarPathExisting = iarPath; // m_log.DebugFormat( // "[INVENTORY ARCHIVER]: Loading folder {0} {1}", rootDestFolder.Name, rootDestFolder.ID); InventoryFolderBase destFolder = ResolveDestinationFolder(rootDestFolder, ref iarPathExisting, resolvedFolders); // m_log.DebugFormat( // "[INVENTORY ARCHIVER]: originalArchivePath [{0}], section already loaded [{1}]", // iarPath, iarPathExisting); string iarPathToCreate = iarPath.Substring(iarPathExisting.Length); CreateFoldersForPath(destFolder, iarPathExisting, iarPathToCreate, resolvedFolders, loadedNodes); return destFolder; } /// <summary> /// Resolve a destination folder /// </summary> /// /// We require here a root destination folder (usually the root of the user's inventory) and the archive /// path. We also pass in a list of previously resolved folders in case we've found this one previously. /// /// <param name="archivePath"> /// The item archive path to resolve. The portion of the path passed back is that /// which corresponds to the resolved desintation folder. /// <param name="rootDestinationFolder"> /// The root folder for the inventory load /// </param> /// <param name="resolvedFolders"> /// The folders that we have resolved so far for a given archive path. /// </param> /// <returns> /// The folder in the user's inventory that matches best the archive path given. If no such folder was found /// then the passed in root destination folder is returned. /// </returns> protected InventoryFolderBase ResolveDestinationFolder( InventoryFolderBase rootDestFolder, ref string archivePath, Dictionary <string, InventoryFolderBase> resolvedFolders) { // string originalArchivePath = archivePath; while (archivePath.Length > 0) { // m_log.DebugFormat("[INVENTORY ARCHIVER]: Trying to resolve destination folder {0}", archivePath); if (resolvedFolders.ContainsKey(archivePath)) { // m_log.DebugFormat( // "[INVENTORY ARCHIVER]: Found previously created folder from archive path {0}", archivePath); return resolvedFolders[archivePath]; } else { if (m_merge) { // TODO: Using m_invPath is totally wrong - what we need to do is strip the uuid from the // iar name and try to find that instead. string plainPath = ArchiveConstants.ExtractPlainPathFromIarPath(archivePath); List<InventoryFolderBase> folderCandidates = InventoryArchiveUtils.FindFoldersByPath( m_InventoryService, m_userInfo.PrincipalID, plainPath); if (folderCandidates.Count != 0) { InventoryFolderBase destFolder = folderCandidates[0]; resolvedFolders[archivePath] = destFolder; return destFolder; } } // Don't include the last slash so find the penultimate one int penultimateSlashIndex = archivePath.LastIndexOf("/", archivePath.Length - 2); if (penultimateSlashIndex >= 0) { // Remove the last section of path so that we can see if we've already resolved the parent archivePath = archivePath.Remove(penultimateSlashIndex + 1); } else { // m_log.DebugFormat( // "[INVENTORY ARCHIVER]: Found no previously created folder for archive path {0}", // originalArchivePath); archivePath = string.Empty; return rootDestFolder; } } } return rootDestFolder; } /// <summary> /// Create a set of folders for the given path. /// </summary> /// <param name="destFolder"> /// The root folder from which the creation will take place. /// </param> /// <param name="iarPathExisting"> /// the part of the iar path that already exists /// </param> /// <param name="iarPathToReplicate"> /// The path to replicate in the user's inventory from iar /// </param> /// <param name="resolvedFolders"> /// The folders that we have resolved so far for a given archive path. /// </param> /// <param name="loadedNodes"> /// Track the inventory nodes created. /// </param> protected void CreateFoldersForPath( InventoryFolderBase destFolder, string iarPathExisting, string iarPathToReplicate, Dictionary <string, InventoryFolderBase> resolvedFolders, HashSet<InventoryNodeBase> loadedNodes) { string[] rawDirsToCreate = iarPathToReplicate.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < rawDirsToCreate.Length; i++) { // m_log.DebugFormat("[INVENTORY ARCHIVER]: Creating folder {0} from IAR", rawDirsToCreate[i]); if (!rawDirsToCreate[i].Contains(ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR)) continue; int identicalNameIdentifierIndex = rawDirsToCreate[i].LastIndexOf( ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR); string newFolderName = rawDirsToCreate[i].Remove(identicalNameIdentifierIndex); newFolderName = InventoryArchiveUtils.UnescapeArchivePath(newFolderName); UUID newFolderId = UUID.Random(); // Asset type has to be Unknown here rather than Folder, otherwise the created folder can't be // deleted once the client has relogged. // The root folder appears to be labelled AssetType.Folder (shows up as "Category" in the client) // even though there is a AssetType.RootCategory destFolder = new InventoryFolderBase( newFolderId, newFolderName, m_userInfo.PrincipalID, (short)AssetType.Unknown, destFolder.ID, 1); m_InventoryService.AddFolder(destFolder); // Record that we have now created this folder iarPathExisting += rawDirsToCreate[i] + "/"; m_log.DebugFormat("[INVENTORY ARCHIVER]: Created folder {0} from IAR", iarPathExisting); resolvedFolders[iarPathExisting] = destFolder; if (0 == i) loadedNodes.Add(destFolder); } } /// <summary> /// Load an item from the archive /// </summary> /// <param name="filePath">The archive path for the item</param> /// <param name="data">The raw item data</param> /// <param name="rootDestinationFolder">The root destination folder for loaded items</param> /// <param name="nodesLoaded">All the inventory nodes (items and folders) loaded so far</param> protected InventoryItemBase LoadItem(byte[] data, InventoryFolderBase loadFolder) { InventoryItemBase item = UserInventoryItemSerializer.Deserialize(data); // Don't use the item ID that's in the file item.ID = UUID.Random(); UUID ospResolvedId = OspResolver.ResolveOspa(item.CreatorId, m_UserAccountService); if (UUID.Zero != ospResolvedId) // The user exists in this grid { // m_log.DebugFormat("[INVENTORY ARCHIVER]: Found creator {0} via OSPA resolution", ospResolvedId); // item.CreatorIdAsUuid = ospResolvedId; // Don't preserve the OSPA in the creator id (which actually gets persisted to the // database). Instead, replace with the UUID that we found. item.CreatorId = ospResolvedId.ToString(); item.CreatorData = string.Empty; } else if (string.IsNullOrEmpty(item.CreatorData)) { item.CreatorId = m_userInfo.PrincipalID.ToString(); // item.CreatorIdAsUuid = new UUID(item.CreatorId); } item.Owner = m_userInfo.PrincipalID; // Reset folder ID to the one in which we want to load it item.Folder = loadFolder.ID; // Record the creator id for the item's asset so that we can use it later, if necessary, when the asset // is loaded. // FIXME: This relies on the items coming before the assets in the TAR file. Need to create stronger // checks for this, and maybe even an external tool for creating OARs which enforces this, rather than // relying on native tar tools. m_creatorIdForAssetId[item.AssetID] = item.CreatorIdAsUuid; if (!m_InventoryService.AddItem(item)) m_log.WarnFormat("[INVENTORY ARCHIVER]: Unable to save item {0} in folder {1}", item.Name, item.Folder); return item; } /// <summary> /// Load an asset /// </summary> /// <param name="assetFilename"></param> /// <param name="data"></param> /// <returns>true if asset was successfully loaded, false otherwise</returns> private bool LoadAsset(string assetPath, byte[] data) { //IRegionSerialiser serialiser = scene.RequestModuleInterface<IRegionSerialiser>(); // Right now we're nastily obtaining the UUID from the filename string filename = assetPath.Remove(0, ArchiveConstants.ASSETS_PATH.Length); int i = filename.LastIndexOf(ArchiveConstants.ASSET_EXTENSION_SEPARATOR); if (i == -1) { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: Could not find extension information in asset path {0} since it's missing the separator {1}. Skipping", assetPath, ArchiveConstants.ASSET_EXTENSION_SEPARATOR); return false; } string extension = filename.Substring(i); string rawUuid = filename.Remove(filename.Length - extension.Length); UUID assetId = new UUID(rawUuid); if (ArchiveConstants.EXTENSION_TO_ASSET_TYPE.ContainsKey(extension)) { sbyte assetType = ArchiveConstants.EXTENSION_TO_ASSET_TYPE[extension]; if (assetType == (sbyte)AssetType.Unknown) { m_log.WarnFormat("[INVENTORY ARCHIVER]: Importing {0} byte asset {1} with unknown type", data.Length, assetId); } else if (assetType == (sbyte)AssetType.Object) { if (m_creatorIdForAssetId.ContainsKey(assetId)) { data = SceneObjectSerializer.ModifySerializedObject(assetId, data, sog => { bool modified = false; foreach (SceneObjectPart sop in sog.Parts) { if (string.IsNullOrEmpty(sop.CreatorData)) { sop.CreatorID = m_creatorIdForAssetId[assetId]; modified = true; } } return modified; }); if (data == null) return false; } } //m_log.DebugFormat("[INVENTORY ARCHIVER]: Importing asset {0}, type {1}", uuid, assetType); AssetBase asset = new AssetBase(assetId, "From IAR", assetType, UUID.Zero.ToString()); asset.Data = data; m_AssetService.Store(asset); return true; } else { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: Tried to dearchive data with path {0} with an unknown type extension {1}", assetPath, extension); return false; } } /// <summary> /// Load control file /// </summary> /// <param name="path"></param> /// <param name="data"></param> public void LoadControlFile(string path, byte[] data) { XDocument doc = XDocument.Parse(Encoding.ASCII.GetString(data)); XElement archiveElement = doc.Element("archive"); int majorVersion = int.Parse(archiveElement.Attribute("major_version").Value); int minorVersion = int.Parse(archiveElement.Attribute("minor_version").Value); string version = string.Format("{0}.{1}", majorVersion, minorVersion); if (majorVersion > MAX_MAJOR_VERSION) { throw new Exception( string.Format( "The IAR you are trying to load has major version number of {0} but this version of OpenSim can only load IARs with major version number {1} and below", majorVersion, MAX_MAJOR_VERSION)); } ControlFileLoaded = true; m_log.InfoFormat("[INVENTORY ARCHIVER]: Loading IAR with version {0}", version); } /// <summary> /// Load inventory file /// </summary> /// <param name="path"></param> /// <param name="entryType"></param> /// <param name="data"></param> protected void LoadInventoryFile(string path, TarArchiveReader.TarEntryType entryType, byte[] data) { if (!ControlFileLoaded) throw new Exception( string.Format( "The IAR you are trying to load does not list {0} before {1}. Aborting load", ArchiveConstants.CONTROL_FILE_PATH, ArchiveConstants.INVENTORY_PATH)); if (m_assetsLoaded) throw new Exception( string.Format( "The IAR you are trying to load does not list all {0} before {1}. Aborting load", ArchiveConstants.INVENTORY_PATH, ArchiveConstants.ASSETS_PATH)); path = path.Substring(ArchiveConstants.INVENTORY_PATH.Length); // Trim off the file portion if we aren't already dealing with a directory path if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY != entryType) path = path.Remove(path.LastIndexOf("/") + 1); InventoryFolderBase foundFolder = ReplicateArchivePathToUserInventory( path, m_rootDestinationFolder, m_resolvedFolders, m_loadedNodes); if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY != entryType) { InventoryItemBase item = LoadItem(data, foundFolder); if (item != null) { m_successfulItemRestores++; // If we aren't loading the folder containing the item then well need to update the // viewer separately for that item. if (!m_loadedNodes.Contains(foundFolder)) m_loadedNodes.Add(item); } } m_inventoryNodesLoaded = true; } /// <summary> /// Load asset file /// </summary> /// <param name="path"></param> /// <param name="data"></param> protected void LoadAssetFile(string path, byte[] data) { if (!ControlFileLoaded) throw new Exception( string.Format( "The IAR you are trying to load does not list {0} before {1}. Aborting load", ArchiveConstants.CONTROL_FILE_PATH, ArchiveConstants.ASSETS_PATH)); if (!m_inventoryNodesLoaded) throw new Exception( string.Format( "The IAR you are trying to load does not list all {0} before {1}. Aborting load", ArchiveConstants.INVENTORY_PATH, ArchiveConstants.ASSETS_PATH)); if (LoadAsset(path, data)) m_successfulAssetRestores++; else m_failedAssetRestores++; if ((m_successfulAssetRestores) % 50 == 0) m_log.DebugFormat( "[INVENTORY ARCHIVER]: Loaded {0} assets...", m_successfulAssetRestores); m_assetsLoaded = true; } } }
44.623211
176
0.558536
[ "BSD-3-Clause" ]
Michelle-Argus/ArribasimExtract
OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiveReadRequest.cs
28,068
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace DDDSkeleton.Portal.Domain.Customer { 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 CustomerBusinessRuleMessages { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal CustomerBusinessRuleMessages() { } /// <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("DDDSkeleton.Portal.Domain.Customer.CustomerBusinessRuleMessages", typeof(CustomerBusinessRuleMessages).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; } } /// <summary> /// Looks up a localized string similar to A customer must have a name.. /// </summary> internal static string CustomerNameRequired { get { return ResourceManager.GetString("CustomerNameRequired", resourceCulture); } } } }
43.90411
227
0.616537
[ "MIT" ]
guillermocorrea/DDDSkeletonNET
DDDSkeletonNET/DDDSkeleton.Portal.Domain/Customer/CustomerBusinessRuleMessages.Designer.cs
3,207
C#
using System; using System.Collections.Generic; using System.Json; namespace Rankings_Common { public class Rank { private static string defaultCategoryType = "handheld"; public Rank (List<DateTime> dateList, JsonValue json) { Country = json ["country"]; JsonValue category = json ["category"]; CategoryName = defaultCategoryType.Equals (category ["device"]) ? (string)category ["name"] : String.Format ("{0} ({1})", (string)category ["name"], (string)category ["device"]); ProductId = json ["product_id"]; JsonArray positions = (JsonArray)json ["positions"]; Positions = new Dictionary<DateTime, int> (); for (int i = 0; i < Math.Min (dateList.Count, positions.Count); i++) { Positions.Add (dateList [i], positions [i] != null ? (int)positions [i] : 0); } } public string Country { get; set; } public string CategoryName { get; set; } public int ProductId { get; set; } public Dictionary<DateTime, int> Positions { get; set; } public string GetGategoryName() { return String.Format ("{0}-{1}", Country, CategoryName); } } }
25.113636
91
0.657919
[ "MIT" ]
Smileek/AppFiguresRanks
Rankings_Common/Rank.cs
1,107
C#
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace WeChatManagementSample.Migrations { public partial class init : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "AbpAuditLogs", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), ApplicationName = table.Column<string>(type: "nvarchar(96)", maxLength: 96, nullable: true), UserId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), UserName = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true), TenantId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), TenantName = table.Column<string>(type: "nvarchar(max)", nullable: true), ImpersonatorUserId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), ImpersonatorTenantId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), ExecutionTime = table.Column<DateTime>(type: "datetime2", nullable: false), ExecutionDuration = table.Column<int>(type: "int", nullable: false), ClientIpAddress = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: true), ClientName = table.Column<string>(type: "nvarchar(128)", maxLength: 128, nullable: true), ClientId = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: true), CorrelationId = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: true), BrowserInfo = table.Column<string>(type: "nvarchar(512)", maxLength: 512, nullable: true), HttpMethod = table.Column<string>(type: "nvarchar(16)", maxLength: 16, nullable: true), Url = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true), Exceptions = table.Column<string>(type: "nvarchar(max)", nullable: true), Comments = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true), HttpStatusCode = table.Column<int>(type: "int", nullable: true), ExtraProperties = table.Column<string>(type: "nvarchar(max)", nullable: true), ConcurrencyStamp = table.Column<string>(type: "nvarchar(40)", maxLength: 40, nullable: true) }, constraints: table => { table.PrimaryKey("PK_AbpAuditLogs", x => x.Id); }); migrationBuilder.CreateTable( name: "AbpBackgroundJobs", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), JobName = table.Column<string>(type: "nvarchar(128)", maxLength: 128, nullable: false), JobArgs = table.Column<string>(type: "nvarchar(max)", maxLength: 1048576, nullable: false), TryCount = table.Column<short>(type: "smallint", nullable: false, defaultValue: (short)0), CreationTime = table.Column<DateTime>(type: "datetime2", nullable: false), NextTryTime = table.Column<DateTime>(type: "datetime2", nullable: false), LastTryTime = table.Column<DateTime>(type: "datetime2", nullable: true), IsAbandoned = table.Column<bool>(type: "bit", nullable: false, defaultValue: false), Priority = table.Column<byte>(type: "tinyint", nullable: false, defaultValue: (byte)15), ExtraProperties = table.Column<string>(type: "nvarchar(max)", nullable: true), ConcurrencyStamp = table.Column<string>(type: "nvarchar(40)", maxLength: 40, nullable: true) }, constraints: table => { table.PrimaryKey("PK_AbpBackgroundJobs", x => x.Id); }); migrationBuilder.CreateTable( name: "AbpClaimTypes", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), Name = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: false), Required = table.Column<bool>(type: "bit", nullable: false), IsStatic = table.Column<bool>(type: "bit", nullable: false), Regex = table.Column<string>(type: "nvarchar(512)", maxLength: 512, nullable: true), RegexDescription = table.Column<string>(type: "nvarchar(128)", maxLength: 128, nullable: true), Description = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true), ValueType = table.Column<int>(type: "int", nullable: false), ExtraProperties = table.Column<string>(type: "nvarchar(max)", nullable: true), ConcurrencyStamp = table.Column<string>(type: "nvarchar(40)", maxLength: 40, nullable: true) }, constraints: table => { table.PrimaryKey("PK_AbpClaimTypes", x => x.Id); }); migrationBuilder.CreateTable( name: "AbpFeatureValues", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), Name = table.Column<string>(type: "nvarchar(128)", maxLength: 128, nullable: false), Value = table.Column<string>(type: "nvarchar(128)", maxLength: 128, nullable: false), ProviderName = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: true), ProviderKey = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: true) }, constraints: table => { table.PrimaryKey("PK_AbpFeatureValues", x => x.Id); }); migrationBuilder.CreateTable( name: "AbpLinkUsers", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), SourceUserId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), SourceTenantId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), TargetUserId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), TargetTenantId = table.Column<Guid>(type: "uniqueidentifier", nullable: true) }, constraints: table => { table.PrimaryKey("PK_AbpLinkUsers", x => x.Id); }); migrationBuilder.CreateTable( name: "AbpOrganizationUnits", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), TenantId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), ParentId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), Code = table.Column<string>(type: "nvarchar(95)", maxLength: 95, nullable: false), DisplayName = table.Column<string>(type: "nvarchar(128)", maxLength: 128, nullable: false), ExtraProperties = table.Column<string>(type: "nvarchar(max)", nullable: true), ConcurrencyStamp = table.Column<string>(type: "nvarchar(40)", maxLength: 40, nullable: true), CreationTime = table.Column<DateTime>(type: "datetime2", nullable: false), CreatorId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), LastModificationTime = table.Column<DateTime>(type: "datetime2", nullable: true), LastModifierId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), IsDeleted = table.Column<bool>(type: "bit", nullable: false, defaultValue: false), DeleterId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), DeletionTime = table.Column<DateTime>(type: "datetime2", nullable: true) }, constraints: table => { table.PrimaryKey("PK_AbpOrganizationUnits", x => x.Id); table.ForeignKey( name: "FK_AbpOrganizationUnits_AbpOrganizationUnits_ParentId", column: x => x.ParentId, principalTable: "AbpOrganizationUnits", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "AbpPermissionGrants", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), TenantId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), Name = table.Column<string>(type: "nvarchar(128)", maxLength: 128, nullable: false), ProviderName = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: false), ProviderKey = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: false) }, constraints: table => { table.PrimaryKey("PK_AbpPermissionGrants", x => x.Id); }); migrationBuilder.CreateTable( name: "AbpRoles", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), TenantId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), Name = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: false), NormalizedName = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: false), IsDefault = table.Column<bool>(type: "bit", nullable: false), IsStatic = table.Column<bool>(type: "bit", nullable: false), IsPublic = table.Column<bool>(type: "bit", nullable: false), ExtraProperties = table.Column<string>(type: "nvarchar(max)", nullable: true), ConcurrencyStamp = table.Column<string>(type: "nvarchar(40)", maxLength: 40, nullable: true) }, constraints: table => { table.PrimaryKey("PK_AbpRoles", x => x.Id); }); migrationBuilder.CreateTable( name: "AbpSecurityLogs", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), TenantId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), ApplicationName = table.Column<string>(type: "nvarchar(96)", maxLength: 96, nullable: true), Identity = table.Column<string>(type: "nvarchar(96)", maxLength: 96, nullable: true), Action = table.Column<string>(type: "nvarchar(96)", maxLength: 96, nullable: true), UserId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), UserName = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true), TenantName = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: true), ClientId = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: true), CorrelationId = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: true), ClientIpAddress = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: true), BrowserInfo = table.Column<string>(type: "nvarchar(512)", maxLength: 512, nullable: true), CreationTime = table.Column<DateTime>(type: "datetime2", nullable: false), ExtraProperties = table.Column<string>(type: "nvarchar(max)", nullable: true), ConcurrencyStamp = table.Column<string>(type: "nvarchar(40)", maxLength: 40, nullable: true) }, constraints: table => { table.PrimaryKey("PK_AbpSecurityLogs", x => x.Id); }); migrationBuilder.CreateTable( name: "AbpSettings", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), Name = table.Column<string>(type: "nvarchar(128)", maxLength: 128, nullable: false), Value = table.Column<string>(type: "nvarchar(2048)", maxLength: 2048, nullable: false), ProviderName = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: true), ProviderKey = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: true) }, constraints: table => { table.PrimaryKey("PK_AbpSettings", x => x.Id); }); migrationBuilder.CreateTable( name: "AbpTenants", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), Name = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: false), TenantOwnerName = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: false), ExtraProperties = table.Column<string>(type: "nvarchar(max)", nullable: true), ConcurrencyStamp = table.Column<string>(type: "nvarchar(40)", maxLength: 40, nullable: true), CreationTime = table.Column<DateTime>(type: "datetime2", nullable: false), CreatorId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), LastModificationTime = table.Column<DateTime>(type: "datetime2", nullable: true), LastModifierId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), IsDeleted = table.Column<bool>(type: "bit", nullable: false, defaultValue: false), DeleterId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), DeletionTime = table.Column<DateTime>(type: "datetime2", nullable: true) }, constraints: table => { table.PrimaryKey("PK_AbpTenants", x => x.Id); }); migrationBuilder.CreateTable( name: "AbpUsers", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), TenantId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), UserName = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: false), NormalizedUserName = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: false), Name = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: true), Surname = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: true), Email = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: false), NormalizedEmail = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: false), EmailConfirmed = table.Column<bool>(type: "bit", nullable: false, defaultValue: false), PasswordHash = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true), SecurityStamp = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: false), IsExternal = table.Column<bool>(type: "bit", nullable: false, defaultValue: false), PhoneNumber = table.Column<string>(type: "nvarchar(16)", maxLength: 16, nullable: true), PhoneNumberConfirmed = table.Column<bool>(type: "bit", nullable: false, defaultValue: false), TwoFactorEnabled = table.Column<bool>(type: "bit", nullable: false, defaultValue: false), LockoutEnd = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: true), LockoutEnabled = table.Column<bool>(type: "bit", nullable: false, defaultValue: false), AccessFailedCount = table.Column<int>(type: "int", nullable: false, defaultValue: 0), ExtraProperties = table.Column<string>(type: "nvarchar(max)", nullable: true), ConcurrencyStamp = table.Column<string>(type: "nvarchar(40)", maxLength: 40, nullable: true), CreationTime = table.Column<DateTime>(type: "datetime2", nullable: false), CreatorId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), LastModificationTime = table.Column<DateTime>(type: "datetime2", nullable: true), LastModifierId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), IsDeleted = table.Column<bool>(type: "bit", nullable: false, defaultValue: false), DeleterId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), DeletionTime = table.Column<DateTime>(type: "datetime2", nullable: true) }, constraints: table => { table.PrimaryKey("PK_AbpUsers", x => x.Id); }); migrationBuilder.CreateTable( name: "AbpUserTenants", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), UserId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), UserName = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: false), TenantOwnerName = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: false), TenantId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), ExtraProperties = table.Column<string>(type: "nvarchar(max)", nullable: true), ConcurrencyStamp = table.Column<string>(type: "nvarchar(40)", maxLength: 40, nullable: true), CreationTime = table.Column<DateTime>(type: "datetime2", nullable: false), CreatorId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), LastModificationTime = table.Column<DateTime>(type: "datetime2", nullable: true), LastModifierId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), IsDeleted = table.Column<bool>(type: "bit", nullable: false, defaultValue: false), DeleterId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), DeletionTime = table.Column<DateTime>(type: "datetime2", nullable: true) }, constraints: table => { table.PrimaryKey("PK_AbpUserTenants", x => x.Id); }); migrationBuilder.CreateTable( name: "IdentityServerApiResources", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), Name = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: false), DisplayName = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: true), Description = table.Column<string>(type: "nvarchar(1000)", maxLength: 1000, nullable: true), Enabled = table.Column<bool>(type: "bit", nullable: false), AllowedAccessTokenSigningAlgorithms = table.Column<string>(type: "nvarchar(100)", maxLength: 100, nullable: true), ShowInDiscoveryDocument = table.Column<bool>(type: "bit", nullable: false), ExtraProperties = table.Column<string>(type: "nvarchar(max)", nullable: true), ConcurrencyStamp = table.Column<string>(type: "nvarchar(40)", maxLength: 40, nullable: true), CreationTime = table.Column<DateTime>(type: "datetime2", nullable: false), CreatorId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), LastModificationTime = table.Column<DateTime>(type: "datetime2", nullable: true), LastModifierId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), IsDeleted = table.Column<bool>(type: "bit", nullable: false, defaultValue: false), DeleterId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), DeletionTime = table.Column<DateTime>(type: "datetime2", nullable: true) }, constraints: table => { table.PrimaryKey("PK_IdentityServerApiResources", x => x.Id); }); migrationBuilder.CreateTable( name: "IdentityServerApiScopes", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), Enabled = table.Column<bool>(type: "bit", nullable: false), Name = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: false), DisplayName = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: true), Description = table.Column<string>(type: "nvarchar(1000)", maxLength: 1000, nullable: true), Required = table.Column<bool>(type: "bit", nullable: false), Emphasize = table.Column<bool>(type: "bit", nullable: false), ShowInDiscoveryDocument = table.Column<bool>(type: "bit", nullable: false), ExtraProperties = table.Column<string>(type: "nvarchar(max)", nullable: true), ConcurrencyStamp = table.Column<string>(type: "nvarchar(40)", maxLength: 40, nullable: true), CreationTime = table.Column<DateTime>(type: "datetime2", nullable: false), CreatorId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), LastModificationTime = table.Column<DateTime>(type: "datetime2", nullable: true), LastModifierId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), IsDeleted = table.Column<bool>(type: "bit", nullable: false, defaultValue: false), DeleterId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), DeletionTime = table.Column<DateTime>(type: "datetime2", nullable: true) }, constraints: table => { table.PrimaryKey("PK_IdentityServerApiScopes", x => x.Id); }); migrationBuilder.CreateTable( name: "IdentityServerClients", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), ClientId = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: false), ClientName = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: true), Description = table.Column<string>(type: "nvarchar(1000)", maxLength: 1000, nullable: true), ClientUri = table.Column<string>(type: "nvarchar(2000)", maxLength: 2000, nullable: true), LogoUri = table.Column<string>(type: "nvarchar(2000)", maxLength: 2000, nullable: true), Enabled = table.Column<bool>(type: "bit", nullable: false), ProtocolType = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: false), RequireClientSecret = table.Column<bool>(type: "bit", nullable: false), RequireConsent = table.Column<bool>(type: "bit", nullable: false), AllowRememberConsent = table.Column<bool>(type: "bit", nullable: false), AlwaysIncludeUserClaimsInIdToken = table.Column<bool>(type: "bit", nullable: false), RequirePkce = table.Column<bool>(type: "bit", nullable: false), AllowPlainTextPkce = table.Column<bool>(type: "bit", nullable: false), RequireRequestObject = table.Column<bool>(type: "bit", nullable: false), AllowAccessTokensViaBrowser = table.Column<bool>(type: "bit", nullable: false), FrontChannelLogoutUri = table.Column<string>(type: "nvarchar(2000)", maxLength: 2000, nullable: true), FrontChannelLogoutSessionRequired = table.Column<bool>(type: "bit", nullable: false), BackChannelLogoutUri = table.Column<string>(type: "nvarchar(2000)", maxLength: 2000, nullable: true), BackChannelLogoutSessionRequired = table.Column<bool>(type: "bit", nullable: false), AllowOfflineAccess = table.Column<bool>(type: "bit", nullable: false), IdentityTokenLifetime = table.Column<int>(type: "int", nullable: false), AllowedIdentityTokenSigningAlgorithms = table.Column<string>(type: "nvarchar(100)", maxLength: 100, nullable: true), AccessTokenLifetime = table.Column<int>(type: "int", nullable: false), AuthorizationCodeLifetime = table.Column<int>(type: "int", nullable: false), ConsentLifetime = table.Column<int>(type: "int", nullable: true), AbsoluteRefreshTokenLifetime = table.Column<int>(type: "int", nullable: false), SlidingRefreshTokenLifetime = table.Column<int>(type: "int", nullable: false), RefreshTokenUsage = table.Column<int>(type: "int", nullable: false), UpdateAccessTokenClaimsOnRefresh = table.Column<bool>(type: "bit", nullable: false), RefreshTokenExpiration = table.Column<int>(type: "int", nullable: false), AccessTokenType = table.Column<int>(type: "int", nullable: false), EnableLocalLogin = table.Column<bool>(type: "bit", nullable: false), IncludeJwtId = table.Column<bool>(type: "bit", nullable: false), AlwaysSendClientClaims = table.Column<bool>(type: "bit", nullable: false), ClientClaimsPrefix = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: true), PairWiseSubjectSalt = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: true), UserSsoLifetime = table.Column<int>(type: "int", nullable: true), UserCodeType = table.Column<string>(type: "nvarchar(100)", maxLength: 100, nullable: true), DeviceCodeLifetime = table.Column<int>(type: "int", nullable: false), ExtraProperties = table.Column<string>(type: "nvarchar(max)", nullable: true), ConcurrencyStamp = table.Column<string>(type: "nvarchar(40)", maxLength: 40, nullable: true), CreationTime = table.Column<DateTime>(type: "datetime2", nullable: false), CreatorId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), LastModificationTime = table.Column<DateTime>(type: "datetime2", nullable: true), LastModifierId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), IsDeleted = table.Column<bool>(type: "bit", nullable: false, defaultValue: false), DeleterId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), DeletionTime = table.Column<DateTime>(type: "datetime2", nullable: true) }, constraints: table => { table.PrimaryKey("PK_IdentityServerClients", x => x.Id); }); migrationBuilder.CreateTable( name: "IdentityServerDeviceFlowCodes", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), DeviceCode = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: false), UserCode = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: false), SubjectId = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: true), SessionId = table.Column<string>(type: "nvarchar(100)", maxLength: 100, nullable: true), ClientId = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: false), Description = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: true), Expiration = table.Column<DateTime>(type: "datetime2", nullable: false), Data = table.Column<string>(type: "nvarchar(max)", maxLength: 50000, nullable: false), ExtraProperties = table.Column<string>(type: "nvarchar(max)", nullable: true), ConcurrencyStamp = table.Column<string>(type: "nvarchar(40)", maxLength: 40, nullable: true), CreationTime = table.Column<DateTime>(type: "datetime2", nullable: false), CreatorId = table.Column<Guid>(type: "uniqueidentifier", nullable: true) }, constraints: table => { table.PrimaryKey("PK_IdentityServerDeviceFlowCodes", x => x.Id); }); migrationBuilder.CreateTable( name: "IdentityServerIdentityResources", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), Name = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: false), DisplayName = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: true), Description = table.Column<string>(type: "nvarchar(1000)", maxLength: 1000, nullable: true), Enabled = table.Column<bool>(type: "bit", nullable: false), Required = table.Column<bool>(type: "bit", nullable: false), Emphasize = table.Column<bool>(type: "bit", nullable: false), ShowInDiscoveryDocument = table.Column<bool>(type: "bit", nullable: false), ExtraProperties = table.Column<string>(type: "nvarchar(max)", nullable: true), ConcurrencyStamp = table.Column<string>(type: "nvarchar(40)", maxLength: 40, nullable: true), CreationTime = table.Column<DateTime>(type: "datetime2", nullable: false), CreatorId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), LastModificationTime = table.Column<DateTime>(type: "datetime2", nullable: true), LastModifierId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), IsDeleted = table.Column<bool>(type: "bit", nullable: false, defaultValue: false), DeleterId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), DeletionTime = table.Column<DateTime>(type: "datetime2", nullable: true) }, constraints: table => { table.PrimaryKey("PK_IdentityServerIdentityResources", x => x.Id); }); migrationBuilder.CreateTable( name: "IdentityServerPersistedGrants", columns: table => new { Key = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: false), Type = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: false), SubjectId = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: true), SessionId = table.Column<string>(type: "nvarchar(100)", maxLength: 100, nullable: true), ClientId = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: false), Description = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: true), CreationTime = table.Column<DateTime>(type: "datetime2", nullable: false), Expiration = table.Column<DateTime>(type: "datetime2", nullable: true), ConsumedTime = table.Column<DateTime>(type: "datetime2", nullable: true), Data = table.Column<string>(type: "nvarchar(max)", maxLength: 50000, nullable: false), Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), ExtraProperties = table.Column<string>(type: "nvarchar(max)", nullable: true), ConcurrencyStamp = table.Column<string>(type: "nvarchar(40)", maxLength: 40, nullable: true) }, constraints: table => { table.PrimaryKey("PK_IdentityServerPersistedGrants", x => x.Key); }); migrationBuilder.CreateTable( name: "WeChatApps", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), TenantId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), Type = table.Column<int>(type: "int", nullable: false), WeChatComponentId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), Name = table.Column<string>(type: "nvarchar(max)", nullable: true), DisplayName = table.Column<string>(type: "nvarchar(max)", nullable: true), OpenAppIdOrName = table.Column<string>(type: "nvarchar(max)", nullable: true), AppId = table.Column<string>(type: "nvarchar(max)", nullable: true), AppSecret = table.Column<string>(type: "nvarchar(max)", nullable: true), Token = table.Column<string>(type: "nvarchar(max)", nullable: true), EncodingAesKey = table.Column<string>(type: "nvarchar(max)", nullable: true), IsStatic = table.Column<bool>(type: "bit", nullable: false), ExtraProperties = table.Column<string>(type: "nvarchar(max)", nullable: true), ConcurrencyStamp = table.Column<string>(type: "nvarchar(40)", maxLength: 40, nullable: true), CreationTime = table.Column<DateTime>(type: "datetime2", nullable: false), CreatorId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), LastModificationTime = table.Column<DateTime>(type: "datetime2", nullable: true), LastModifierId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), IsDeleted = table.Column<bool>(type: "bit", nullable: false, defaultValue: false), DeleterId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), DeletionTime = table.Column<DateTime>(type: "datetime2", nullable: true) }, constraints: table => { table.PrimaryKey("PK_WeChatApps", x => x.Id); }); migrationBuilder.CreateTable( name: "WeChatAppUsers", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), TenantId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), WeChatAppId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), UserId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), UnionId = table.Column<string>(type: "nvarchar(max)", nullable: true), OpenId = table.Column<string>(type: "nvarchar(max)", nullable: true), SessionKey = table.Column<string>(type: "nvarchar(max)", nullable: true), SessionKeyChangedTime = table.Column<DateTime>(type: "datetime2", nullable: true), ExtraProperties = table.Column<string>(type: "nvarchar(max)", nullable: true), ConcurrencyStamp = table.Column<string>(type: "nvarchar(40)", maxLength: 40, nullable: true), CreationTime = table.Column<DateTime>(type: "datetime2", nullable: false), CreatorId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), LastModificationTime = table.Column<DateTime>(type: "datetime2", nullable: true), LastModifierId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), IsDeleted = table.Column<bool>(type: "bit", nullable: false, defaultValue: false), DeleterId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), DeletionTime = table.Column<DateTime>(type: "datetime2", nullable: true) }, constraints: table => { table.PrimaryKey("PK_WeChatAppUsers", x => x.Id); }); migrationBuilder.CreateTable( name: "WeChatUserInfos", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), TenantId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), UserId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), NickName = table.Column<string>(type: "nvarchar(max)", nullable: true), Gender = table.Column<byte>(type: "tinyint", nullable: false), Language = table.Column<string>(type: "nvarchar(max)", nullable: true), City = table.Column<string>(type: "nvarchar(max)", nullable: true), Province = table.Column<string>(type: "nvarchar(max)", nullable: true), Country = table.Column<string>(type: "nvarchar(max)", nullable: true), AvatarUrl = table.Column<string>(type: "nvarchar(max)", nullable: true), ExtraProperties = table.Column<string>(type: "nvarchar(max)", nullable: true), ConcurrencyStamp = table.Column<string>(type: "nvarchar(40)", maxLength: 40, nullable: true), CreationTime = table.Column<DateTime>(type: "datetime2", nullable: false), CreatorId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), LastModificationTime = table.Column<DateTime>(type: "datetime2", nullable: true), LastModifierId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), IsDeleted = table.Column<bool>(type: "bit", nullable: false, defaultValue: false), DeleterId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), DeletionTime = table.Column<DateTime>(type: "datetime2", nullable: true) }, constraints: table => { table.PrimaryKey("PK_WeChatUserInfos", x => x.Id); }); migrationBuilder.CreateTable( name: "AbpAuditLogActions", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), TenantId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), AuditLogId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), ServiceName = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true), MethodName = table.Column<string>(type: "nvarchar(128)", maxLength: 128, nullable: true), Parameters = table.Column<string>(type: "nvarchar(2000)", maxLength: 2000, nullable: true), ExecutionTime = table.Column<DateTime>(type: "datetime2", nullable: false), ExecutionDuration = table.Column<int>(type: "int", nullable: false), ExtraProperties = table.Column<string>(type: "nvarchar(max)", nullable: true) }, constraints: table => { table.PrimaryKey("PK_AbpAuditLogActions", x => x.Id); table.ForeignKey( name: "FK_AbpAuditLogActions_AbpAuditLogs_AuditLogId", column: x => x.AuditLogId, principalTable: "AbpAuditLogs", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AbpEntityChanges", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), AuditLogId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), TenantId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), ChangeTime = table.Column<DateTime>(type: "datetime2", nullable: false), ChangeType = table.Column<byte>(type: "tinyint", nullable: false), EntityTenantId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), EntityId = table.Column<string>(type: "nvarchar(128)", maxLength: 128, nullable: false), EntityTypeFullName = table.Column<string>(type: "nvarchar(128)", maxLength: 128, nullable: false), ExtraProperties = table.Column<string>(type: "nvarchar(max)", nullable: true) }, constraints: table => { table.PrimaryKey("PK_AbpEntityChanges", x => x.Id); table.ForeignKey( name: "FK_AbpEntityChanges_AbpAuditLogs_AuditLogId", column: x => x.AuditLogId, principalTable: "AbpAuditLogs", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AbpOrganizationUnitRoles", columns: table => new { RoleId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), OrganizationUnitId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), TenantId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), CreationTime = table.Column<DateTime>(type: "datetime2", nullable: false), CreatorId = table.Column<Guid>(type: "uniqueidentifier", nullable: true) }, constraints: table => { table.PrimaryKey("PK_AbpOrganizationUnitRoles", x => new { x.OrganizationUnitId, x.RoleId }); table.ForeignKey( name: "FK_AbpOrganizationUnitRoles_AbpOrganizationUnits_OrganizationUnitId", column: x => x.OrganizationUnitId, principalTable: "AbpOrganizationUnits", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_AbpOrganizationUnitRoles_AbpRoles_RoleId", column: x => x.RoleId, principalTable: "AbpRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AbpRoleClaims", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), RoleId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), TenantId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), ClaimType = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: false), ClaimValue = table.Column<string>(type: "nvarchar(1024)", maxLength: 1024, nullable: true) }, constraints: table => { table.PrimaryKey("PK_AbpRoleClaims", x => x.Id); table.ForeignKey( name: "FK_AbpRoleClaims_AbpRoles_RoleId", column: x => x.RoleId, principalTable: "AbpRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AbpTenantConnectionStrings", columns: table => new { TenantId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), Name = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: false), Value = table.Column<string>(type: "nvarchar(1024)", maxLength: 1024, nullable: false) }, constraints: table => { table.PrimaryKey("PK_AbpTenantConnectionStrings", x => new { x.TenantId, x.Name }); table.ForeignKey( name: "FK_AbpTenantConnectionStrings_AbpTenants_TenantId", column: x => x.TenantId, principalTable: "AbpTenants", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AbpUserClaims", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), UserId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), TenantId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), ClaimType = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: false), ClaimValue = table.Column<string>(type: "nvarchar(1024)", maxLength: 1024, nullable: true) }, constraints: table => { table.PrimaryKey("PK_AbpUserClaims", x => x.Id); table.ForeignKey( name: "FK_AbpUserClaims_AbpUsers_UserId", column: x => x.UserId, principalTable: "AbpUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AbpUserLogins", columns: table => new { UserId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), LoginProvider = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: false), TenantId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), ProviderKey = table.Column<string>(type: "nvarchar(196)", maxLength: 196, nullable: false), ProviderDisplayName = table.Column<string>(type: "nvarchar(128)", maxLength: 128, nullable: true) }, constraints: table => { table.PrimaryKey("PK_AbpUserLogins", x => new { x.UserId, x.LoginProvider }); table.ForeignKey( name: "FK_AbpUserLogins_AbpUsers_UserId", column: x => x.UserId, principalTable: "AbpUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AbpUserOrganizationUnits", columns: table => new { UserId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), OrganizationUnitId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), TenantId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), CreationTime = table.Column<DateTime>(type: "datetime2", nullable: false), CreatorId = table.Column<Guid>(type: "uniqueidentifier", nullable: true) }, constraints: table => { table.PrimaryKey("PK_AbpUserOrganizationUnits", x => new { x.OrganizationUnitId, x.UserId }); table.ForeignKey( name: "FK_AbpUserOrganizationUnits_AbpOrganizationUnits_OrganizationUnitId", column: x => x.OrganizationUnitId, principalTable: "AbpOrganizationUnits", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_AbpUserOrganizationUnits_AbpUsers_UserId", column: x => x.UserId, principalTable: "AbpUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AbpUserRoles", columns: table => new { UserId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), RoleId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), TenantId = table.Column<Guid>(type: "uniqueidentifier", nullable: true) }, constraints: table => { table.PrimaryKey("PK_AbpUserRoles", x => new { x.UserId, x.RoleId }); table.ForeignKey( name: "FK_AbpUserRoles_AbpRoles_RoleId", column: x => x.RoleId, principalTable: "AbpRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_AbpUserRoles_AbpUsers_UserId", column: x => x.UserId, principalTable: "AbpUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AbpUserTokens", columns: table => new { UserId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), LoginProvider = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: false), Name = table.Column<string>(type: "nvarchar(128)", maxLength: 128, nullable: false), TenantId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), Value = table.Column<string>(type: "nvarchar(max)", nullable: true) }, constraints: table => { table.PrimaryKey("PK_AbpUserTokens", x => new { x.UserId, x.LoginProvider, x.Name }); table.ForeignKey( name: "FK_AbpUserTokens_AbpUsers_UserId", column: x => x.UserId, principalTable: "AbpUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "IdentityServerApiResourceClaims", columns: table => new { Type = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: false), ApiResourceId = table.Column<Guid>(type: "uniqueidentifier", nullable: false) }, constraints: table => { table.PrimaryKey("PK_IdentityServerApiResourceClaims", x => new { x.ApiResourceId, x.Type }); table.ForeignKey( name: "FK_IdentityServerApiResourceClaims_IdentityServerApiResources_ApiResourceId", column: x => x.ApiResourceId, principalTable: "IdentityServerApiResources", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "IdentityServerApiResourceProperties", columns: table => new { ApiResourceId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), Key = table.Column<string>(type: "nvarchar(250)", maxLength: 250, nullable: false), Value = table.Column<string>(type: "nvarchar(2000)", maxLength: 2000, nullable: false) }, constraints: table => { table.PrimaryKey("PK_IdentityServerApiResourceProperties", x => new { x.ApiResourceId, x.Key, x.Value }); table.ForeignKey( name: "FK_IdentityServerApiResourceProperties_IdentityServerApiResources_ApiResourceId", column: x => x.ApiResourceId, principalTable: "IdentityServerApiResources", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "IdentityServerApiResourceScopes", columns: table => new { ApiResourceId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), Scope = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: false) }, constraints: table => { table.PrimaryKey("PK_IdentityServerApiResourceScopes", x => new { x.ApiResourceId, x.Scope }); table.ForeignKey( name: "FK_IdentityServerApiResourceScopes_IdentityServerApiResources_ApiResourceId", column: x => x.ApiResourceId, principalTable: "IdentityServerApiResources", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "IdentityServerApiResourceSecrets", columns: table => new { Type = table.Column<string>(type: "nvarchar(250)", maxLength: 250, nullable: false), Value = table.Column<string>(type: "nvarchar(4000)", maxLength: 4000, nullable: false), ApiResourceId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), Description = table.Column<string>(type: "nvarchar(1000)", maxLength: 1000, nullable: true), Expiration = table.Column<DateTime>(type: "datetime2", nullable: true) }, constraints: table => { table.PrimaryKey("PK_IdentityServerApiResourceSecrets", x => new { x.ApiResourceId, x.Type, x.Value }); table.ForeignKey( name: "FK_IdentityServerApiResourceSecrets_IdentityServerApiResources_ApiResourceId", column: x => x.ApiResourceId, principalTable: "IdentityServerApiResources", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "IdentityServerApiScopeClaims", columns: table => new { Type = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: false), ApiScopeId = table.Column<Guid>(type: "uniqueidentifier", nullable: false) }, constraints: table => { table.PrimaryKey("PK_IdentityServerApiScopeClaims", x => new { x.ApiScopeId, x.Type }); table.ForeignKey( name: "FK_IdentityServerApiScopeClaims_IdentityServerApiScopes_ApiScopeId", column: x => x.ApiScopeId, principalTable: "IdentityServerApiScopes", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "IdentityServerApiScopeProperties", columns: table => new { ApiScopeId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), Key = table.Column<string>(type: "nvarchar(250)", maxLength: 250, nullable: false), Value = table.Column<string>(type: "nvarchar(2000)", maxLength: 2000, nullable: false) }, constraints: table => { table.PrimaryKey("PK_IdentityServerApiScopeProperties", x => new { x.ApiScopeId, x.Key, x.Value }); table.ForeignKey( name: "FK_IdentityServerApiScopeProperties_IdentityServerApiScopes_ApiScopeId", column: x => x.ApiScopeId, principalTable: "IdentityServerApiScopes", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "IdentityServerClientClaims", columns: table => new { ClientId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), Type = table.Column<string>(type: "nvarchar(250)", maxLength: 250, nullable: false), Value = table.Column<string>(type: "nvarchar(250)", maxLength: 250, nullable: false) }, constraints: table => { table.PrimaryKey("PK_IdentityServerClientClaims", x => new { x.ClientId, x.Type, x.Value }); table.ForeignKey( name: "FK_IdentityServerClientClaims_IdentityServerClients_ClientId", column: x => x.ClientId, principalTable: "IdentityServerClients", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "IdentityServerClientCorsOrigins", columns: table => new { ClientId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), Origin = table.Column<string>(type: "nvarchar(150)", maxLength: 150, nullable: false) }, constraints: table => { table.PrimaryKey("PK_IdentityServerClientCorsOrigins", x => new { x.ClientId, x.Origin }); table.ForeignKey( name: "FK_IdentityServerClientCorsOrigins_IdentityServerClients_ClientId", column: x => x.ClientId, principalTable: "IdentityServerClients", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "IdentityServerClientGrantTypes", columns: table => new { ClientId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), GrantType = table.Column<string>(type: "nvarchar(250)", maxLength: 250, nullable: false) }, constraints: table => { table.PrimaryKey("PK_IdentityServerClientGrantTypes", x => new { x.ClientId, x.GrantType }); table.ForeignKey( name: "FK_IdentityServerClientGrantTypes_IdentityServerClients_ClientId", column: x => x.ClientId, principalTable: "IdentityServerClients", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "IdentityServerClientIdPRestrictions", columns: table => new { ClientId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), Provider = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: false) }, constraints: table => { table.PrimaryKey("PK_IdentityServerClientIdPRestrictions", x => new { x.ClientId, x.Provider }); table.ForeignKey( name: "FK_IdentityServerClientIdPRestrictions_IdentityServerClients_ClientId", column: x => x.ClientId, principalTable: "IdentityServerClients", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "IdentityServerClientPostLogoutRedirectUris", columns: table => new { ClientId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), PostLogoutRedirectUri = table.Column<string>(type: "nvarchar(2000)", maxLength: 2000, nullable: false) }, constraints: table => { table.PrimaryKey("PK_IdentityServerClientPostLogoutRedirectUris", x => new { x.ClientId, x.PostLogoutRedirectUri }); table.ForeignKey( name: "FK_IdentityServerClientPostLogoutRedirectUris_IdentityServerClients_ClientId", column: x => x.ClientId, principalTable: "IdentityServerClients", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "IdentityServerClientProperties", columns: table => new { ClientId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), Key = table.Column<string>(type: "nvarchar(250)", maxLength: 250, nullable: false), Value = table.Column<string>(type: "nvarchar(2000)", maxLength: 2000, nullable: false) }, constraints: table => { table.PrimaryKey("PK_IdentityServerClientProperties", x => new { x.ClientId, x.Key, x.Value }); table.ForeignKey( name: "FK_IdentityServerClientProperties_IdentityServerClients_ClientId", column: x => x.ClientId, principalTable: "IdentityServerClients", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "IdentityServerClientRedirectUris", columns: table => new { ClientId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), RedirectUri = table.Column<string>(type: "nvarchar(2000)", maxLength: 2000, nullable: false) }, constraints: table => { table.PrimaryKey("PK_IdentityServerClientRedirectUris", x => new { x.ClientId, x.RedirectUri }); table.ForeignKey( name: "FK_IdentityServerClientRedirectUris_IdentityServerClients_ClientId", column: x => x.ClientId, principalTable: "IdentityServerClients", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "IdentityServerClientScopes", columns: table => new { ClientId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), Scope = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: false) }, constraints: table => { table.PrimaryKey("PK_IdentityServerClientScopes", x => new { x.ClientId, x.Scope }); table.ForeignKey( name: "FK_IdentityServerClientScopes_IdentityServerClients_ClientId", column: x => x.ClientId, principalTable: "IdentityServerClients", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "IdentityServerClientSecrets", columns: table => new { Type = table.Column<string>(type: "nvarchar(250)", maxLength: 250, nullable: false), Value = table.Column<string>(type: "nvarchar(4000)", maxLength: 4000, nullable: false), ClientId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), Description = table.Column<string>(type: "nvarchar(2000)", maxLength: 2000, nullable: true), Expiration = table.Column<DateTime>(type: "datetime2", nullable: true) }, constraints: table => { table.PrimaryKey("PK_IdentityServerClientSecrets", x => new { x.ClientId, x.Type, x.Value }); table.ForeignKey( name: "FK_IdentityServerClientSecrets_IdentityServerClients_ClientId", column: x => x.ClientId, principalTable: "IdentityServerClients", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "IdentityServerIdentityResourceClaims", columns: table => new { Type = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: false), IdentityResourceId = table.Column<Guid>(type: "uniqueidentifier", nullable: false) }, constraints: table => { table.PrimaryKey("PK_IdentityServerIdentityResourceClaims", x => new { x.IdentityResourceId, x.Type }); table.ForeignKey( name: "FK_IdentityServerIdentityResourceClaims_IdentityServerIdentityResources_IdentityResourceId", column: x => x.IdentityResourceId, principalTable: "IdentityServerIdentityResources", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "IdentityServerIdentityResourceProperties", columns: table => new { IdentityResourceId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), Key = table.Column<string>(type: "nvarchar(250)", maxLength: 250, nullable: false), Value = table.Column<string>(type: "nvarchar(2000)", maxLength: 2000, nullable: false) }, constraints: table => { table.PrimaryKey("PK_IdentityServerIdentityResourceProperties", x => new { x.IdentityResourceId, x.Key, x.Value }); table.ForeignKey( name: "FK_IdentityServerIdentityResourceProperties_IdentityServerIdentityResources_IdentityResourceId", column: x => x.IdentityResourceId, principalTable: "IdentityServerIdentityResources", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AbpEntityPropertyChanges", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), TenantId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), EntityChangeId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), NewValue = table.Column<string>(type: "nvarchar(512)", maxLength: 512, nullable: true), OriginalValue = table.Column<string>(type: "nvarchar(512)", maxLength: 512, nullable: true), PropertyName = table.Column<string>(type: "nvarchar(128)", maxLength: 128, nullable: false), PropertyTypeFullName = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: false) }, constraints: table => { table.PrimaryKey("PK_AbpEntityPropertyChanges", x => x.Id); table.ForeignKey( name: "FK_AbpEntityPropertyChanges_AbpEntityChanges_EntityChangeId", column: x => x.EntityChangeId, principalTable: "AbpEntityChanges", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_AbpAuditLogActions_AuditLogId", table: "AbpAuditLogActions", column: "AuditLogId"); migrationBuilder.CreateIndex( name: "IX_AbpAuditLogActions_TenantId_ServiceName_MethodName_ExecutionTime", table: "AbpAuditLogActions", columns: new[] { "TenantId", "ServiceName", "MethodName", "ExecutionTime" }); migrationBuilder.CreateIndex( name: "IX_AbpAuditLogs_TenantId_ExecutionTime", table: "AbpAuditLogs", columns: new[] { "TenantId", "ExecutionTime" }); migrationBuilder.CreateIndex( name: "IX_AbpAuditLogs_TenantId_UserId_ExecutionTime", table: "AbpAuditLogs", columns: new[] { "TenantId", "UserId", "ExecutionTime" }); migrationBuilder.CreateIndex( name: "IX_AbpBackgroundJobs_IsAbandoned_NextTryTime", table: "AbpBackgroundJobs", columns: new[] { "IsAbandoned", "NextTryTime" }); migrationBuilder.CreateIndex( name: "IX_AbpEntityChanges_AuditLogId", table: "AbpEntityChanges", column: "AuditLogId"); migrationBuilder.CreateIndex( name: "IX_AbpEntityChanges_TenantId_EntityTypeFullName_EntityId", table: "AbpEntityChanges", columns: new[] { "TenantId", "EntityTypeFullName", "EntityId" }); migrationBuilder.CreateIndex( name: "IX_AbpEntityPropertyChanges_EntityChangeId", table: "AbpEntityPropertyChanges", column: "EntityChangeId"); migrationBuilder.CreateIndex( name: "IX_AbpFeatureValues_Name_ProviderName_ProviderKey", table: "AbpFeatureValues", columns: new[] { "Name", "ProviderName", "ProviderKey" }); migrationBuilder.CreateIndex( name: "IX_AbpLinkUsers_SourceUserId_SourceTenantId_TargetUserId_TargetTenantId", table: "AbpLinkUsers", columns: new[] { "SourceUserId", "SourceTenantId", "TargetUserId", "TargetTenantId" }, unique: true, filter: "[SourceTenantId] IS NOT NULL AND [TargetTenantId] IS NOT NULL"); migrationBuilder.CreateIndex( name: "IX_AbpOrganizationUnitRoles_RoleId_OrganizationUnitId", table: "AbpOrganizationUnitRoles", columns: new[] { "RoleId", "OrganizationUnitId" }); migrationBuilder.CreateIndex( name: "IX_AbpOrganizationUnits_Code", table: "AbpOrganizationUnits", column: "Code"); migrationBuilder.CreateIndex( name: "IX_AbpOrganizationUnits_ParentId", table: "AbpOrganizationUnits", column: "ParentId"); migrationBuilder.CreateIndex( name: "IX_AbpPermissionGrants_Name_ProviderName_ProviderKey", table: "AbpPermissionGrants", columns: new[] { "Name", "ProviderName", "ProviderKey" }); migrationBuilder.CreateIndex( name: "IX_AbpRoleClaims_RoleId", table: "AbpRoleClaims", column: "RoleId"); migrationBuilder.CreateIndex( name: "IX_AbpRoles_NormalizedName", table: "AbpRoles", column: "NormalizedName"); migrationBuilder.CreateIndex( name: "IX_AbpSecurityLogs_TenantId_Action", table: "AbpSecurityLogs", columns: new[] { "TenantId", "Action" }); migrationBuilder.CreateIndex( name: "IX_AbpSecurityLogs_TenantId_ApplicationName", table: "AbpSecurityLogs", columns: new[] { "TenantId", "ApplicationName" }); migrationBuilder.CreateIndex( name: "IX_AbpSecurityLogs_TenantId_Identity", table: "AbpSecurityLogs", columns: new[] { "TenantId", "Identity" }); migrationBuilder.CreateIndex( name: "IX_AbpSecurityLogs_TenantId_UserId", table: "AbpSecurityLogs", columns: new[] { "TenantId", "UserId" }); migrationBuilder.CreateIndex( name: "IX_AbpSettings_Name_ProviderName_ProviderKey", table: "AbpSettings", columns: new[] { "Name", "ProviderName", "ProviderKey" }); migrationBuilder.CreateIndex( name: "IX_AbpTenants_Name", table: "AbpTenants", column: "Name"); migrationBuilder.CreateIndex( name: "IX_AbpUserClaims_UserId", table: "AbpUserClaims", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AbpUserLogins_LoginProvider_ProviderKey", table: "AbpUserLogins", columns: new[] { "LoginProvider", "ProviderKey" }); migrationBuilder.CreateIndex( name: "IX_AbpUserOrganizationUnits_UserId_OrganizationUnitId", table: "AbpUserOrganizationUnits", columns: new[] { "UserId", "OrganizationUnitId" }); migrationBuilder.CreateIndex( name: "IX_AbpUserRoles_RoleId_UserId", table: "AbpUserRoles", columns: new[] { "RoleId", "UserId" }); migrationBuilder.CreateIndex( name: "IX_AbpUsers_Email", table: "AbpUsers", column: "Email"); migrationBuilder.CreateIndex( name: "IX_AbpUsers_NormalizedEmail", table: "AbpUsers", column: "NormalizedEmail"); migrationBuilder.CreateIndex( name: "IX_AbpUsers_NormalizedUserName", table: "AbpUsers", column: "NormalizedUserName"); migrationBuilder.CreateIndex( name: "IX_AbpUsers_UserName", table: "AbpUsers", column: "UserName"); migrationBuilder.CreateIndex( name: "IX_IdentityServerClients_ClientId", table: "IdentityServerClients", column: "ClientId"); migrationBuilder.CreateIndex( name: "IX_IdentityServerDeviceFlowCodes_DeviceCode", table: "IdentityServerDeviceFlowCodes", column: "DeviceCode", unique: true); migrationBuilder.CreateIndex( name: "IX_IdentityServerDeviceFlowCodes_Expiration", table: "IdentityServerDeviceFlowCodes", column: "Expiration"); migrationBuilder.CreateIndex( name: "IX_IdentityServerDeviceFlowCodes_UserCode", table: "IdentityServerDeviceFlowCodes", column: "UserCode"); migrationBuilder.CreateIndex( name: "IX_IdentityServerPersistedGrants_Expiration", table: "IdentityServerPersistedGrants", column: "Expiration"); migrationBuilder.CreateIndex( name: "IX_IdentityServerPersistedGrants_SubjectId_ClientId_Type", table: "IdentityServerPersistedGrants", columns: new[] { "SubjectId", "ClientId", "Type" }); migrationBuilder.CreateIndex( name: "IX_IdentityServerPersistedGrants_SubjectId_SessionId_Type", table: "IdentityServerPersistedGrants", columns: new[] { "SubjectId", "SessionId", "Type" }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "AbpAuditLogActions"); migrationBuilder.DropTable( name: "AbpBackgroundJobs"); migrationBuilder.DropTable( name: "AbpClaimTypes"); migrationBuilder.DropTable( name: "AbpEntityPropertyChanges"); migrationBuilder.DropTable( name: "AbpFeatureValues"); migrationBuilder.DropTable( name: "AbpLinkUsers"); migrationBuilder.DropTable( name: "AbpOrganizationUnitRoles"); migrationBuilder.DropTable( name: "AbpPermissionGrants"); migrationBuilder.DropTable( name: "AbpRoleClaims"); migrationBuilder.DropTable( name: "AbpSecurityLogs"); migrationBuilder.DropTable( name: "AbpSettings"); migrationBuilder.DropTable( name: "AbpTenantConnectionStrings"); migrationBuilder.DropTable( name: "AbpUserClaims"); migrationBuilder.DropTable( name: "AbpUserLogins"); migrationBuilder.DropTable( name: "AbpUserOrganizationUnits"); migrationBuilder.DropTable( name: "AbpUserRoles"); migrationBuilder.DropTable( name: "AbpUserTenants"); migrationBuilder.DropTable( name: "AbpUserTokens"); migrationBuilder.DropTable( name: "IdentityServerApiResourceClaims"); migrationBuilder.DropTable( name: "IdentityServerApiResourceProperties"); migrationBuilder.DropTable( name: "IdentityServerApiResourceScopes"); migrationBuilder.DropTable( name: "IdentityServerApiResourceSecrets"); migrationBuilder.DropTable( name: "IdentityServerApiScopeClaims"); migrationBuilder.DropTable( name: "IdentityServerApiScopeProperties"); migrationBuilder.DropTable( name: "IdentityServerClientClaims"); migrationBuilder.DropTable( name: "IdentityServerClientCorsOrigins"); migrationBuilder.DropTable( name: "IdentityServerClientGrantTypes"); migrationBuilder.DropTable( name: "IdentityServerClientIdPRestrictions"); migrationBuilder.DropTable( name: "IdentityServerClientPostLogoutRedirectUris"); migrationBuilder.DropTable( name: "IdentityServerClientProperties"); migrationBuilder.DropTable( name: "IdentityServerClientRedirectUris"); migrationBuilder.DropTable( name: "IdentityServerClientScopes"); migrationBuilder.DropTable( name: "IdentityServerClientSecrets"); migrationBuilder.DropTable( name: "IdentityServerDeviceFlowCodes"); migrationBuilder.DropTable( name: "IdentityServerIdentityResourceClaims"); migrationBuilder.DropTable( name: "IdentityServerIdentityResourceProperties"); migrationBuilder.DropTable( name: "IdentityServerPersistedGrants"); migrationBuilder.DropTable( name: "WeChatApps"); migrationBuilder.DropTable( name: "WeChatAppUsers"); migrationBuilder.DropTable( name: "WeChatUserInfos"); migrationBuilder.DropTable( name: "AbpEntityChanges"); migrationBuilder.DropTable( name: "AbpTenants"); migrationBuilder.DropTable( name: "AbpOrganizationUnits"); migrationBuilder.DropTable( name: "AbpRoles"); migrationBuilder.DropTable( name: "AbpUsers"); migrationBuilder.DropTable( name: "IdentityServerApiResources"); migrationBuilder.DropTable( name: "IdentityServerApiScopes"); migrationBuilder.DropTable( name: "IdentityServerClients"); migrationBuilder.DropTable( name: "IdentityServerIdentityResources"); migrationBuilder.DropTable( name: "AbpAuditLogs"); } } }
57.044385
136
0.543495
[ "MIT" ]
zhangke4300/WeChatManagement
samples/WeChatManagementSample/aspnet-core/src/WeChatManagementSample.EntityFrameworkCore/Migrations/20210830034622_init.cs
84,827
C#
/// ETML /// Author: Gil Balsiger /// Date: 18.05.2018 /// Summary: Handles the weapons spawning using UnityEngine; using UnityEngine.Networking; /// <summary> /// Handles the weapons spawning /// </summary> public class WeaponSpawner : NetworkBehaviour { /// <summary> /// Different weapons to instantiate randomly /// </summary> [SerializeField] private Weapon[] weaponsPrefab; /// <summary> /// Spawn weapons /// </summary> [Command] public void CmdSpawnWeapons() { Debug.Log("Spawning weapons !"); for (int i = 0; i < transform.childCount; i++) { Weapon weaponToSpawn = weaponsPrefab[Random.Range(0, weaponsPrefab.Length)]; Weapon weaponInstance = Instantiate(weaponToSpawn, transform.GetChild(i).transform); NetworkServer.Spawn(weaponInstance.gameObject); } } /// <summary> /// Debug spawn of weapons /// </summary> private void Update() { if (hasAuthority && Input.GetKeyDown(KeyCode.G)) { CmdSpawnWeapons(); } } }
23.847826
96
0.606199
[ "Apache-2.0" ]
balsigergil/Oxynite
Assets/Scripts/Weapons/WeaponSpawner.cs
1,099
C#
using Orleans.Serialization.Codecs; using Orleans.Serialization; using Orleans.Serialization.GeneratedCodeHelpers; using Orleans.Serialization.Serializers; using Orleans.Serialization.Buffers; using Orleans.Serialization.WireProtocol; using Orleans.Serialization.Cloning; using System.Net; using System; using System.Buffers; using System.Runtime.CompilerServices; namespace Orleans.Runtime.Serialization { /// <summary> /// Serializer and deserializer for <see cref="SiloAddress"/> instances. /// </summary> [RegisterSerializer] [RegisterCopier] public sealed class SiloAddressCodec : IFieldCodec<SiloAddress>, IDeepCopier<SiloAddress> { private static readonly Type _iPEndPointType = typeof(IPEndPoint); private static readonly Type _int32Type = typeof(int); private static readonly Type _codecFieldType = typeof(SiloAddress); /// <inheritdoc /> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, SiloAddress value) where TBufferWriter : IBufferWriter<byte> { if (value is null) { ReferenceCodec.WriteNullReference(ref writer, fieldIdDelta, expectedType); return; } ReferenceCodec.MarkValueField(writer.Session); writer.WriteStartObject(fieldIdDelta, expectedType, _codecFieldType); IPEndPointCodec.WriteField(ref writer, 0U, _iPEndPointType, value.Endpoint); Int32Codec.WriteField(ref writer, 1U, _int32Type, value.Generation); writer.WriteEndObject(); } /// <inheritdoc /> [MethodImpl(MethodImplOptions.AggressiveInlining)] public SiloAddress ReadValue<TReaderInput>(ref Reader<TReaderInput> reader, Field field) { if (field.WireType == WireType.Reference) { return ReferenceCodec.ReadReference<SiloAddress, TReaderInput>(ref reader, field); } ReferenceCodec.MarkValueField(reader.Session); int id = 0; Field header = default; IPEndPoint endpoint = default; int generation = default; while (true) { id = OrleansGeneratedCodeHelper.ReadHeader(ref reader, ref header, id); if (id == 0) { endpoint = IPEndPointCodec.ReadValue(ref reader, header); id = OrleansGeneratedCodeHelper.ReadHeader(ref reader, ref header, id); } if (id == 1) { generation = Int32Codec.ReadValue(ref reader, header); id = OrleansGeneratedCodeHelper.ReadHeaderExpectingEndBaseOrEndObject(ref reader, ref header, id); } if (id == -1) { break; } reader.ConsumeUnknownField(header); } return SiloAddress.New(endpoint, generation); } /// <inheritdoc /> public SiloAddress DeepCopy(SiloAddress input, CopyContext context) => input; } }
37.252874
178
0.622339
[ "MIT" ]
BearerPipelineTest/orleans
src/Orleans.Core.Abstractions/IDs/SiloAddressCodec.cs
3,241
C#
using System; using System.Collections.Generic; namespace EZOper.NetSiteUtilities.AopApi { /// <summary> /// AOP API: alipay.offline.marketing.voucher.offline /// </summary> public class AlipayOfflineMarketingVoucherOfflineRequest : IAopRequest<AlipayOfflineMarketingVoucherOfflineResponse> { /// <summary> /// 券下架 /// </summary> public string BizContent { get; set; } #region IAopRequest Members private bool needEncrypt=false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AopObject bizModel; public void SetNeedEncrypt(bool needEncrypt){ this.needEncrypt=needEncrypt; } public bool GetNeedEncrypt(){ return this.needEncrypt; } public void SetNotifyUrl(string notifyUrl){ this.notifyUrl = notifyUrl; } public string GetNotifyUrl(){ return this.notifyUrl; } public void SetReturnUrl(string returnUrl){ this.returnUrl = returnUrl; } public string GetReturnUrl(){ return this.returnUrl; } public void SetTerminalType(String terminalType){ this.terminalType=terminalType; } public string GetTerminalType(){ return this.terminalType; } public void SetTerminalInfo(String terminalInfo){ this.terminalInfo=terminalInfo; } public string GetTerminalInfo(){ return this.terminalInfo; } public void SetProdCode(String prodCode){ this.prodCode=prodCode; } public string GetProdCode(){ return this.prodCode; } public string GetApiName() { return "alipay.offline.marketing.voucher.offline"; } public void SetApiVersion(string apiVersion){ this.apiVersion=apiVersion; } public string GetApiVersion(){ return this.apiVersion; } public IDictionary<string, string> GetParameters() { AopDictionary parameters = new AopDictionary(); parameters.Add("biz_content", this.BizContent); return parameters; } public AopObject GetBizModel() { return this.bizModel; } public void SetBizModel(AopObject bizModel) { this.bizModel = bizModel; } #endregion } }
23.5
120
0.60735
[ "MIT" ]
erikzhouxin/CSharpSolution
NetSiteUtilities/AopApi/Request/AlipayOfflineMarketingVoucherOfflineRequest.cs
2,591
C#
namespace GameStore.Models.Games { public class GameShoppingCartViewModel { public int Id { get; init; } public string Name { get; init; } public string Publisher { get; init; } public string PegiRating { get; init; } public decimal Price { get; init; } public string ImageUrl { get; init; } } }
21.235294
47
0.595568
[ "MIT" ]
radostinatanasov98/GameStore
GameStore/GameStore/Models/Games/GameShoppingCartViewModel.cs
363
C#
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BookLibrary { class Program { static void Main() { string[] inputLines = File.ReadAllLines(@"..\..\input.txt"); int index = 0; File.WriteAllText(@"..\..\output.txt", ""); while (index < inputLines.Length) { Library myLibrary = new Library() { Name = "My books", Books = new List<Book>() }; int nums = int.Parse(inputLines[index]); for (int i = 0; i < nums; i++) { index++; myLibrary.Books.Add(ConvertInputToBook(inputLines[index])); } var result = new SortedDictionary<string, double>(); foreach (string autor in myLibrary.Books.Select(x => x.Autor).Distinct()) { double sum = myLibrary.Books.Where(x => x.Autor == autor).Sum(x => x.Price); result.Add(autor, sum); } foreach (var item in result.OrderByDescending(x => x.Value)) { File.AppendAllText(@"..\..\output.txt", $"{item.Key} -> {item.Value:0.00}" + Environment.NewLine); Console.WriteLine($"{item.Key} -> {item.Value:0.00}"); } File.AppendAllText(@"..\..\output.txt", Environment.NewLine); Console.WriteLine(); index++; } } private static Book ConvertInputToBook(string inputString) { string[] arr = inputString.Split(); Book book = new Book() { Title = arr[0], Autor = arr[1], Publisher = arr[2], ReleaseDate = DateTime.ParseExact(arr[3], "dd.MM.yyyy", CultureInfo.InvariantCulture), ISBN = int.Parse(arr[4]), Price = double.Parse(arr[5]) }; return book; } } public class Book { public string Title { get; set; } public string Autor { get; set; } public string Publisher { get; set; } public DateTime ReleaseDate { get; set; } public int ISBN { get; set; } public double Price { get; set; } } public class Library { public string Name { get; set; } public List<Book> Books { get; set; } } }
31.463415
118
0.489922
[ "MIT" ]
nikistoianov/TechMod-homeworks
FilesDirectoriesAndExceptions/BookLibrary/09.StartUp.cs
2,582
C#
using System; // ReSharper disable once CheckNamespace namespace NcnnDotNet.Layers { public sealed class BatchNorm : Layer { #region Constructors public BatchNorm() { NativeMethods.layer_layers_BatchNorm_new(out var ret); this.NativePtr = ret; } #endregion #region Methods #region Overrides /// <summary> /// Releases all unmanaged resources. /// </summary> protected override void DisposeUnmanaged() { // Suspend to call Layer.DisposeUnmanaged //base.DisposeUnmanaged(); if (this.NativePtr == IntPtr.Zero) return; NativeMethods.layer_layers_BatchNorm_delete(this.NativePtr); } #endregion #endregion } }
19.204545
72
0.559763
[ "MIT" ]
AvenSun/NcnnDotNet
src/NcnnDotNet/Layer/Layers/BatchNorm.cs
847
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the pinpoint-2016-12-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Pinpoint.Model { /// <summary> /// This is the response object from the DeleteUserEndpoints operation. /// </summary> public partial class DeleteUserEndpointsResponse : AmazonWebServiceResponse { private EndpointsResponse _endpointsResponse; /// <summary> /// Gets and sets the property EndpointsResponse. /// </summary> [AWSProperty(Required=true)] public EndpointsResponse EndpointsResponse { get { return this._endpointsResponse; } set { this._endpointsResponse = value; } } // Check to see if EndpointsResponse property is set internal bool IsSetEndpointsResponse() { return this._endpointsResponse != null; } } }
31.436364
107
0.666859
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/Pinpoint/Generated/Model/DeleteUserEndpointsResponse.cs
1,729
C#
using System; using System.Collections.Generic; using System.Linq; using BinarySerializer; using BinarySerializer.Ray1; using Sprite = UnityEngine.Sprite; namespace R1Engine { public class Unity_Object_R1Jaguar : Unity_SpriteObject { public Unity_Object_R1Jaguar(Unity_ObjectManager_R1Jaguar objManager, Pointer eventDefinitionPointer) { // Set properties ObjManager = objManager; EventDefinitionPointer = eventDefinitionPointer; // Set editor states RuntimeComplexStateIndex = ComplexStateIndex; RuntimeStateIndex = StateIndex; } public Unity_ObjectManager_R1Jaguar ObjManager { get; } public JAG_EventInstance Instance { get; set; } public override short XPosition { get; set; } public override short YPosition { get; set; } public override string DebugText => $"{nameof(Instance.Unk_00)}: {Instance?.Unk_00}{Environment.NewLine}" + $"{nameof(Instance.Unk_0A)}: {Instance?.Unk_0A}{Environment.NewLine}" + $"{nameof(Instance.EventIndex)}: {Instance?.EventIndex}{Environment.NewLine}" + $"{nameof(EventDefinitionPointer)}: {EventDefinitionPointer}{Environment.NewLine}" + $"IsComplex: {ObjManager.EventDefinitions[EventDefinitionIndex].Definition.ComplexData != null}{Environment.NewLine}" + $"CAR: {String.Join("-", ObjManager.EventDefinitions[EventDefinitionIndex].Definition.CarData ?? new byte[0])}{Environment.NewLine}" + $"Byte_25: {ObjManager.EventDefinitions[EventDefinitionIndex].Definition.Byte_25}{Environment.NewLine}" + $"Byte_26: {ObjManager.EventDefinitions[EventDefinitionIndex].Definition.Byte_26}{Environment.NewLine}" + $"{nameof(Instance.OffsetX)}: {Instance?.OffsetX}{Environment.NewLine}" + $"{nameof(Instance.OffsetY)}: {Instance?.OffsetY}{Environment.NewLine}"; public override bool CanBeLinkedToGroup => true; protected Pointer EventDefinitionPointer { get; set; } public int EventDefinitionIndex { get => ObjManager.EventDefinitions.FindIndex(x => x.Pointer == EventDefinitionPointer); set { if (value != EventDefinitionIndex) { ComplexStateIndex = RuntimeComplexStateIndex = 0; StateIndex = RuntimeStateIndex = 0; OverrideAnimIndex = null; EventDefinitionPointer = ObjManager.EventDefinitions[value].Pointer; } } } public byte RuntimeStateIndex { get; set; } public byte StateIndex { get; set; } public byte RuntimeComplexStateIndex { get; set; } public byte ComplexStateIndex { get; set; } public bool ForceNoAnimation { get; set; } public byte? ForceFrame { get; set; } public int LinkIndex { get; set; } public override Unity_ObjectType Type => ObjManager.EventDefinitions[EventDefinitionIndex].DisplayName == "MS_ge1" ? Unity_ObjectType.Trigger : Unity_ObjectType.Object; public Unity_ObjGraphics DES => ObjManager.EventDefinitions[EventDefinitionIndex].DES; public Unity_ObjectManager_R1Jaguar.State[][] ETA => ObjManager.EventDefinitions[EventDefinitionIndex].ETA; public Unity_ObjectManager_R1Jaguar.State State => ETA?.ElementAtOrDefault(RuntimeComplexStateIndex)?.ElementAtOrDefault(RuntimeStateIndex); public override BinarySerializable SerializableData => Instance; public override BaseLegacyEditorWrapper LegacyWrapper => new LegacyEditorWrapper(this); public override string PrimaryName => ObjManager.EventDefinitions[EventDefinitionIndex].DisplayName; public override string SecondaryName => null; public override Unity_ObjAnimation CurrentAnimation => DES.Animations.ElementAtOrDefault(AnimationIndex ?? -1); public override int AnimSpeed => (ForceNoAnimation ? 0 : State?.AnimSpeed ?? 1); public override int? GetAnimIndex => OverrideAnimIndex ?? State?.AnimationIndex; protected override int GetSpriteID => EventDefinitionIndex; public override IList<Sprite> Sprites => DES.Sprites; protected override bool ShouldUpdateFrame() { if (ForceFrame != null && ForceNoAnimation) { AnimationFrame = ForceFrame.Value; AnimationFrameFloat = ForceFrame.Value; return false; } return true; } private class LegacyEditorWrapper : BaseLegacyEditorWrapper { public LegacyEditorWrapper(Unity_Object_R1Jaguar obj) { Obj = obj; } private Unity_Object_R1Jaguar Obj { get; } public override int DES { get => Obj.EventDefinitionIndex; set => Obj.EventDefinitionIndex = value; } public override byte Etat { get => Obj.ComplexStateIndex; set => Obj.ComplexStateIndex = Obj.RuntimeComplexStateIndex = value; } public override byte SubEtat { get => Obj.StateIndex; set => Obj.StateIndex = Obj.RuntimeStateIndex = value; } public override int EtatLength => Obj.ObjManager.EventDefinitions.ElementAtOrDefault(Obj.EventDefinitionIndex)?.ETA.Length ?? 0; public override int SubEtatLength => Obj.ObjManager.EventDefinitions.ElementAtOrDefault(Obj.EventDefinitionIndex)?.ETA.ElementAtOrDefault(Obj.RuntimeComplexStateIndex)?.Length ?? 0; } #region UI States protected int UIStates_EventDefinitionIndex { get; set; } = -2; protected override bool IsUIStateArrayUpToDate => EventDefinitionIndex == UIStates_EventDefinitionIndex; protected class R1Jaguar_UIState : UIState { public R1Jaguar_UIState(string displayName, byte complexStateIndex, byte stateIndex) : base(displayName) { ComplexStateIndex = complexStateIndex; StateIndex = stateIndex; } public byte ComplexStateIndex { get; } public byte StateIndex { get; } public override void Apply(Unity_Object obj) { if (IsState) { var r1jo = obj as Unity_Object_R1Jaguar; r1jo.RuntimeComplexStateIndex = r1jo.ComplexStateIndex = ComplexStateIndex; r1jo.RuntimeStateIndex = r1jo.StateIndex = StateIndex; obj.OverrideAnimIndex = null; } else { obj.OverrideAnimIndex = AnimIndex; } } public override bool IsCurrentState(Unity_Object obj) { if (obj.OverrideAnimIndex.HasValue) return !IsState && AnimIndex == obj.OverrideAnimIndex; else return IsState && ComplexStateIndex == (obj as Unity_Object_R1Jaguar).RuntimeComplexStateIndex && StateIndex == (obj as Unity_Object_R1Jaguar).RuntimeStateIndex; } } protected override void RecalculateUIStates() { UIStates_EventDefinitionIndex = EventDefinitionIndex; //HashSet<int> usedAnims = new HashSet<int>(); List<UIState> uiStates = new List<UIState>(); var eta = ETA; if (eta != null) { for (byte i = 0; i < eta.Length; i++) { for (byte j = 0; j < eta[i].Length; j++) { if (eta[i][j].Name != null) { uiStates.Add(new R1Jaguar_UIState($"State {i}-{j}: {eta[i][j].Name}", i, j)); } else { uiStates.Add(new R1Jaguar_UIState($"State {i}-{j}", i, j)); } } } } UIStates = uiStates.ToArray(); } #endregion } }
45.668478
193
0.593002
[ "MIT" ]
Adsolution/Ray1Map
Assets/Scripts/DataTypes/Unity/LevelObj/Games/Rayman1_Jaguar/Unity_Object_R1Jaguar.cs
8,405
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BasicBoss : Enemy { [SerializeField] private float chargeTime; [SerializeField] private float turnTime; private BasicBossMode mode; private float currentModeTime; private Vector3 chargeDirection; protected override void Start() { base.Start(); mode = BasicBossMode.Charging; currentModeTime = chargeTime; chargeDirection = Vector3.Normalize(player.transform.position - transform.position); FacePlayer(); } protected override void Update() { currentModeTime -= Time.deltaTime; // Switch to the other mode if (currentModeTime <= 0) { if (mode == BasicBossMode.Charging) { mode = BasicBossMode.Turning; currentModeTime = turnTime; } else { mode = BasicBossMode.Charging; chargeDirection = Vector3.Normalize(player.transform.position - transform.position); currentModeTime = chargeTime; } } if (mode == BasicBossMode.Charging) { transform.position += chargeDirection * speed * Time.deltaTime; } else { FacePlayer(); } } } enum BasicBossMode { Charging, Turning, }
25.327273
100
0.590811
[ "MIT" ]
ashwingur/Turret-Spinner
TurretSpinner/Assets/Scripts/Enemies/BasicBoss.cs
1,393
C#
using UnityEngine; namespace ModComponentAPI { public class ModCookingPotComponent : ModComponent { [Tooltip("Can the item cook liquids?")] public bool CanCookLiquid; [Tooltip("Can the item cook grub? Cookable canned food counts as grub.")] public bool CanCookGrub; [Tooltip("Can the item cook meat?")] public bool CanCookMeat; [Range(0.0f, 10.0f)] [Tooltip("The total water capacity of the item.")] public float Capacity; [Tooltip("Template item to be used in the mapping process.")] public string Template; public Mesh SnowMesh; public Mesh WaterMesh; } }
28.25
81
0.632743
[ "MIT" ]
johnjollystupid/ModComponent
ModComponentAPI_Unity/VisualStudio/src/Components/ModCookingPotComponent.cs
680
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.Linq; using Cake.Cli; using Cake.Core; using Cake.Core.Diagnostics; using Cake.Core.IO; using Cake.Core.Packaging; using Microsoft.Extensions.DependencyInjection; using Spectre.Console.Cli; namespace Cake.Frosting.Internal { internal sealed class DefaultCommand : Command<DefaultCommandSettings> { private readonly IServiceCollection _services; public DefaultCommand(IServiceCollection services) { _services = services ?? throw new ArgumentNullException(nameof(services)); } public override int Execute(CommandContext context, DefaultCommandSettings settings) { // Register arguments var arguments = new CakeArguments(context.Remaining.Parsed); _services.AddSingleton<ICakeArguments>(arguments); _services.AddSingleton(context.Remaining); var provider = _services.BuildServiceProvider(); try { if (settings.Version) { // Show version var console = provider.GetRequiredService<IConsole>(); provider.GetRequiredService<VersionFeature>().Run(console); return 0; } else if (settings.Info) { // Show information var console = provider.GetRequiredService<IConsole>(); provider.GetRequiredService<InfoFeature>().Run(console); return 0; } // Set the log verbosity var log = provider.GetRequiredService<ICakeLog>(); log.Verbosity = settings.Verbosity; // Run var runner = GetFrostingEngine(provider, settings); // Install tools InstallTools(provider); // Set the working directory SetWorkingDirectory(provider, settings); if (settings.Exclusive) { runner.Settings.UseExclusiveTarget(); } runner.Run(settings.Target); } catch (Exception ex) { LogException(provider.GetService<ICakeLog>(), ex); return -1; } return 0; } private static int LogException<T>(ICakeLog log, T ex) where T : Exception { log = log ?? new CakeBuildLog( new CakeConsole(new CakeEnvironment(new CakePlatform(), new CakeRuntime()))); if (log.Verbosity == Verbosity.Diagnostic) { log.Error("Error: {0}", ex); } else { log.Error("Error: {0}", ex.Message); if (ex is AggregateException aex) { foreach (var exception in aex.Flatten().InnerExceptions) { log.Error("\t{0}", exception.Message); } } } return 1; } private void InstallTools(ServiceProvider provider) { var installer = provider.GetRequiredService<IToolInstaller>(); var tools = provider.GetServices<PackageReference>(); var log = provider.GetService<ICakeLog>(); // Install tools. if (tools.Any()) { log.Verbose("Installing tools..."); foreach (var tool in tools) { installer.Install(tool); } } } private void SetWorkingDirectory(ServiceProvider provider, DefaultCommandSettings settings) { var fileSystem = provider.GetRequiredService<IFileSystem>(); var environment = provider.GetRequiredService<ICakeEnvironment>(); var directory = settings.WorkingDirectory ?? provider.GetService<WorkingDirectory>()?.Path; directory = directory?.MakeAbsolute(environment) ?? environment.WorkingDirectory; if (!fileSystem.Exist(directory)) { throw new FrostingException($"The working directory '{directory.FullPath}' does not exist."); } environment.WorkingDirectory = directory; } private IFrostingEngine GetFrostingEngine(ServiceProvider provider, DefaultCommandSettings settings) { if (settings.DryRun) { return provider.GetRequiredService<FrostingDryRunner>(); } else if (settings.Tree) { return provider.GetRequiredService<FrostingTreeRunner>(); } else if (settings.Description) { return provider.GetRequiredService<FrostingDescriptionRunner>(); } else { return provider.GetRequiredService<FrostingRunner>(); } } } }
33.08125
109
0.542037
[ "MIT" ]
epaulsen/cake
src/Cake.Frosting/Internal/Commands/DefaultCommand.cs
5,295
C#
using System; namespace Validation.Validators { public class ObjectValidator { private const string DefaultError = "Invalid object."; private readonly object value; public ObjectValidator(object value) { this.value = value; } public ObjectValidator Be(object otherValue, string error = DefaultError, params object[] args) { Execute(() => value == otherValue, error, args); return this; } public ObjectValidator BeNull(string error = DefaultError, params object[] args) { Execute(() => GetValue<object>() == null, error, args); return this; } public ObjectValidator NotBe(object otherValue, string error = DefaultError, params object[] args) { Execute(() => value != otherValue, error, args); return this; } public ObjectValidator NotBeNull(string error = DefaultError, params object[] args) { Execute(() => GetValue<object>() != null, error, args); return this; } internal void Execute(Func<bool> validation, string error, params object[] args) { if (!validation.Invoke()) { Fail(error, args); } } protected static void Fail(string error, object[] args) { throw new ValidationException(string.Format(error, args)); } protected T GetValue<T>() { if (value == null) { return default; } if (value is T) { return (T)value; } return (T)Convert.ChangeType(value, typeof(T)); } } }
26.397059
106
0.519777
[ "Apache-2.0" ]
digovc/DirectValidation
src/validation/Validators/ObjectValidator.cs
1,797
C#
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Reliance.Core.Infrastructure; using Reliance.Core.Services.Infrastructure; using Reliance.Core.Services.Queries.DevOps; using Reliance.Web.Client; using SnowStorm.QueryExecutors; using System.Threading.Tasks; namespace Reliance.Core.Services.Domain.DevOps { public class App : ReferenceType { #region Properties #endregion //properties #region Methods internal static async Task<App> Create(IQueryExecutor executor, long organisationId, string name) { //validation - confirm app does not already exists if (string.IsNullOrWhiteSpace(name)) throw new ThisAppException(StatusCodes.Status417ExpectationFailed, Messages.Err417MissingObjectData("App")); var existingValue = await executor.Execute(new GetAppQuery(organisationId, name)); if (existingValue != null) throw new ThisAppException(StatusCodes.Status409Conflict, Messages.Err409ObjectExists("App")); //create new record var value = new App(organisationId, name); await executor.Add<App>(value); await executor.Save(); //return record return value; } private App(long organisationId, string name) : base(organisationId, name) { } #endregion //methods #region Configuration internal class Mapping : IEntityTypeConfiguration<App> { public void Configure(EntityTypeBuilder<App> builder) { builder.ToTable("App", "DevOps"); builder.HasKey(u => u.Id); // PK. builder.Property(p => p.Id).HasColumnName("Id"); builder.Property(p => p.Name).HasMaxLength(1024).IsRequired(); // TODO: Setup relationship objects } } #endregion //config } }
38.901961
124
0.635585
[ "MIT" ]
BenVanZyl/Reliance
src/Reliance.Core/Domain/DevOps/App.cs
1,986
C#
/* using System.Collections; using System.Collections.Generic; using UnityEngine; public class MovingObject : MonoBehaviour { public float moveTime = 0.1f; public LayerMask blockingLayer; private BoxCollider2D boxCollider; private Rigidbody2D rb2d; private float inverseMoveTime; public Component hitComponent; // Start is called before the first frame update protected virtual void Start() { boxCollider = GetComponent<BoxCollider2D>(); rb2d = GetComponent<Rigidbody2D>(); inverseMoveTime = 1f / moveTime; } protected bool Move (int xDir, int yDir, out RaycastHit2D hit) { Vector2 start = transform.position; Vector2 end = start + new Vector2(xDir, yDir); boxCollider.enabled = false; hit = Physics2D.Linecast(start, end, blockingLayer); boxCollider.enabled = true; if (hit.transform == null) { StartCoroutine(SmoothMovement(end)); return true; } return false; } protected IEnumerator SmoothMovement(Vector3 end) { float sqrRemainingDistance = (transform.position - end).sqrMagnitude; while (sqrRemainingDistance > float.Epsilon) { Vector3 newPosition = Vector3.MoveTowards(rb2d.position, end, inverseMoveTime * Time.deltaTime); rb2d.MovePosition(newPosition); sqrRemainingDistance = (transform.position - end).sqrMagnitude; yield return null; } } protected virtual void AttemptMove<T>(int xDir, int yDir) where T : Component { RaycastHit2D hit; bool canMove = Move(xDir, yDir, out hit); if (hit.transform == null) return T hitComponent = hit.transform.GetComponent<T>(); if (!canMove && hitComponent != null) OnCantMove(hitComponent); } protected abstract void OnCantMove <T>(T component) where T : Component; } */
25.87013
108
0.63253
[ "Unlicense" ]
BizarroKlyza/Spells-N-Shells
Assets/Scripts/Enemy movement/MovingObject.cs
1,994
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34014 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace ExcelVSTOSignalR.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "12.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
39.666667
151
0.583567
[ "MIT" ]
tanaka-takayoshi/VSTOSample
ExcelVSTOSignalR/ExcelVSTOSignalR/Properties/Settings.Designer.cs
1,073
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Naos.HubSpot.Domain.Contracts.ContactsApi.PayloadContracts { using Naos.HubSpot.Domain.Contracts.ContactsApi.QueryModels; public class CreateOrUpdateBatchContactsPayload { /// <summary> /// /// </summary> public IEnumerable<CreateOrUpdateContactPayload> Contacts { get; set; } /// <summary> /// /// </summary> /// <param name="contacts"></param> public CreateOrUpdateBatchContactsPayload(IEnumerable<CreateOrUpdateContactPayload> contacts) { Contacts = contacts; } } }
25.607143
101
0.651325
[ "MIT" ]
ghostofrecon/Naos.HubSpot
Naos.HubSpot.Domain/Contracts/ContactsApi/PayloadContracts/CreateOrUpdateBatchContactsPayload.cs
719
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/ShObjIdl_core.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace TerraFX.Interop { [Guid("D2BC4C84-3F72-4A52-A604-7BCBF3982CBB")] [NativeTypeName("struct INewWindowManager : IUnknown")] [NativeInheritance("IUnknown")] public unsafe partial struct INewWindowManager { public void** lpVtbl; [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(0)] [return: NativeTypeName("HRESULT")] public int QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject) { return ((delegate* unmanaged<INewWindowManager*, Guid*, void**, int>)(lpVtbl[0]))((INewWindowManager*)Unsafe.AsPointer(ref this), riid, ppvObject); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(1)] [return: NativeTypeName("ULONG")] public uint AddRef() { return ((delegate* unmanaged<INewWindowManager*, uint>)(lpVtbl[1]))((INewWindowManager*)Unsafe.AsPointer(ref this)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(2)] [return: NativeTypeName("ULONG")] public uint Release() { return ((delegate* unmanaged<INewWindowManager*, uint>)(lpVtbl[2]))((INewWindowManager*)Unsafe.AsPointer(ref this)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(3)] [return: NativeTypeName("HRESULT")] public int EvaluateNewWindow([NativeTypeName("LPCWSTR")] ushort* pszUrl, [NativeTypeName("LPCWSTR")] ushort* pszName, [NativeTypeName("LPCWSTR")] ushort* pszUrlContext, [NativeTypeName("LPCWSTR")] ushort* pszFeatures, [NativeTypeName("BOOL")] int fReplace, [NativeTypeName("DWORD")] uint dwFlags, [NativeTypeName("DWORD")] uint dwUserActionTime) { return ((delegate* unmanaged<INewWindowManager*, ushort*, ushort*, ushort*, ushort*, int, uint, uint, int>)(lpVtbl[3]))((INewWindowManager*)Unsafe.AsPointer(ref this), pszUrl, pszName, pszUrlContext, pszFeatures, fReplace, dwFlags, dwUserActionTime); } } }
46.692308
353
0.68575
[ "MIT" ]
DaZombieKiller/terrafx.interop.windows
sources/Interop/Windows/um/ShObjIdl_core/INewWindowManager.cs
2,430
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("TestLibraryConsume")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("TestLibraryConsume")] [assembly: AssemblyCopyright("Copyright © Microsoft 2014")] [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("10945fe7-65c9-42e6-b6df-e84a39078582")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.527778
84
0.754146
[ "MIT" ]
trafi/clickatell-csharp
TestLibraryConsume/Properties/AssemblyInfo.cs
1,390
C#
#pragma warning disable 0626 #pragma warning disable 0649 using UnityEngine; using System.Collections; using System.Collections.Generic; using ETGGUI; using System; public class ETGModGUI : MonoBehaviour { public enum MenuOpened { None, Loader, Logger, Console, Inspector }; private static MenuOpened _CurrentMenu = MenuOpened.None; public static MenuOpened CurrentMenu { get { return _CurrentMenu; } set { bool change = _CurrentMenu != value; if (change) { CurrentMenuInstance.OnClose(); } _CurrentMenu = value; if (change) { CurrentMenuInstance.OnOpen(); UpdateTimeScale(); UpdatePlayerState(); } } } public static GameObject MenuObject; public readonly static ETGModNullMenu NullMenu = new ETGModNullMenu(); public static ETGModLoaderMenu LoaderMenu; public static ETGModConsole ConsoleMenu; public static ETGModDebugLogMenu LoggerMenu; public static ETGModInspector InspectorMenu; public static float? StoredTimeScale = null; public static bool UseDamageIndicators = false; public static Texture2D TestTexture; public static IETGModMenu CurrentMenuInstance { get { switch (CurrentMenu) { case MenuOpened.Loader: return LoaderMenu; case MenuOpened.Console: return ConsoleMenu; case MenuOpened.Logger: return LoggerMenu; case MenuOpened.Inspector: return InspectorMenu; } return NullMenu; } } /// <summary> /// Creates a new object with this script on it. /// </summary> public static void Create() { if (MenuObject != null) { return; } MenuObject = new GameObject(); MenuObject.name = "ModLoaderMenu"; MenuObject.AddComponent<ETGModGUI>(); DontDestroyOnLoad(MenuObject); } public void Awake() { LoggerMenu = new ETGModDebugLogMenu(); LoaderMenu = new ETGModLoaderMenu(); ConsoleMenu = new ETGModConsole(); InspectorMenu = new ETGModInspector(); ETGDamageIndicatorGUI.Create(); } public static void Start() { TestTexture = Resources.Load<Texture2D>("test/texture"); LoggerMenu.Start(); LoaderMenu.Start(); ConsoleMenu.Start(); InspectorMenu.Start(); } public void Update() { if (Input.GetKeyDown(KeyCode.F1)) { if (CurrentMenu == MenuOpened.Loader) { CurrentMenu = MenuOpened.None; } else { CurrentMenu = MenuOpened.Loader; } UpdateTimeScale (); UpdatePlayerState(); } if (Input.GetKeyDown(KeyCode.F2) || Input.GetKeyDown(KeyCode.Slash) || Input.GetKeyDown(KeyCode.BackQuote)) { if (CurrentMenu == MenuOpened.Console) { CurrentMenu = MenuOpened.None; } else { CurrentMenu = MenuOpened.Console; } UpdateTimeScale(); UpdatePlayerState(); } if (Input.GetKeyDown(KeyCode.F3)) { if (CurrentMenu == MenuOpened.Logger) { CurrentMenu = MenuOpened.None; } else { CurrentMenu = MenuOpened.Logger; } } if (Input.GetKeyDown(KeyCode.F4)) { if (CurrentMenu == MenuOpened.Inspector) { CurrentMenu = MenuOpened.None; } else { CurrentMenu = MenuOpened.Inspector; } } if (CurrentMenu != MenuOpened.None && Input.GetKeyDown(KeyCode.Escape)) { CurrentMenu = MenuOpened.None; } CurrentMenuInstance.Update(); } public static void UpdateTimeScale() { if (StoredTimeScale.HasValue) { Time.timeScale = (float)StoredTimeScale; StoredTimeScale = null; } } public static void UpdatePlayerState() { if (GameManager.Instance?.PrimaryPlayer != null) { bool set = CurrentMenu == MenuOpened.None; GameManager.Instance.PrimaryPlayer.enabled = set; CameraController cam = Camera.main?.GetComponent<CameraController>(); if (cam != null) { cam.enabled = set; } } } // Font f; public void OnGUI() { if (ETGModGUI.CurrentMenu != ETGModGUI.MenuOpened.None) { if (!StoredTimeScale.HasValue) { StoredTimeScale = Time.timeScale; Time.timeScale = 0; } } CurrentMenuInstance.OnGUI(); //RandomSelector.OnGUI(); } internal static IEnumerator ListAllItemsAndGuns() { yield return new WaitForSeconds(1); int count = 0; while (PickupObjectDatabase.Instance == null) yield return new WaitForEndOfFrame(); for (int i = 0; i < PickupObjectDatabase.Instance.Objects.Count; i++) { PickupObject obj = PickupObjectDatabase.Instance.Objects[i]; if (obj==null) continue; if (obj.encounterTrackable==null) continue; if (obj.encounterTrackable.journalData==null) continue; string name = obj.encounterTrackable.journalData.GetPrimaryDisplayName(true).Replace(' ', '_').ToLower(); count++; // Handle Master Rounds specially because we actually care about the order if (name == "master_round") { string objectname = obj.gameObject.name; int floornumber = 420; switch (objectname.Substring("MasteryToken_".Length)) { case "Castle": // Keep of the Lead Lord floornumber = 1; break; case "Gungeon": // Gungeon Proper floornumber = 2; break; case "Mines": floornumber = 3; break; case "Catacombs": // Hollow floornumber = 4; break; case "Forge": floornumber = 5; break; } name = name + "_" + floornumber; } if (ETGModConsole.AllItems.ContainsKey(name)) { int appendindex = 2; while (ETGModConsole.AllItems.ContainsKey (name + "_" + appendindex.ToString())) { appendindex++; } name = name + "_" + appendindex.ToString (); } ETGModConsole.AllItems.Add(name, i); if (count >= 30) { count = 0; yield return null; } } //Add command arguments. Debug.Log(ETGModConsole.AllItems.Values.Count + " give command args"); } }
28.891566
117
0.532666
[ "MIT" ]
Gl0rfindel/ETGMod
Assembly-CSharp.Base.mm/src/ETGGUI/ETGModGUI.cs
7,196
C#
#if UNITY_EDITOR && UNITY_ANDROID using System.IO; using UnityEditor; using UnityEngine; internal static class Directories { private static readonly string UnityDirectory = Path.GetDirectoryName(EditorApplication.applicationPath); private static readonly string UnityAssetsDirectory = Application.dataPath; public static readonly string UnityRootGradleDirectory = Path.Combine(UnityDirectory, Path.Combine("PlaybackEngines", Path.Combine("AndroidPlayer", Path.Combine("Tools", "gradle")))); public static readonly string UnityGradleLibDirectory = Path.Combine(UnityRootGradleDirectory, "lib"); public static readonly string UnityGradlePluginsDirectory = Path.Combine(UnityGradleLibDirectory, "plugins"); public static readonly string TempGradleDirectory = Path.Combine(UnityAssetsDirectory, Path.Combine("Skillz", Path.Combine("Build", Path.Combine("Editor", "OldGradleVersion")))); public static readonly string TempGradleLibDirectory = Path.Combine(TempGradleDirectory, "lib"); public static readonly string TempGradlePluginsDirectory = Path.Combine(TempGradleLibDirectory, "plugins"); public static readonly string SkillzLibDirectory = Path.Combine(UnityAssetsDirectory, Path.Combine("Skillz", Path.Combine("Build", Path.Combine("Editor", "lib")))); } #endif
45.785714
184
0.808892
[ "MIT" ]
skillz/Unity-Pinball
Pinball/Assets/Skillz/Internal/Directories.cs
1,284
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 CorbaHub.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", "16.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("CorbaHub.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; } } /// <summary> /// Looks up a localized resource of type System.Byte[]. /// </summary> internal static byte[] cSharpClient { get { object obj = ResourceManager.GetObject("cSharpClient", resourceCulture); return ((byte[])(obj)); } } /// <summary> /// Looks up a localized resource of type System.Byte[]. /// </summary> internal static byte[] cSharpObject { get { object obj = ResourceManager.GetObject("cSharpObject", resourceCulture); return ((byte[])(obj)); } } /// <summary> /// Looks up a localized resource of type System.Byte[]. /// </summary> internal static byte[] cSharpServer { get { object obj = ResourceManager.GetObject("cSharpServer", resourceCulture); return ((byte[])(obj)); } } /// <summary> /// Looks up a localized resource of type System.Byte[]. /// </summary> internal static byte[] IDLPreProcCSharp { get { object obj = ResourceManager.GetObject("IDLPreProcCSharp", resourceCulture); return ((byte[])(obj)); } } /// <summary> /// Looks up a localized resource of type System.Byte[]. /// </summary> internal static byte[] IIOPChannel { get { object obj = ResourceManager.GetObject("IIOPChannel", resourceCulture); return ((byte[])(obj)); } } /// <summary> /// Looks up a localized resource of type System.Byte[]. /// </summary> internal static byte[] javaClient { get { object obj = ResourceManager.GetObject("javaClient", resourceCulture); return ((byte[])(obj)); } } /// <summary> /// Looks up a localized resource of type System.Byte[]. /// </summary> internal static byte[] javaObject { get { object obj = ResourceManager.GetObject("javaObject", resourceCulture); return ((byte[])(obj)); } } /// <summary> /// Looks up a localized resource of type System.Byte[]. /// </summary> internal static byte[] javaServer { get { object obj = ResourceManager.GetObject("javaServer", resourceCulture); return ((byte[])(obj)); } } /// <summary> /// Looks up a localized resource of type System.Byte[]. /// </summary> internal static byte[] nunit_framework { get { object obj = ResourceManager.GetObject("nunit_framework", resourceCulture); return ((byte[])(obj)); } } } }
37.805195
174
0.541395
[ "MIT" ]
Shabibii/CorbaHub
CorbaHub/CorbaHub/Properties/Resources.Designer.cs
5,824
C#
#region License //-------------------------------------------------- // <License> // <Copyright> 2018 © Top Nguyen </Copyright> // <Url> http://topnguyen.net/ </Url> // <Author> Top </Author> // <Project> Elect </Project> // <File> // <Name> StringHelper.cs </Name> // <Created> 21/03/2018 4:11:44 PM </Created> // <Key> 25f935ca-8d97-4b64-9f08-2d3449b47188 </Key> // </File> // <Summary> // StringHelper.cs is a part of Elect // </Summary> // <License> //-------------------------------------------------- #endregion License using System.Text; using Microsoft.AspNetCore.WebUtilities; namespace Elect.Web.StringUtils { public class StringHelper : Core.StringUtils.StringHelper { public static string GetFriendlySlug(string value, int maxLength = 150) { if (string.IsNullOrWhiteSpace(value)) { return string.Empty; } value = Normalize(value).ToLowerInvariant(); var length = value.Length; var previousDash = false; var stringBuilder = new StringBuilder(length); for (var i = 0; i < length; ++i) { var c = value[i]; if (c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c >= 'A' && c <= 'Z') { stringBuilder.Append(c); previousDash = false; } else if (c == ' ' || c == ',' || c == '.' || c == '/' || c == '\\' || c == '-' || c == '_' || c == '=') { if (!previousDash && stringBuilder.Length > 0) { stringBuilder.Append('-'); previousDash = true; } } else if (c >= 128) { var previousLength = stringBuilder.Length; stringBuilder.Append(c); if (previousLength != stringBuilder.Length) { previousDash = false; } } if (stringBuilder.Length >= maxLength) { break; } } if (previousDash || stringBuilder.Length > maxLength) { return stringBuilder.ToString().Substring(0, stringBuilder.Length - 1); } return stringBuilder.ToString(); } public static string EncodeBase64Url(string value) { byte[] bytes = Encoding.UTF8.GetBytes(value); string base64Encode = WebEncoders.Base64UrlEncode(bytes); return base64Encode; } public static string DecodeBase64Url(string value) { byte[] bytes = WebEncoders.Base64UrlDecode(value); string base64Decode = Encoding.UTF8.GetString(bytes); return base64Decode; } } }
28.345794
119
0.444774
[ "MIT" ]
nminhduc/Elect
src/Web/Elect.Web/StringUtils/StringHelper.cs
3,036
C#
using System.ComponentModel; namespace SharpUnarc.Events { public enum EventType : byte { /// <summary> /// An unknown event type. /// This should never be the case unless a new version of Unarc is released. /// </summary> Unknown, /// <summary> /// An event that occurs at the start of unpacking and provides the total archive size. /// </summary> [Description( "total" )] ArchiveSize, /// <summary> /// An event that occurs when bytes have been read from the archive. /// </summary> [Description( "read" )] BytesRead, /// <summary> /// An event that occurs when bytes have been written to extracted files. /// </summary> [Description( "write" )] BytesWritten, /// <summary> /// An event that occurs when a file is about to be extracted and provides information /// about the file. /// </summary> [Description( "filename" )] FileInfo, /// <summary> /// An event that occurs when an extraced file will overwrite a file that already /// exists in the destination path. /// </summary> [Description( "overwrite?" )] OverwriteFileRequest, /// <summary> /// An event that occurs when an archive is password protected. /// </summary> [Description( "password?" )] PasswordRequest, /// <summary> /// An event that occurs when an error is encountered. /// </summary> [Description( "error" )] Error, /// <summary> /// An event that occurs during the [l]ist command and provides the total number /// of files inside the archive. /// </summary> [Description( "total_files" )] ArchiveTotalFiles, /// <summary> /// An event that occurs during the [l]ist command and provides the total /// uncompressed size of the archive. /// </summary> [Description( "origsize" )] ArchiveUncompressedSize, /// <summary> /// An event that occurs during the [l]ist command and provides the total /// uncompressed size of the archive. /// </summary> [Description( "compsize" )] ArchiveCompressedSize, } }
26.156627
93
0.608936
[ "MIT" ]
Wildenhaus/SharpUnarc
SharpUnarc/SharpUnarc/Events/EventType.cs
2,173
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Buffers; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Reflection; using Microsoft.AspNetCore.Components.Reflection; using Microsoft.AspNetCore.Components.Rendering; using Microsoft.AspNetCore.Internal; using static Microsoft.AspNetCore.Internal.LinkerFlags; namespace Microsoft.AspNetCore.Components.Routing { internal sealed class QueryParameterValueSupplier { public static void ClearCache() => _cacheByType.Clear(); private static readonly Dictionary<Type, QueryParameterValueSupplier?> _cacheByType = new(); // These two arrays contain the same number of entries, and their corresponding positions refer to each other. // Holding the info like this means we can use Array.BinarySearch with less custom implementation. private readonly ReadOnlyMemory<char>[] _queryParameterNames; private readonly QueryParameterDestination[] _destinations; public static QueryParameterValueSupplier? ForType([DynamicallyAccessedMembers(Component)] Type componentType) { if (!_cacheByType.TryGetValue(componentType, out var instanceOrNull)) { // If the component doesn't have any query parameters, store a null value for it // so we know the upstream code can't try to render query parameter frames for it. var sortedMappings = GetSortedMappings(componentType); instanceOrNull = sortedMappings == null ? null : new QueryParameterValueSupplier(sortedMappings); _cacheByType.TryAdd(componentType, instanceOrNull); } return instanceOrNull; } private QueryParameterValueSupplier(QueryParameterMapping[] sortedMappings) { _queryParameterNames = new ReadOnlyMemory<char>[sortedMappings.Length]; _destinations = new QueryParameterDestination[sortedMappings.Length]; for (var i = 0; i < sortedMappings.Length; i++) { ref var mapping = ref sortedMappings[i]; _queryParameterNames[i] = mapping.QueryParameterName; _destinations[i] = mapping.Destination; } } public void RenderParametersFromQueryString(RenderTreeBuilder builder, ReadOnlyMemory<char> queryString) { // If there's no querystring contents, we can skip renting from the pool if (queryString.IsEmpty) { for (var destinationIndex = 0; destinationIndex < _destinations.Length; destinationIndex++) { ref var destination = ref _destinations[destinationIndex]; var blankValue = destination.IsArray ? destination.Parser.ParseMultiple(default, string.Empty) : null; builder.AddAttribute(0, destination.ComponentParameterName, blankValue); } return; } // Temporary workspace in which we accumulate the data while walking the querystring. var valuesByMapping = ArrayPool<StringSegmentAccumulator>.Shared.Rent(_destinations.Length); try { // Capture values by destination in a single pass through the querystring var queryStringEnumerable = new QueryStringEnumerable(queryString); foreach (var suppliedPair in queryStringEnumerable) { var decodedName = suppliedPair.DecodeName(); var mappingIndex = Array.BinarySearch(_queryParameterNames, decodedName, QueryParameterNameComparer.Instance); if (mappingIndex >= 0) { var decodedValue = suppliedPair.DecodeValue(); if (_destinations[mappingIndex].IsArray) { valuesByMapping[mappingIndex].Add(decodedValue); } else { valuesByMapping[mappingIndex].SetSingle(decodedValue); } } } // Finally, emit the parameter attributes by parsing all the string segments and building arrays for (var mappingIndex = 0; mappingIndex < _destinations.Length; mappingIndex++) { ref var destination = ref _destinations[mappingIndex]; ref var values = ref valuesByMapping[mappingIndex]; var parsedValue = destination.IsArray ? destination.Parser.ParseMultiple(values, destination.ComponentParameterName) : values.Count == 0 ? default : destination.Parser.Parse(values[0].Span, destination.ComponentParameterName); builder.AddAttribute(0, destination.ComponentParameterName, parsedValue); } } finally { ArrayPool<StringSegmentAccumulator>.Shared.Return(valuesByMapping, true); } } private static QueryParameterMapping[]? GetSortedMappings([DynamicallyAccessedMembers(Component)] Type componentType) { var candidateProperties = MemberAssignment.GetPropertiesIncludingInherited(componentType, ComponentProperties.BindablePropertyFlags); HashSet<ReadOnlyMemory<char>>? usedQueryParameterNames = null; List<QueryParameterMapping>? mappings = null; foreach (var propertyInfo in candidateProperties) { if (!propertyInfo.IsDefined(typeof(ParameterAttribute))) { continue; } var fromQueryAttribute = propertyInfo.GetCustomAttribute<SupplyParameterFromQueryAttribute>(); if (fromQueryAttribute is not null) { // Found a parameter that's assignable from querystring var componentParameterName = propertyInfo.Name; var queryParameterName = (string.IsNullOrEmpty(fromQueryAttribute.Name) ? componentParameterName : fromQueryAttribute.Name).AsMemory(); // If it's an array type, capture that info and prepare to parse the element type Type effectiveType = propertyInfo.PropertyType; var isArray = false; if (effectiveType.IsArray) { isArray = true; effectiveType = effectiveType.GetElementType()!; } if (!UrlValueConstraint.TryGetByTargetType(effectiveType, out var parser)) { throw new NotSupportedException($"Querystring values cannot be parsed as type '{propertyInfo.PropertyType}'."); } // Add the destination for this component parameter name usedQueryParameterNames ??= new(QueryParameterNameComparer.Instance); if (usedQueryParameterNames.Contains(queryParameterName)) { throw new InvalidOperationException($"The component '{componentType}' declares more than one mapping for the query parameter '{queryParameterName}'."); } usedQueryParameterNames.Add(queryParameterName); mappings ??= new(); mappings.Add(new QueryParameterMapping { QueryParameterName = queryParameterName, Destination = new QueryParameterDestination(componentParameterName, parser, isArray) }); } } mappings?.Sort((a, b) => QueryParameterNameComparer.Instance.Compare(a.QueryParameterName, b.QueryParameterName)); return mappings?.ToArray(); } private readonly struct QueryParameterMapping { public ReadOnlyMemory<char> QueryParameterName { get; init; } public QueryParameterDestination Destination { get; init; } } private readonly struct QueryParameterDestination { public readonly string ComponentParameterName; public readonly UrlValueConstraint Parser; public readonly bool IsArray; public QueryParameterDestination(string componentParameterName, UrlValueConstraint parser, bool isArray) { ComponentParameterName = componentParameterName; Parser = parser; IsArray = isArray; } } private class QueryParameterNameComparer : IComparer<ReadOnlyMemory<char>>, IEqualityComparer<ReadOnlyMemory<char>> { public static readonly QueryParameterNameComparer Instance = new(); public int Compare(ReadOnlyMemory<char> x, ReadOnlyMemory<char> y) => x.Span.CompareTo(y.Span, StringComparison.OrdinalIgnoreCase); public bool Equals(ReadOnlyMemory<char> x, ReadOnlyMemory<char> y) => x.Span.Equals(y.Span, StringComparison.OrdinalIgnoreCase); public int GetHashCode([DisallowNull] ReadOnlyMemory<char> obj) => string.GetHashCode(obj.Span, StringComparison.OrdinalIgnoreCase); } } }
47.179612
175
0.606338
[ "MIT" ]
FWest98/MicrosoftAspNetCore
src/Components/Components/src/Routing/QueryParameterValueSupplier.cs
9,719
C#
using UnityEngine; /// <summary> /// Used as a tag to detect upon game over collision /// </summary> public class Killer : MonoBehaviour { public bool active = true; }
18
53
0.661111
[ "MIT" ]
RLst/KomiOuch
Assets/Scripts/Killer.cs
182
C#
using CommunityToolkit.Mvvm.DependencyInjection; using IoC.Services; using IoC.ViewModels; using Microsoft.Extensions.DependencyInjection; using Microsoft.UI.Xaml; // To learn more about WinUI, the WinUI project structure, // and more about our project templates, see: http://aka.ms/winui-project-info. namespace IoC { /// <summary> /// Provides application-specific behavior to supplement the default Application class. /// </summary> public partial class App : Application { /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { this.InitializeComponent(); } /// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="args">Details about the launch request and process.</param> protected override void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args) { Ioc.Default.ConfigureServices(new ServiceCollection() .AddSingleton<IDatabaseService, DatabaseService>() .AddTransient<MainViewModel>() .BuildServiceProvider()); m_window = new MainWindow(); m_window.Activate(); } private Window m_window; } }
34.391304
98
0.644121
[ "MIT" ]
PacktPublishing/Modernizing-Your-Windows-Applications-with-the-Windows-Apps-SDK-and-WinUI
Chapter06/03-IoC/IoC/App.xaml.cs
1,584
C#
/////////////////////////////////////////////////////////////////////////////// // // // EditorForm.cs // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // /////////////////////////////////////////////////////////////////////////////// using DotNetDxc; using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Windows.Forms; namespace MainNs { public partial class EditorForm : Form { private const string AppName = "DirectX Compiler Editor"; private const string OptDescSeparator = "\t"; private bool autoDisassemble; private IDxcLibrary library; private IDxcIntelliSense isense; private IDxcIndex lastIndex; private IDxcTranslationUnit lastTU; private IDxcBlob selectedShaderBlob; private string selectedShaderBlobTarget; private bool passesLoaded = false; private bool docModified = false; private string docFileName; private DocumentKind documentKind; private MRUManager mruManager; private SettingsManager settingsManager; private Action pendingASTDump; private FindDialog findDialog; private TabPage errorListTabPage; private List<DiagnosticDetail> diagnosticDetails; private DataGridView diagnosticDetailsGrid; private List<PassInfo> passInfos; private TabPage debugInfoTabPage; private RichTextBox debugInfoControl; private HlslHost hlslHost = new HlslHost(); private TabPage renderViewTabPage; private TabPage rewriterOutputTabPage; private TabPage helpTabPage; private RichTextBox helpControl; internal enum DocumentKind { /// <summary> /// HLSL source code. /// </summary> HlslText, /// <summary> /// LLVM source code. /// </summary> AsmText, /// <summary> /// Compiled DXIL container. /// </summary> CompiledObject, } public EditorForm() { InitializeComponent(); cbProfile.SelectedIndex = 0; } internal IDxcBlob SelectedShaderBlob { get { return this.selectedShaderBlob; } set { this.selectedShaderBlob = value; this.selectedShaderBlobTarget = TryGetBlobShaderTarget(this.selectedShaderBlob); } } private const uint DFCC_DXIL = 1279875140; private const uint DFCC_SHDR = 1380206675; private const uint DFCC_SHEX = 1480935507; private const uint DFCC_ILDB = 1111772233; private const uint DFCC_SPDB = 1111773267; private TabPage HelpTabPage { get { if (this.helpTabPage == null) { this.helpTabPage = new TabPage("Help"); this.AnalysisTabControl.TabPages.Add(helpTabPage); } return this.helpTabPage; } } private RichTextBox HelpControl { get { if (this.helpControl == null) { this.helpControl = new RichTextBox(); this.HelpTabPage.Controls.Add(this.helpControl); this.helpControl.Dock = DockStyle.Fill; this.helpControl.Font = this.CodeBox.Font; } return this.helpControl; } } private TabPage RenderViewTabPage { get { if (this.renderViewTabPage == null) { this.renderViewTabPage = new TabPage("Render View"); this.AnalysisTabControl.TabPages.Add(renderViewTabPage); } return this.renderViewTabPage; } } private TabPage RewriterOutputTabPage { get { if (this.rewriterOutputTabPage == null) { this.rewriterOutputTabPage = new TabPage("Rewriter Output"); this.AnalysisTabControl.TabPages.Add(rewriterOutputTabPage); } return this.rewriterOutputTabPage; } } private string TryGetBlobShaderTarget(IDxcBlob blob) { if (blob == null) return null; uint size = blob.GetBufferSize(); if (size == 0) return null; unsafe { try { var reflection = HlslDxcLib.CreateDxcContainerReflection(); reflection.Load(blob); uint index; int hr = reflection.FindFirstPartKind(DFCC_DXIL, out index); if (hr < 0) hr = reflection.FindFirstPartKind(DFCC_SHEX, out index); if (hr < 0) hr = reflection.FindFirstPartKind(DFCC_SHDR, out index); if (hr < 0) return null; unsafe { IDxcBlob part = reflection.GetPartContent(index); UInt32* p = (UInt32*)part.GetBufferPointer(); return DescribeProgramVersionShort(*p); } } catch (Exception) { return null; } } } private void EditorForm_Shown(object sender, EventArgs e) { // Launched as a console program, so this needs to be done explicitly. this.Activate(); this.UpdateWindowText(); } #region Menu item handlers. private void aboutToolStripMenuItem_Click(object sender, EventArgs e) { // Version information currently is available through validator. string libraryVersion; try { IDxcValidator validator = HlslDxcLib.CreateDxcValidator(); IDxcVersionInfo versionInfo = (IDxcVersionInfo)validator; uint major, minor; versionInfo.GetVersion(out major, out minor); DxcVersionInfoFlags flags = versionInfo.GetFlags(); libraryVersion = major.ToString() + "." + minor.ToString(); if ((flags & DxcVersionInfoFlags.Debug) == DxcVersionInfoFlags.Debug) { libraryVersion += " (debug)"; } } catch (Exception err) { libraryVersion = err.Message; } IDxcLibrary library = HlslDxcLib.CreateDxcLibrary(); MessageBox.Show(this, AppName + "\r\n" + "Compiler Library Version: " + libraryVersion + "\r\n" + "See LICENSE.txt for license information.", "About " + AppName); } private void compileToolStripMenuItem_Click(object sender, EventArgs e) { this.CompileDocument(); this.AnalysisTabControl.SelectedTab = this.DisassemblyTabPage; } private void errorListToolStripMenuItem_Click(object sender, EventArgs e) { if (errorListTabPage == null) { this.errorListTabPage = new TabPage("Error List"); this.AnalysisTabControl.TabPages.Add(this.errorListTabPage); this.diagnosticDetailsGrid = new DataGridView() { AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells, Dock = DockStyle.Fill, ReadOnly = true, }; this.diagnosticDetailsGrid.DoubleClick += DiagnosticDetailsGridDoubleClick; this.diagnosticDetailsGrid.CellDoubleClick += (_, __) => { DiagnosticDetailsGridDoubleClick(sender, EventArgs.Empty); }; this.errorListTabPage.Controls.Add(this.diagnosticDetailsGrid); this.RefreshDiagnosticDetails(); } this.AnalysisTabControl.SelectedTab = this.errorListTabPage; } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); } private void fileVariablesToolStripMenuItem_Click(object sender, EventArgs e) { string codeText = this.CodeBox.Text; HlslFileVariables fileVars = GetFileVars(); using (Form form = new Form()) { PropertyGrid grid = new PropertyGrid() { Dock = DockStyle.Fill, SelectedObject = fileVars, }; Button okButton = new Button() { Dock = DockStyle.Bottom, DialogResult = DialogResult.OK, Text = "OK" }; Button cancelButton = new Button() { DialogResult = DialogResult.Cancel, Text = "Cancel" }; form.Controls.Add(grid); form.Controls.Add(okButton); if (form.ShowDialog(this) == DialogResult.OK) { string newFirstLine = fileVars.ToString(); if (fileVars.SetFromText) { int firstEnd = codeText.IndexOf('\n'); if (firstEnd == 0) { codeText = "// " + fileVars.ToString(); } else { codeText = "// " + fileVars.ToString() + "\r\n" + codeText.Substring(firstEnd + 1); } } else { codeText = "// " + fileVars.ToString() + "\r\n" + codeText; } this.CodeBox.Text = codeText; } } } private void NewToolStripMenuItem_Click(object sender, EventArgs e) { if (!IsOKToOverwriteContent()) return; // Consider: using this a simpler File | New experience. //string psBanner = // "// -*- mode: hlsl; hlsl-entry: main; hlsl-target: ps_6_0; hlsl-args: /Zi; -*-\r\n"; //string simpleShader = // "float4 main() : SV_Target {\r\n return 1;\r\n}\r\n"; string shaderSample = "// -*- mode: hlsl; hlsl-entry: VSMain; hlsl-target: vs_6_0; hlsl-args: /Zi; -*-\r\n" + "struct PSInput {\r\n" + " float4 position : SV_POSITION;\r\n" + " float4 color : COLOR;\r\n" + "};\r\n" + "[RootSignature(\"RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT)\")]\r\n" + "PSInput VSMain(float4 position: POSITION, float4 color: COLOR) {\r\n" + " float aspect = 320.0 / 200.0;\r\n" + " PSInput result;\r\n" + " result.position = position;\r\n" + " result.position.y *= aspect;\r\n" + " result.color = color;\r\n" + " return result;\r\n" + "}\r\n" + "[RootSignature(\"RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT)\")]\r\n" + "float4 PSMain(PSInput input) : SV_TARGET {\r\n" + " return input.color;\r\n" + "}\r\n"; string xmlSample = "<ShaderOp PS='PS' VS='VS'>\r\n" + " <RootSignature>RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT)</RootSignature>\r\n" + " <Resource Name='VBuffer' Dimension='BUFFER' Width='1024' Flags='ALLOW_UNORDERED_ACCESS' InitialResourceState='COPY_DEST' Init='FromBytes'>\r\n" + " { { 0.0f, 0.25f , 0.0f }, { 1.0f, 0.0f, 0.0f, 1.0f } },\r\n" + " { { 0.25f, -0.25f , 0.0f }, { 0.0f, 1.0f, 0.0f, 1.0f } },\r\n" + " { { -0.25f, -0.25f , 0.0f }, { 0.0f, 0.0f, 1.0f, 1.0f } }\r\n" + " </Resource>\r\n" + " <DescriptorHeap Name='RtvHeap' NumDescriptors='1' Type='RTV'>\r\n" + " </DescriptorHeap>\r\n" + " <InputElements>\r\n" + " <InputElement SemanticName='POSITION' Format='R32G32B32_FLOAT' AlignedByteOffset='0' />\r\n" + " <InputElement SemanticName='COLOR' Format='R32G32B32A32_FLOAT' AlignedByteOffset='12' />\r\n" + " </InputElements>\r\n" + " <Shader Name='VS' Target='vs_6_0' EntryPoint='VSMain' />\r\n" + " <Shader Name='PS' Target='ps_6_0' EntryPoint='PSMain' />\r\n" + "</ShaderOp>\r\n"; this.CodeBox.Text = shaderSample + "\r\n" + ShaderOpStartMarker + "\r\n" + xmlSample + ShaderOpStopMarker + "\r\n"; this.CodeBox.ClearUndo(); this.DocKind = DocumentKind.HlslText; this.DocFileName = null; this.DocModified = false; } private void saveToolStripMenuItem_Click(object sender, EventArgs e) { if (this.DocKind == DocumentKind.CompiledObject) { throw new NotImplementedException(); } if (String.IsNullOrEmpty(this.DocFileName)) { saveAsToolStripMenuItem_Click(sender, e); return; } try { System.IO.File.WriteAllText(this.DocFileName, GetCodeWithFileVars()); } catch (System.IO.IOException) { this.mruManager.HandleFileFail(this.DocFileName); throw; } this.DocModified = false; this.mruManager.HandleFileSave(this.DocFileName); this.mruManager.SaveToFile(); } private void saveAsToolStripMenuItem_Click(object sender, EventArgs e) { using (SaveFileDialog dialog = new SaveFileDialog()) { dialog.DefaultExt = ".hlsl"; if (!String.IsNullOrEmpty(this.DocFileName)) dialog.FileName = this.DocFileName; dialog.Filter = "HLSL Files (*.hlsl)|*.hlsl|DXIL Files (*.ll)|*.ll|All Files (*.*)|*.*"; dialog.ValidateNames = true; if (dialog.ShowDialog(this) != DialogResult.OK) return; this.DocFileName = dialog.FileName; } System.IO.File.WriteAllText(this.DocFileName, GetCodeWithFileVars()); this.DocModified = false; } private void HandleOpenUI(string mruPath) { if (!IsOKToOverwriteContent()) return; if (mruPath == null) { // If not MRU, prompt for a path. using (OpenFileDialog dialog = new OpenFileDialog()) { dialog.DefaultExt = ".hlsl"; if (!String.IsNullOrEmpty(this.DocFileName)) dialog.FileName = this.DocFileName; dialog.Filter = "HLSL Files (*.hlsl)|*.hlsl|Compiled Shader Objects (*.cso;*.fxc)|*.cso;*.fxc|All Files (*.*)|*.*"; dialog.ValidateNames = true; if (dialog.ShowDialog(this) != DialogResult.OK) return; this.DocFileName = dialog.FileName; } } else { this.DocFileName = mruPath; } string ext = System.IO.Path.GetExtension(this.DocFileName).ToLowerInvariant(); if (ext == ".cso" || ext == ".fxc") { this.SelectedShaderBlob = this.Library.CreateBlobFromFile(this.DocFileName, IntPtr.Zero); this.DocKind = DocumentKind.CompiledObject; this.DisassembleSelectedShaderBlob(); } else { this.DocKind = (ext == ".ll") ? DocumentKind.AsmText : DocumentKind.HlslText; try { this.CodeBox.Text = System.IO.File.ReadAllText(this.DocFileName); } catch (System.IO.IOException) { this.mruManager.HandleFileFail(this.DocFileName); throw; } } this.DocModified = false; this.mruManager.HandleFileLoad(this.DocFileName); this.mruManager.SaveToFile(); } private void openToolStripMenuItem_Click(object sender, EventArgs e) { this.HandleOpenUI(null); } private void exportCompiledObjectToolStripMenuItem_Click(object sender, EventArgs e) { if (this.SelectedShaderBlob == null) { MessageBox.Show(this, "There is no compiled shader blob available for exporting."); return; } using (SaveFileDialog dialog = new SaveFileDialog()) { dialog.DefaultExt = ".cso"; if (!String.IsNullOrEmpty(this.DocFileName)) { dialog.FileName = this.DocFileName; if (String.IsNullOrEmpty(System.IO.Path.GetExtension(this.DocFileName))) { dialog.FileName += ".cso"; } } dialog.Filter = "Compiled Shader Object Files (*.cso;*.fxc)|*.cso;*.fxc|All Files (*.*)|*.*"; dialog.ValidateNames = true; if (dialog.ShowDialog(this) != DialogResult.OK) return; System.IO.File.WriteAllBytes(dialog.FileName, GetBytesFromBlob(this.SelectedShaderBlob)); } } private void quickFindToolStripMenuItem_Click(object sender, EventArgs e) { TextBoxBase target = (this.DeepActiveControl as TextBoxBase); if (target == null) return; if (findDialog == null) { this.findDialog = new FindDialog(); this.findDialog.Disposed += (_sender, _e) => { this.findDialog = null; }; } if (target.SelectionLength < 128) this.findDialog.FindText = target.SelectedText; else this.findDialog.FindText = ""; this.findDialog.Target = target; if (this.findDialog.Visible) { this.findDialog.Focus(); } else { this.findDialog.Show(this); } } #endregion Menu item handlers. private static bool IsDxilTarget(string target) { // ps_6_0 // 012345 int major; if (target != null && target.Length == 6) if (Int32.TryParse(new string(target[3], 1), out major)) return major >= 6; if (target.StartsWith("lib")) if (Int32.TryParse(new string(target[4], 1), out major)) return major >= 6; return false; } private void CompileDocument() { this.DisassemblyTextBox.Font = this.CodeBox.Font; this.ASTDumpBox.Font = this.CodeBox.Font; SelectionHighlightData.ClearAnyFromRtb(this.CodeBox); var library = this.Library; // Switch modes. Can probably be better. DocumentKind localKind = this.DocKind; string text = null; if (localKind == DocumentKind.HlslText || this.DocKind == DocumentKind.AsmText) { text = this.CodeBox.Text; if (String.IsNullOrEmpty(text)) { return; } // Make some obvious changes. if (text[0] == ';') { localKind = DocumentKind.AsmText; } else if (text[0] == '/') { localKind = DocumentKind.HlslText; } } if (localKind == DocumentKind.HlslText) { var source = this.CreateBlobForText(text); string fileName = "hlsl.hlsl"; HlslFileVariables fileVars = GetFileVars(); bool isDxil = IsDxilTarget(fileVars.Target); IDxcCompiler compiler = isDxil ? HlslDxcLib.CreateDxcCompiler() : null; { string[] arguments = fileVars.Arguments; if (isDxil) { try { var result = compiler.Compile(source, fileName, fileVars.Entry, fileVars.Target, arguments, arguments.Length, null, 0, library.CreateIncludeHandler()); if (result.GetStatus() == 0) { this.SelectedShaderBlob = result.GetResult(); this.DisassembleSelectedShaderBlob(); } else { this.colorizationService.ClearColorization(this.DisassemblyTextBox); this.DisassemblyTextBox.Text = GetStringFromBlob(result.GetErrors()); } } catch (Exception e) { DisassemblyTextBox.Text = e.ToString(); } } else { this.colorizationService.ClearColorization(this.DisassemblyTextBox); IDxcBlob code, errorMsgs; uint flags = 0; const uint D3DCOMPILE_DEBUG = 1; if (fileVars.Arguments.Contains("/Zi")) flags = D3DCOMPILE_DEBUG; int hr = D3DCompiler.D3DCompiler.D3DCompile(text, text.Length, fileName, null, 0, fileVars.Entry, fileVars.Target, flags, 0, out code, out errorMsgs); if (hr != 0) { if (errorMsgs != null) { this.DisassemblyTextBox.Text = GetStringFromBlob(errorMsgs); } else { this.DisassemblyTextBox.Text = "Compilation filed with 0x" + hr.ToString("x"); } return; } IDxcBlob disassembly; unsafe { IntPtr buf = new IntPtr(code.GetBufferPointer()); hr = D3DCompiler.D3DCompiler.D3DDisassemble(buf, code.GetBufferSize(), 0, null, out disassembly); this.DisassemblyTextBox.Text = GetStringFromBlob(disassembly); } this.SelectedShaderBlob = code; } } // AST Dump - defer to avoid another parse pass pendingASTDump = () => { try { var result = compiler.Compile(source, fileName, fileVars.Entry, fileVars.Target, new string[] { "-ast-dump" }, 1, null, 0, library.CreateIncludeHandler()); if (result.GetStatus() == 0) { this.ASTDumpBox.Text = GetStringFromBlob(result.GetResult()); } else { this.ASTDumpBox.Text = GetStringFromBlob(result.GetErrors()); } } catch (Exception e) { this.ASTDumpBox.Text = e.ToString(); } }; if (AnalysisTabControl.SelectedTab == ASTTabPage) { pendingASTDump(); pendingASTDump = null; } if (this.diagnosticDetailsGrid != null) { this.RefreshDiagnosticDetails(); } } else if (localKind == DocumentKind.CompiledObject) { this.CodeBox.Text = "Cannot compile a shader object."; return; } else if (localKind == DocumentKind.AsmText) { var source = this.CreateBlobForText(text); var assembler = HlslDxcLib.CreateDxcAssembler(); var result = assembler.AssembleToContainer(source); if (result.GetStatus() == 0) { this.SelectedShaderBlob = result.GetResult(); this.DisassembleSelectedShaderBlob(); // TODO: run validation on this shader blob } else { this.DisassemblyTextBox.Text = GetStringFromBlob(result.GetErrors()); } return; } } class RtbColorization { private RichTextBox rtb; private NumericRanges colored; private AsmColorizer colorizer; private string text; public RtbColorization(RichTextBox rtb, string text) { this.rtb = rtb; this.colorizer = new AsmColorizer(); this.text = text; this.colored = new NumericRanges(); } public void Start() { this.rtb.SizeChanged += Rtb_SizeChanged; this.rtb.HScroll += Rtb_SizeChanged; this.rtb.VScroll += Rtb_SizeChanged; this.ColorizeVisibleRegion(); } public void Stop() { this.rtb.SizeChanged -= Rtb_SizeChanged; this.rtb.HScroll -= Rtb_SizeChanged; this.rtb.VScroll -= Rtb_SizeChanged; } private void Rtb_SizeChanged(object sender, EventArgs e) { this.ColorizeVisibleRegion(); } private void ColorizeVisibleRegion() { int firstCharIdx = rtb.GetCharIndexFromPosition(new Point(0, 0)); firstCharIdx = rtb.GetFirstCharIndexFromLine(rtb.GetLineFromCharIndex(firstCharIdx)); int lastCharIdx = rtb.GetCharIndexFromPosition(new Point(rtb.ClientSize)); NumericRange visibleRange = new NumericRange(firstCharIdx, lastCharIdx + 1); if (this.colored.Contains(visibleRange)) { return; } var doc = GetTextDocument(rtb); using (new RichTextBoxEditAction(rtb)) { foreach (var idxRange in this.colored.ListGaps(visibleRange)) { this.colored.Add(idxRange); foreach (var range in this.colorizer.GetColorRanges(this.text, idxRange.Lo, idxRange.Hi - 1)) { if (range.RangeKind == AsmRangeKind.WS) continue; if (range.Start + range.Length < firstCharIdx) continue; if (lastCharIdx < range.Start) return; Color color; switch (range.RangeKind) { case AsmRangeKind.Comment: color = Color.DarkGreen; break; case AsmRangeKind.LLVMTypeName: case AsmRangeKind.Keyword: case AsmRangeKind.Instruction: color = Color.Blue; break; case AsmRangeKind.StringConstant: color = Color.DarkRed; break; case AsmRangeKind.Metadata: color = Color.DarkOrange; break; default: color = Color.Black; break; } SetStartLengthColor(doc, range.Start, range.Length, color); } } } } } class RtbColorizationService { private Dictionary<RichTextBox, RtbColorization> instances = new Dictionary<RichTextBox, RtbColorization>(); public void ClearColorization(RichTextBox rtb) { SetColorization(rtb, null); } public void SetColorization(RichTextBox rtb, RtbColorization colorization) { RtbColorization existing; if (instances.TryGetValue(rtb, out existing) && existing != null) { existing.Stop(); } instances[rtb] = colorization; if (colorization != null) colorization.Start(); } } RtbColorizationService colorizationService = new RtbColorizationService(); private void DisassembleSelectedShaderBlob() { this.DisassemblyTextBox.Font = this.CodeBox.Font; var compiler = HlslDxcLib.CreateDxcCompiler(); try { var dis = compiler.Disassemble(this.SelectedShaderBlob); string disassemblyText = GetStringFromBlob(dis); RichTextBox rtb = this.DisassemblyTextBox; this.DisassemblyTextBox.Text = disassemblyText; this.colorizationService.SetColorization(rtb, new RtbColorization(rtb, disassemblyText)); } catch (Exception e) { this.DisassemblyTextBox.Text = "Unable to disassemble selected shader.\r\n" + e.ToString(); } } private void HandleException(Exception exception) { HandleException(exception, "Exception " + exception.GetType().Name); } private void HandleException(Exception exception, string caption) { MessageBox.Show(this, exception.ToString(), caption); } private static Dictionary<string, string> ParseFirstLineOptions(string line) { Dictionary<string, string> result = new Dictionary<string, string>(); int start = line.IndexOf("-*-"); if (start < 0) return result; int end = line.IndexOf("-*-", start + 3); if (end < 0) return result; string[] nameValuePairs = line.Substring(start + 3, (end - start - 3)).Split(';'); foreach (string pair in nameValuePairs) { int separator = pair.IndexOf(':'); if (separator < 0) continue; string name = pair.Substring(0, separator).Trim(); string value = pair.Substring(separator + 1).Trim(); result[name] = value; } return result; } class HlslFileVariables { [Description("Editing mode for the file, typically hlsl")] public string Mode { get; set; } [Description("Name of the entry point function")] public string Entry { get; set; } [Description("Shader model target")] public string Target { get; set; } [Description("Arguments for compilation")] public string[] Arguments { get; set; } [Description("Whether the variables where obtained from the text file")] public bool SetFromText { get; private set; } public static HlslFileVariables FromText(string text) { HlslFileVariables result = new HlslFileVariables(); int lineEnd = text.IndexOf('\n'); if (lineEnd > 0) text = text.Substring(0, lineEnd); Dictionary<string, string> options = ParseFirstLineOptions(text); result.SetFromText = options.Count > 0; result.Mode = GetValueOrDefault(options, "mode", "hlsl"); result.Entry = GetValueOrDefault(options, "hlsl-entry", "main"); result.Target = GetValueOrDefault(options, "hlsl-target", "ps_6_0"); result.Arguments = GetValueOrDefault(options, "hlsl-args", "").Split(' ').Select(a => a.Trim()).ToArray(); return result; } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("-*- "); sb.AppendFormat("mode: {0}; ", this.Mode); sb.AppendFormat("hlsl-entry: {0}; ", this.Entry); sb.AppendFormat("hlsl-target: {0}; ", this.Target); if (this.Arguments.Length > 0) { sb.AppendFormat("hlsl-args: {0}; ", String.Join(" ", this.Arguments)); } sb.Append("-*-"); return sb.ToString(); } } internal bool AutoDisassemble { get { return this.autoDisassemble; } set { this.autoDisassemble = value; this.autoUpdateToolStripMenuItem.Checked = value; if (value) { this.CompileDocument(); } } } private void UpdateWindowText() { string text = ""; if (this.DocModified) text = "* "; if (!String.IsNullOrEmpty(this.DocFileName)) { text += System.IO.Path.GetFileName(this.DocFileName); } else { text += "Untitled"; } text += " - " + AppName; this.Text = text; } internal DocumentKind DocKind { get { return this.documentKind; } set { this.documentKind = value; switch (value) { case DocumentKind.AsmText: this.CodeBox.Enabled = true; break; case DocumentKind.HlslText: this.CodeBox.Enabled = true; break; case DocumentKind.CompiledObject: this.CodeBox.Enabled = false; break; } } } internal string DocFileName { get { return this.docFileName; } set { this.docFileName = value; this.UpdateWindowText(); } } internal bool DocModified { get { return this.docModified; } set { if (this.docModified != value) { this.docModified = value; this.UpdateWindowText(); } } } internal IDxcLibrary Library { get { return (library ?? (library = HlslDxcLib.CreateDxcLibrary())); } } internal bool ShowCodeColor { get { return ColorMenuItem.Checked; } set { ColorMenuItem.Checked = value; } } internal bool ShowReferences { get { return ColorMenuItem.Checked; } set { ColorMenuItem.Checked = value; } } internal IDxcTranslationUnit GetTU() { if (this.lastTU == null) { if (this.isense == null) { this.isense = HlslDxcLib.CreateDxcIntelliSense(); } this.lastIndex = this.isense.CreateIndex(); IDxcUnsavedFile[] unsavedFiles = new IDxcUnsavedFile[] { new TrivialDxcUnsavedFile("hlsl.hlsl", this.CodeBox.Text) }; HlslFileVariables fileVars = GetFileVars(); this.lastTU = this.lastIndex.ParseTranslationUnit("hlsl.hlsl", fileVars.Arguments, fileVars.Arguments.Length, unsavedFiles, (uint)unsavedFiles.Length, (uint)DxcTranslationUnitFlags.DxcTranslationUnitFlags_UseCallerThread); } return this.lastTU; } private HlslFileVariables GetFileVars() { HlslFileVariables fileVars = HlslFileVariables.FromText(this.CodeBox.Text); if (fileVars.SetFromText) { tbEntry.Text = fileVars.Entry; cbProfile.Text = fileVars.Target; tbOptions.Text = string.Join(" ", fileVars.Arguments); } else { fileVars.Arguments = tbOptions.Text.Split(); fileVars.Entry = tbEntry.Text; fileVars.Target = cbProfile.Text; } return fileVars; } private string GetCodeWithFileVars() { HlslFileVariables fileVars = GetFileVars(); string codeText = CodeBox.Text; if (fileVars.SetFromText) { int firstEnd = codeText.IndexOf('\n'); if (firstEnd == 0) { codeText = "// " + fileVars.ToString(); } else { codeText = "// " + fileVars.ToString() + "\r\n" + codeText.Substring(firstEnd + 1); } } else { codeText = "// " + fileVars.ToString() + "\r\n" + codeText; } return codeText; } internal void InvalidateTU() { this.lastTU = null; this.lastIndex = null; this.pendingASTDump = null; } private IDxcBlobEncoding CreateBlobForCodeText() { return CreateBlobForText(this.CodeBox.Text); } private IDxcBlobEncoding CreateBlobForText(string text) { return CreateBlobForText(this.Library, text); } public static IDxcBlobEncoding CreateBlobForText(IDxcLibrary library, string text) { if (String.IsNullOrEmpty(text)) { return null; } const UInt32 CP_UTF16 = 1200; var source = library.CreateBlobWithEncodingOnHeapCopy(text, (UInt32)(text.Length * 2), CP_UTF16); return source; } private void CodeBox_SelectionChanged(object sender, System.EventArgs e) { if (!this.ShowReferences && !this.ShowCodeColor) { return; } IDxcTranslationUnit tu = this.GetTU(); if (tu == null) { return; } RichTextBox rtb = this.CodeBox; SelectionHighlightData data = SelectionHighlightData.FromRtb(rtb); int start = this.CodeBox.SelectionStart; if (this.ShowReferences && rtb.SelectionLength > 0) { return; } var doc = GetTextDocument(rtb); var mainFile = tu.GetFile(tu.GetFileName()); using (new RichTextBoxEditAction(rtb)) { data.ClearFromRtb(rtb); if (this.ShowCodeColor) { // Basic tokenization. IDxcToken[] tokens; uint tokenCount; IDxcSourceRange range = this.isense.GetRange( tu.GetLocationForOffset(mainFile, 0), tu.GetLocationForOffset(mainFile, (uint)this.CodeBox.TextLength)); tu.Tokenize(range, out tokens, out tokenCount); if (tokens != null) { foreach (var t in tokens) { switch (t.GetKind()) { case DxcTokenKind.Keyword: uint line, col, offset, endOffset; IDxcFile file; t.GetLocation().GetSpellingLocation(out file, out line, out col, out offset); t.GetExtent().GetEnd().GetSpellingLocation(out file, out line, out col, out endOffset); SetStartLengthColor(doc, (int)offset, (int)(endOffset - offset), Color.Blue); break; } } } } if (this.ShowReferences) { var loc = tu.GetLocationForOffset(mainFile, (uint)start); var locCursor = tu.GetCursorForLocation(loc); uint resultLength; IDxcCursor[] cursors; locCursor.FindReferencesInFile(mainFile, 0, 100, out resultLength, out cursors); for (int i = 0; i < cursors.Length; ++i) { uint startOffset, endOffset; GetRangeOffsets(cursors[i].GetExtent(), out startOffset, out endOffset); data.Add((int)startOffset, (int)(endOffset - startOffset)); } data.ApplyToRtb(rtb, Color.LightGray); this.TheStatusStripLabel.Text = locCursor.GetCursorKind().ToString(); } } } private static void GetRangeOffsets(IDxcSourceRange range, out uint start, out uint end) { IDxcSourceLocation l; IDxcFile file; uint line, col; l = range.GetStart(); l.GetSpellingLocation(out file, out line, out col, out start); l = range.GetEnd(); l.GetSpellingLocation(out file, out line, out col, out end); } private void CodeBox_TextChanged(object sender, EventArgs e) { if (this.DocKind == DocumentKind.CompiledObject) return; if (e != null) this.DocModified = true; this.InvalidateTU(); if (this.AutoDisassemble) this.CompileDocument(); } private string GetStringFromBlob(IDxcBlob blob) { return GetStringFromBlob(this.Library, blob); } public static string GetStringFromBlob(IDxcLibrary library, IDxcBlob blob) { unsafe { blob = library.GetBlobAstUf16(blob); return new string(blob.GetBufferPointer(), 0, (int)(blob.GetBufferSize() / 2)); } } private byte[] GetBytesFromBlob(IDxcBlob blob) { unsafe { byte* pMem = (byte*)blob.GetBufferPointer(); uint size = blob.GetBufferSize(); byte[] result = new byte[size]; fixed (byte* pTarget = result) { for (uint i = 0; i < size; ++i) pTarget[i] = pMem[i]; } return result; } } private void selectAllToolStripMenuItem_Click(object sender, EventArgs e) { TextBoxBase tb = this.DeepActiveControl as TextBoxBase; if (tb != null) { tb.SelectAll(); return; } } private void undoToolStripMenuItem_Click(object sender, EventArgs e) { TextBoxBase tb = this.DeepActiveControl as TextBoxBase; if (tb != null) { tb.Undo(); return; } } private void cutToolStripMenuItem_Click(object sender, EventArgs e) { TextBoxBase tb = this.DeepActiveControl as TextBoxBase; if (tb != null) { tb.Cut(); return; } } private void copyToolStripMenuItem_Click(object sender, EventArgs e) { TextBoxBase tb = this.DeepActiveControl as TextBoxBase; if (tb != null) { tb.Copy(); return; } ListBox lb = this.DeepActiveControl as ListBox; if (lb != null) { if (lb.SelectedItems.Count > 0) { string content; if (lb.SelectedItems.Count == 1) { content = lb.SelectedItem.ToString(); } else { StringBuilder sb = new StringBuilder(); foreach (var item in lb.SelectedItems) { sb.AppendLine(item.ToString()); } content = sb.ToString(); } Clipboard.SetText(content, TextDataFormat.UnicodeText); } return; } } private Control DeepActiveControl { get { Control result = this; while (result is IContainerControl) { result = ((IContainerControl)result).ActiveControl; } return result; } } private void pasteToolStripMenuItem_Click(object sender, EventArgs e) { RichTextBox rtb = this.DeepActiveControl as RichTextBox; if (rtb != null) { // Handle the container format. if (Clipboard.ContainsData(ContainerData.DataFormat.Name)) { object o = Clipboard.GetData(ContainerData.DataFormat.Name); rtb.SelectedText = ContainerData.DataObjectToString(o); } else { rtb.Paste(DataFormats.GetFormat(DataFormats.UnicodeText)); } return; } TextBoxBase tb = this.ActiveControl as TextBoxBase; if (tb != null) { tb.Paste(); return; } } private void deleteToolStripMenuItem_Click(object sender, EventArgs e) { TextBoxBase tb = this.DeepActiveControl as TextBoxBase; if (tb != null) { tb.SelectedText = ""; return; } } private void goToToolStripMenuItem_Click(object sender, EventArgs e) { int lastIndex = this.CodeBox.TextLength; int lastLine = this.CodeBox.GetLineFromCharIndex(lastIndex - 1); int currentLine = this.CodeBox.GetLineFromCharIndex(this.CodeBox.SelectionStart); using (GoToDialog dialog = new GoToDialog()) { dialog.MaxLineNumber = lastLine + 1; dialog.LineNumber = currentLine + 1; if (dialog.ShowDialog(this) == DialogResult.OK) { this.CodeBox.Select(this.CodeBox.GetFirstCharIndexFromLine(dialog.LineNumber - 1), 0); } } } private void ResetDefaultPassesButton_Click(object sender, EventArgs e) { this.ResetDefaultPasses(); } private static bool IsDisassemblyTokenChar(char c) { return char.IsLetterOrDigit(c) || c == '@' || c == '%' || c == '$'; } private static bool IsTokenLeftBoundary(string text, int i) { // Whether there is a token boundary between text[i] and text[i-1]. if (i == 0) return true; if (i >= text.Length - 1) return true; char cPrior = text[i - 1]; char c = text[i]; return !IsDisassemblyTokenChar(cPrior) && IsDisassemblyTokenChar(c); } private static bool IsTokenRightBoundary(string text, int i) { if (i == 0) return true; if (i >= text.Length - 1) return true; char cPrior = text[i - 1]; char c = text[i]; return IsDisassemblyTokenChar(cPrior) && !IsDisassemblyTokenChar(c); } private static int ColorToCOLORREF(Color value) { // 0x00bbggrr. int result = value.R | (value.G << 8) | (value.B << 16); return result; } private static Tom.ITextRange SetStartLengthColor(Tom.ITextDocument doc, int start, int length, Color color) { Tom.ITextRange range = doc.Range(start, start + length); Tom.ITextFont font = range.Font; font.ForeColor = ColorToCOLORREF(color); return range; } private static void SetStartLengthBackColor(Tom.ITextRange range, Color color) { Tom.ITextFont font = range.Font; font.BackColor = ColorToCOLORREF(color); } private static Tom.ITextRange SetStartLengthBackColor(Tom.ITextDocument doc, int start, int length, Color color) { Tom.ITextRange range = doc.Range(start, start + length); SetStartLengthBackColor(range, color); return range; } private static Regex dbgLineRegEx; private static Regex DbgLineRegEx { get { return (dbgLineRegEx = dbgLineRegEx ?? new Regex(@"line: (\d+)")); } } private static Regex dbgColRegEx; private static Regex DbgColRegEx { get { return (dbgColRegEx = dbgColRegEx ?? new Regex(@"column: (\d+)")); } } private static void HandleDebugMetadata(string dbgLine, RichTextBox sourceBox) { Match lineMatch = DbgLineRegEx.Match(dbgLine); if (!lineMatch.Success) { return; } int lineVal = Int32.Parse(lineMatch.Groups[1].Value) - 1; int targetStart = sourceBox.GetFirstCharIndexFromLine(lineVal); int targetEnd = sourceBox.GetFirstCharIndexFromLine(lineVal + 1); Match colMatch = DbgColRegEx.Match(dbgLine); if (colMatch.Success) { targetStart += Int32.Parse(colMatch.Groups[1].Value) - 1; } var highlights = SelectionHighlightData.FromRtb(sourceBox); highlights.ClearFromRtb(sourceBox); highlights.Add(targetStart, targetEnd - targetStart); highlights.ApplyToRtb(sourceBox, Color.Yellow); sourceBox.SelectionStart = targetStart; sourceBox.ScrollToCaret(); } private static void HandleDebugTokenOnDisassemblyLine(RichTextBox rtb, RichTextBox sourceBox) { // Get the line. string[] lines = rtb.Lines; string line = lines[rtb.GetLineFromCharIndex(rtb.SelectionStart)]; Regex re = new Regex(@"!dbg !(\d+)"); Match m = re.Match(line); if (!m.Success) { return; } string val = m.Groups[1].Value; int dbgMetadata = Int32.Parse(val); for (int dbgLineIndex = lines.Length - 1; dbgLineIndex >= 0;) { string dbgLine = lines[dbgLineIndex]; if (dbgLine.StartsWith("!")) { int dbgIdx = Int32.Parse(dbgLine.Substring(1, dbgLine.IndexOf(' ') - 1)); if (dbgIdx == dbgMetadata) { HandleDebugMetadata(dbgLine, sourceBox); return; } else if (dbgIdx < dbgMetadata) { return; } else { dbgLineIndex -= (dbgIdx - dbgMetadata); } } else { --dbgLineIndex; } } } public static void HandleCodeSelectionChanged(RichTextBox rtb, RichTextBox sourceBox) { SelectionHighlightData data = SelectionHighlightData.FromRtb(rtb); SelectionExpandResult expand = SelectionExpandResult.Expand(rtb); if (expand.IsEmpty) return; string token = expand.Token; if (sourceBox != null && token == "dbg") { HandleDebugTokenOnDisassemblyLine(rtb, sourceBox); } if (data.SelectedToken == token) return; string text = expand.Text; // OK, time to do work. using (new RichTextBoxEditAction(rtb)) { data.SelectedToken = token; data.ClearFromRtb(rtb); int match = text.IndexOf(token); while (match != -1) { data.Add(match, token.Length); match += token.Length; match = text.IndexOf(token, match); } data.ApplyToRtb(rtb, Color.LightPink); } } private void DisassemblyTextBox_SelectionChanged(object sender, EventArgs e) { HandleCodeSelectionChanged((RichTextBox)sender, this.CodeBox); } private string PassToPassString(IDxcOptimizerPass pass) { return pass.GetOptionName() + OptDescSeparator + pass.GetDescription(); } private string PassStringToBanner(string value) { int separator = value.IndexOf(OptDescSeparator); if (separator >= 0) value = value.Substring(0, separator); return value; } private static string PassStringToOption(string value) { int separator = value.IndexOf(OptDescSeparator); if (separator >= 0) value = value.Substring(0, separator); return "-" + value; } private void AnalysisTabControl_Selecting(object sender, TabControlCancelEventArgs e) { if (e.TabPage == this.OptimizerTabPage) { if (passesLoaded) { return; } this.ResetDefaultPasses(); } if (e.TabPage == this.ASTTabPage) { if (pendingASTDump != null) { pendingASTDump(); pendingASTDump = null; } } } private void ResetDefaultPasses() { IDxcOptimizer opt = HlslDxcLib.CreateDxcOptimizer(); if (!this.passesLoaded) { int passCount = opt.GetAvailablePassCount(); PassInfo[] localInfos = new PassInfo[passCount]; for (int i = 0; i < passCount; ++i) { localInfos[i] = PassInfo.FromOptimizerPass(opt.GetAvailablePass(i)); } localInfos = localInfos.OrderBy(p => p.Name).ToArray(); this.passInfos = localInfos.ToList(); this.AvailablePassesBox.Items.AddRange(localInfos); this.passesLoaded = true; } List<string> args; try { HlslFileVariables fileVars = GetFileVars(); args = fileVars.Arguments.Where(a => !String.IsNullOrWhiteSpace(a)).ToList(); } catch (Exception) { args = new List<string>() { "/Od" }; } args.Add("/Odump"); IDxcCompiler compiler = HlslDxcLib.CreateDxcCompiler(); IDxcOperationResult optDumpResult = compiler.Compile(CreateBlobForText("[RootSignature(\"\")]float4 main() : SV_Target { return 0; }"), "hlsl.hlsl", "main", "ps_6_0", args.ToArray(), args.Count, null, 0, null); IDxcBlob optDumpBlob = optDumpResult.GetResult(); string optDumpText = GetStringFromBlob(optDumpBlob); this.AddSelectedPassesFromText(optDumpText, true); } private void AddSelectedPassesFromText(string optDumpText, bool replace) { List<object> defaultPasses = new List<object>(); foreach (string line in optDumpText.Split('\n')) { if (line.StartsWith("#")) continue; string lineTrim = line.Trim(); if (String.IsNullOrEmpty(lineTrim)) continue; lineTrim = line.TrimStart('-'); int argSepIndex = lineTrim.IndexOf(','); string passName = argSepIndex > 0 ? lineTrim.Substring(0, argSepIndex) : lineTrim; PassInfo passInfo = this.passInfos.FirstOrDefault(p => p.Name == passName); if (passInfo == null) { defaultPasses.Add(lineTrim); continue; } PassInfoWithValues passWithValues = new PassInfoWithValues(passInfo); if (argSepIndex > 0) { bool problemFound = false; string[] parts = lineTrim.Split(','); for (int i = 1; i < parts.Length; ++i) { string[] nameValue = parts[i].Split('='); PassArgInfo argInfo = passInfo.Args.FirstOrDefault(a => a.Name == nameValue[0]); if (argInfo == null) { problemFound = true; break; } passWithValues.Values.Add(new PassArgValueInfo() { Arg = argInfo, Value = (nameValue.Length == 1) ? null : nameValue[1] }); } if (problemFound) { defaultPasses.Add(lineTrim); continue; } } defaultPasses.Add(passWithValues); } if (replace) { this.SelectedPassesBox.Items.Clear(); } this.SelectedPassesBox.Items.AddRange(defaultPasses.ToArray()); } public static string[] CreatePassOptions(IEnumerable<string> passes, bool analyze, bool printAll) { List<string> result = new List<string>(); if (analyze) result.Add("-analyze"); if (printAll) result.Add("-print-module:start"); bool inOptFn = false; foreach (var itemText in passes) { result.Add(PassStringToOption(itemText)); if (itemText == "opt-fn-passes") { inOptFn = true; } else if (itemText.StartsWith("opt-") && itemText.EndsWith("-passes")) { inOptFn = false; } if (printAll && !inOptFn) { result.Add("-hlsl-passes-pause"); result.Add("-print-module:" + itemText); } } return result.ToArray(); } private string[] CreatePassOptions(bool analyze, bool printAll) { return CreatePassOptions(this.SelectedPassesBox.Items.ToStringEnumerable(), analyze, printAll); } private void RunPassesButton_Click(object sender, EventArgs e) { // TODO: consider accepting DXIL in the code editor as well // Do a high-level only compile. HighLevelCompileResult compile = RunHighLevelCompile(); if (compile.Blob == null) { MessageBox.Show("Failed to compile: " + compile.ResultText); return; } string[] options = CreatePassOptions(this.AnalyzeCheckBox.Checked, false); OptimizeResult opt = RunOptimize(this.Library, options, compile.Blob); if (!opt.Succeeded) { MessageBox.Show("Failed to optimize: " + opt.ResultText); return; } Form form = new Form(); RichTextBox rtb = new RichTextBox(); LogContextMenuHelper helper = new LogContextMenuHelper(rtb); rtb.Dock = DockStyle.Fill; rtb.Font = this.CodeBox.Font; rtb.ContextMenu = new ContextMenu( new MenuItem[] { new MenuItem("Show Graph", helper.ShowGraphClick) }); rtb.SelectionChanged += DisassemblyTextBox_SelectionChanged; rtb.Text = opt.ResultText; form.Controls.Add(rtb); form.StartPosition = FormStartPosition.CenterParent; form.Show(this); } private void SelectPassUpButton_Click(object sender, EventArgs e) { ListBox lb = this.SelectedPassesBox; int selectedIndex = lb.SelectedIndex; if (selectedIndex == -1 || selectedIndex == 0) return; object o = lb.Items[selectedIndex - 1]; lb.Items.RemoveAt(selectedIndex - 1); lb.Items.Insert(selectedIndex, o); } private void SelectPassDownButton_Click(object sender, EventArgs e) { ListBox lb = this.SelectedPassesBox; int selectedIndex = lb.SelectedIndex; if (selectedIndex == -1 || selectedIndex == lb.Items.Count - 1) return; object o = lb.Items[selectedIndex + 1]; lb.Items.RemoveAt(selectedIndex + 1); lb.Items.Insert(selectedIndex, o); } private void AvailablePassesBox_DoubleClick(object sender, EventArgs e) { ListBox lb = (ListBox)sender; if (lb.SelectedItems.Count == 0) return; foreach (var item in lb.SelectedItems) this.SelectedPassesBox.Items.Add(new PassInfoWithValues((PassInfo)item)); } private void SelectedPassesBox_DoubleClick(object sender, EventArgs e) { for (int x = SelectedPassesBox.SelectedIndices.Count - 1; x >= 0; x--) { int idx = SelectedPassesBox.SelectedIndices[x]; SelectedPassesBox.Items.RemoveAt(idx); } } private void AddPrintModuleButton_Click(object sender, EventArgs e) { // Known, very handy. this.SelectedPassesBox.Items.Add("print-module" + OptDescSeparator + "Print module to stderr"); } private void SelectedPassesBox_KeyUp(object sender, KeyEventArgs e) { ListBox lb = (ListBox)sender; if (e.KeyCode == Keys.Delete) { for (int x = SelectedPassesBox.SelectedIndices.Count - 1; x >= 0; x--) { int idx = SelectedPassesBox.SelectedIndices[x]; SelectedPassesBox.Items.RemoveAt(idx); } e.Handled = true; return; } } private void autoUpdateToolStripMenuItem_Click(object sender, EventArgs e) { this.AutoDisassemble = !this.AutoDisassemble; } private static string GetValueOrDefault(Dictionary<string, string> d, string name, string defaultValue) { string result; if (!d.TryGetValue(name, out result)) result = defaultValue; return result; } /// <summary>Helper class to handle the context menu of operations log.</summary> public class LogContextMenuHelper { public RichTextBox Rtb { get; set; } public LogContextMenuHelper(RichTextBox rtb) { this.Rtb = rtb; } public void ShowGraphClick(object sender, EventArgs e) { SelectionExpandResult s = SelectionExpandResult.Expand(this.Rtb); if (s.IsEmpty) return; if (s.Token == "digraph") { int nextStart = s.Text.IndexOf('{', s.SelectionEnd); if (nextStart < 0) return; int closing = FindBalanced('{', '}', s.Text, nextStart); if (closing < 0) return; // See file history for a version that inserted the image in-line with graph. // The svg/web browser approach provides zooming and more interactivity. string graphText = s.Text.Substring(s.SelectionStart, closing - s.SelectionStart); ShowDot(graphText); } } static public void ShowDot(string graphText) { string path = System.IO.Path.GetTempFileName(); string outPath = path + ".svg"; try { System.IO.File.WriteAllText(path, graphText); string svgData = RunDot(path, DotOutFormat.Svg, null); Form browserForm = new Form(); TrackBar zoomControl = new TrackBar(); zoomControl.Minimum = 10; zoomControl.Maximum = 400; zoomControl.Value = 100; zoomControl.Dock = DockStyle.Top; zoomControl.Text = "zoom"; WebBrowser browser = new WebBrowser(); browser.Dock = DockStyle.Fill; browser.DocumentText = svgData; browserForm.Controls.Add(browser); browserForm.Controls.Add(zoomControl); zoomControl.ValueChanged += (_, __) => { if (browser.Document != null && browser.Document.DomDocument != null) { dynamic o = browser.Document.DomDocument; o.documentElement.style.zoom = String.Format("{0}%", zoomControl.Value); } }; browserForm.Text = "graph"; browserForm.Show(); } catch (DotProgram.CannotFindDotException cfde) { MessageBox.Show(cfde.Message, "Unable to find dot.exe", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { DeleteIfExists(path); } } internal static void DeleteIfExists(string path) { if (System.IO.File.Exists(path)) System.IO.File.Delete(path); } internal static string RunDot(string inputFile, DotOutFormat format, string outFile) { DotProgram program = new DotProgram(); program.InFilePath = inputFile; program.OutFilePath = outFile; program.OutFormat = format; return program.StartAndWaitForExit(); } internal static int FindBalanced(char open, char close, string text, int start) { // return exclusive end System.Diagnostics.Debug.Assert(text[start] == open); int level = 1; int result = start + 1; int end = text.Length; while (result < end && level != 0) { if (text[result] == open) level++; if (text[result] == close) level--; result++; } return (result == end) ? -1 : result; } } internal enum DotOutFormat { Svg, Png } class DotProgram { private string fileName; private Dictionary<string, string> options; internal class CannotFindDotException : InvalidOperationException { internal CannotFindDotException(string message) : base(message) { } } public DotProgram() { this.options = new Dictionary<string, string>(); this.options["-Nfontname"] = "Consolas"; this.options["-Efontname"] = "Tahoma"; } public static IEnumerable<string> DotFileNameCandidates() { // Look in a few known places. string path = Environment.GetEnvironmentVariable("PATH"); string[] partPaths = path.Split(';'); foreach (var partPath in partPaths) { yield return System.IO.Path.Combine(partPath, "bin\\dot.exe"); } string progPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86); if (!String.IsNullOrEmpty(progPath)) { yield return System.IO.Path.Combine(progPath, "Graphviz2.38\\bin\\dot.exe"); } progPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); yield return System.IO.Path.Combine(progPath, "Graphviz2.38\\bin\\dot.exe"); } public static string FindDotFileName() { StringBuilder sb = new StringBuilder(); sb.AppendLine("Cannot find dot.exe in any of these locations."); foreach (string result in DotFileNameCandidates()) { sb.AppendLine(result); if (System.IO.File.Exists(result)) return result; } throw new CannotFindDotException(sb.ToString()); } public string BuildArguments() { StringBuilder sb = new StringBuilder(); sb.AppendFormat("-T{0}", this.OutFormat.ToString().ToLowerInvariant()); foreach (var pair in this.Options) { sb.AppendFormat(" {0}={1}", pair.Key, pair.Value); } if (!String.IsNullOrEmpty(this.OutFilePath)) { sb.AppendFormat(" -o{0}", this.OutFilePath); } sb.AppendFormat(" {0}", this.InFilePath); return sb.ToString(); } public string FileName { get { if (String.IsNullOrEmpty(this.fileName)) { this.fileName = FindDotFileName(); } return this.fileName; } set { this.fileName = value; } } public string InFilePath { get; set; } public IDictionary<string, string> Options { get { return this.options; } } public string OutFilePath { get; set; } public DotOutFormat OutFormat { get; set; } public System.Diagnostics.Process Start() { System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(this.FileName, this.BuildArguments()); psi.CreateNoWindow = true; psi.RedirectStandardOutput = String.IsNullOrEmpty(this.OutFilePath); psi.UseShellExecute = false; return System.Diagnostics.Process.Start(psi); } public string StartAndWaitForExit() { using (System.Diagnostics.Process p = this.Start()) { string result = p.StandardOutput.ReadToEnd(); p.WaitForExit(); int code = p.ExitCode; if (code > 0) { throw new Exception("dot.exe failed with code " + code); } return result; } } } /// <summary>Helper class to expand a short selection into something more useful.</summary> class SelectionExpandResult { public int SelectionStart { get; set; } public int SelectionEnd { get; set; } public string Text { get; set; } public string Token { get; set; } public bool IsEmpty { get { return SelectionEnd - 1 == SelectionStart; } } internal static SelectionExpandResult Empty() { return new SelectionExpandResult() { SelectionStart = 0, SelectionEnd = 1 }; } internal static SelectionExpandResult Expand(RichTextBox rtb) { string text = rtb.Text; int selStart = rtb.SelectionStart; int selLength = rtb.SelectionLength; int tokenStart = selStart; int tokenEnd = selStart; if (tokenStart < text.Length && !char.IsLetterOrDigit(text[tokenStart])) return Empty(); // check last token case tokenEnd++; // it's a letter or digit, so it's at least one offset while (tokenStart > 0 && !IsTokenLeftBoundary(text, tokenStart)) tokenStart--; while (tokenEnd < text.Length && !IsTokenRightBoundary(text, tokenEnd)) tokenEnd++; if (tokenEnd - 1 == tokenStart) return Empty(); string token = text.Substring(tokenStart, tokenEnd - tokenStart); return new SelectionExpandResult() { SelectionEnd = tokenEnd, SelectionStart = tokenStart, Text = text, Token = token }; } } /// <summary>Helper class to record editor highlights.</summary> class SelectionHighlightData { public static SelectionHighlightData FromRtb(RichTextBox rtb) { SelectionHighlightData result = (SelectionHighlightData)rtb.Tag; if (result == null) { result = new SelectionHighlightData(); rtb.Tag = result; } return result; } public static void ClearAnyFromRtb(RichTextBox rtb) { SelectionHighlightData data = (SelectionHighlightData)rtb.Tag; if (data != null) data.ClearFromRtb(rtb); } public void Add(int start, int length) { this.StartLengthHighlights.Add(new Tuple<int, int>(start, length)); } public void ApplyToRtb(RichTextBox rtb, Color color) { Tom.ITextDocument doc = GetTextDocument(rtb); foreach (var pair in this.StartLengthHighlights) { this.HighlightRanges.Add(SetStartLengthBackColor(doc, pair.Item1, pair.Item2, color)); } } public void ClearFromRtb(RichTextBox rtb) { Tom.ITextDocument doc = GetTextDocument(rtb); for (int i = 0; i < this.HighlightRanges.Count; ++i) { SetStartLengthBackColor(HighlightRanges[i], rtb.BackColor); } this.StartLengthHighlights.Clear(); this.HighlightRanges.Clear(); } private List<Tom.ITextRange> HighlightRanges = new List<Tom.ITextRange>(); public List<Tuple<int, int>> StartLengthHighlights = new List<Tuple<int, int>>(); public string SelectedToken; } [System.Runtime.InteropServices.Guid("00020d00-0000-0000-c000-000000000046")] interface IRichEditOle { } private const int WM_USER = 0x0400; private const int EM_GETOLEINTERFACE = (WM_USER + 60); [System.Runtime.InteropServices.DllImport( "user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)] private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, ref IRichEditOle lParam); internal static Tom.ITextDocument GetTextDocument(RichTextBox rtb) { IRichEditOle ole = null; SendMessage(rtb.Handle, EM_GETOLEINTERFACE, IntPtr.Zero, ref ole); return ole as Tom.ITextDocument; } /// <summary>Helper class to suppress events and restore selection.</summary> class RichTextBoxEditAction : IDisposable { private const int EM_SETEVENTMASK = (WM_USER + 69); private const int EM_GETSCROLLPOS = (WM_USER + 221); private const int EM_SETSCROLLPOS = (WM_USER + 222); private const int WM_SETREDRAW = 0x0b; private RichTextBox rtb; private bool readOnly; private IntPtr eventMask; [System.Runtime.InteropServices.DllImport( "user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)] private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam); [System.Runtime.InteropServices.DllImport( "user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)] private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, ref Point lParam); internal RichTextBoxEditAction(RichTextBox rtb) { this.rtb = rtb; this.readOnly = rtb.ReadOnly; this.eventMask = (IntPtr)SendMessage(rtb.Handle, EM_SETEVENTMASK, IntPtr.Zero, IntPtr.Zero); SendMessage(rtb.Handle, WM_SETREDRAW, IntPtr.Zero, IntPtr.Zero); this.rtb.ReadOnly = false; } public void Dispose() { SendMessage(rtb.Handle, WM_SETREDRAW, (IntPtr)1, IntPtr.Zero); SendMessage(rtb.Handle, EM_SETEVENTMASK, IntPtr.Zero, this.eventMask); this.rtb.ReadOnly = this.readOnly; } } private void SelectNodeWithOffset(TreeView view, TreeNode node, int offset) { bool foundBetter; do { foundBetter = false; foreach (TreeNode child in node.Nodes) { TreeNodeRange r = child.Tag as TreeNodeRange; if (r != null && r.Contains(offset)) { node = child; foundBetter = true; break; } } } while (foundBetter); view.SelectedNode = node; } private void bitstreamToolStripMenuItem_Click(object sender, EventArgs e) { if (this.SelectedShaderBlob == null) { MessageBox.Show(this, "No shader blob selected. Try compiling a file."); return; } DisplayBitstream(ContainerData.BlobToBytes(this.SelectedShaderBlob), "Bitstream Viewer - Selected Shader"); } private void bitstreamFromClipboardToolStripMenuItem_Click(object sender, EventArgs e) { if (!Clipboard.ContainsData(ContainerData.DataFormat.Name)) { MessageBox.Show(this, "No shader blob on clipboard. Try pasting from the optimizer view."); return; } DisplayBitstream(ContainerData.DataObjectToBytes(Clipboard.GetData(ContainerData.DataFormat.Name)), "Bitstream Viewer - Clipboard"); } private void DisplayBitstream(byte[] bytes, string title) { StatusBar statusBar = new StatusBar(); statusBar.Dock = DockStyle.Bottom; BinaryViewControl binaryView = new BinaryViewControl(); TreeView treeView = new TreeView(); treeView.Dock = DockStyle.Fill; treeView.AfterSelect += (eSender, treeViewEventArgs) => { TreeNodeRange r = treeViewEventArgs.Node.Tag as TreeNodeRange; if (r == null) { binaryView.SetSelection(0, 0); statusBar.ResetText(); } else { binaryView.SetSelection(r.Offset, r.Length); statusBar.Text = String.Format("Bits {0}-{1} (length {2})", r.Offset, r.Offset + r.Length, r.Length); } }; BuildBitstreamNodes(bytes, treeView.Nodes); binaryView.BitClick += (eSender, bitArgs) => { int offset = bitArgs.BitOffset; SelectNodeWithOffset(treeView, treeView.Nodes[0], offset); }; binaryView.BitMouseMove += (eSender, bitArgs) => { int offset = bitArgs.BitOffset; int byteOffset = offset / 8; byte b = bytes[byteOffset]; string toolTipText = String.Format("Byte @ 0x{0:x} = 0x{1:x} = {2}", byteOffset, b, b); TheToolTip.SetToolTip(binaryView, toolTipText); }; Panel binaryPanel = new Panel(); binaryPanel.Dock = DockStyle.Fill; binaryPanel.AutoScroll = true; binaryPanel.Controls.Add(binaryView); SplitContainer container = new SplitContainer(); container.Orientation = Orientation.Vertical; container.Panel1.Controls.Add(treeView); container.Panel2.Controls.Add(binaryPanel); container.Dock = DockStyle.Fill; Form form = new Form(); form.Text = title; form.Controls.Add(container); form.Controls.Add(statusBar); binaryView.Bytes = bytes; form.StartPosition = FormStartPosition.CenterParent; form.Show(this); } #region Bitstream generation. private static void BuildBitstreamNodes(byte[] bytes, TreeNodeCollection nodes) { TreeNode root; if (bytes[0] == 'D' && bytes[1] == 'X' && bytes[2] == 'B' && bytes[3] == 'C') { root = RangeNode("Content: DXBC"); BuildBitstreamForDXBC(bytes, root); } else { root = RangeNode("Content: Unknown", 0, bytes.Length); } nodes.Add(root); AddBitstreamOffsets(root); } private static void AddBitstreamOffsets(TreeNode node) { TreeNodeRange r = node.Tag as TreeNodeRange; if (r == null) { int offset = -1; int length = 0; foreach (TreeNode child in node.Nodes) { AddBitstreamOffsets(child); TreeNodeRange childRange = child.Tag as TreeNodeRange; Debug.Assert(childRange != null); if (offset == -1) { offset = childRange.Offset; length = childRange.Length; } else { Debug.Assert(offset <= childRange.Offset); int lastBit = childRange.Offset + childRange.Length; length = Math.Max(length, lastBit - offset); } } node.Tag = new TreeNodeRange(offset, length); } } private static void BuildBitstreamForDXBC(byte[] bytes, TreeNode root) { int offset = 0; TreeNode header = RangeNode("Header"); root.Nodes.Add(header); string signature; header.Nodes.Add(RangeNodeASCII(bytes, "Signature", ref offset, 4, out signature)); header.Nodes.Add(RangeNodeBytes("Hash", ref offset, 16 * 8)); ushort verMajor, verMinor; header.Nodes.Add(RangeNodeUInt16(bytes, "VerMajor", ref offset, out verMajor)); header.Nodes.Add(RangeNodeUInt16(bytes, "VerMinor", ref offset, out verMinor)); uint containerSize, partCount; header.Nodes.Add(RangeNodeUInt32(bytes, "ContainerSize", ref offset, out containerSize)); header.Nodes.Add(RangeNodeUInt32(bytes, "PartCount", ref offset, out partCount)); uint[] partOffsets = new uint[partCount]; TreeNode partOffsetTable = RangeNode("Part Offsets"); root.Nodes.Add(partOffsetTable); for (uint i = 0; i < partCount; i++) { uint partSize; partOffsetTable.Nodes.Add(RangeNodeUInt32(bytes, "Part Offset #" + i, ref offset, out partSize)); partOffsets[i] = partSize; } TreeNode partsNode = RangeNode("Parts"); root.Nodes.Add(partsNode); for (uint i = 0; i < partCount; i++) { offset = (int)(8 * partOffsets[i]); TreeNode partNode = RangeNode("Part #" + i); TreeNode headerNode = RangeNode("Header"); string partCC; UInt32 partSize; headerNode.Nodes.Add(RangeNodeASCII(bytes, "PartFourCC", ref offset, 4, out partCC)); headerNode.Nodes.Add(RangeNodeUInt32(bytes, "PartSize", ref offset, out partSize)); partNode.Nodes.Add(headerNode); if (partCC == "DXIL") { BuildBitstreamForDXIL(bytes, offset, partNode); } else if (partCC == "ISGN" || partCC == "OSGN" || partCC == "PSGN" || partCC == "ISG1" || partCC == "OSG1" || partCC == "PSG1") { BuildBitstreamForSignature(bytes, offset, partNode, partCC); } partsNode.Nodes.Add(partNode); } } private static void BuildBitstreamForSignature(byte[] bytes, int offset, TreeNode root, string partName) { // DxilProgramSignature bool hasStream = partName.Last() == '1'; bool hasMinprec = hasStream; int startOffset = offset; uint paramCount, paramOffset; root.Nodes.Add(RangeNodeUInt32(bytes, "ParamCount", ref offset, out paramCount)); root.Nodes.Add(RangeNodeUInt32(bytes, "ParamOffset", ref offset, out paramOffset)); if (paramOffset != 8) return; // padding here not yet implemented for (int i = 0; i < paramCount; i++) { TreeNode paramNode = RangeNode("Param #" + i); // DxilProgramSignatureElement uint stream, semanticIndex, semanticName, systemValue, compType, register, minprec; ushort pad; byte mask, maskUsage; if (hasStream) paramNode.Nodes.Add(RangeNodeUInt32(bytes, "Stream", ref offset, out stream)); paramNode.Nodes.Add(RangeNodeUInt32(bytes, "SemanticName", ref offset, out semanticName)); // Now go read the string. if (semanticName != 0) { StringBuilder sb = new StringBuilder(); int nameOffset = startOffset / 8 + (int)semanticName; while (bytes[nameOffset] != 0) { sb.Append((char)bytes[nameOffset]); nameOffset++; } paramNode.Text += " - " + sb.ToString(); } paramNode.Nodes.Add(RangeNodeUInt32(bytes, "SemanticIndex", ref offset, out semanticIndex)); paramNode.Nodes.Add(RangeNodeUInt32(bytes, "SystemValue", ref offset, out systemValue)); paramNode.Nodes.Add(RangeNodeUInt32(bytes, "CompType", ref offset, out compType)); paramNode.Nodes.Add(RangeNodeUInt32(bytes, "Register", ref offset, out register)); paramNode.Nodes.Add(RangeNodeUInt8(bytes, "Mask", ref offset, out mask)); paramNode.Nodes.Add(RangeNodeUInt8(bytes, "MaskUsage", ref offset, out maskUsage)); paramNode.Nodes.Add(RangeNodeUInt16(bytes, "Pad", ref offset, out pad)); if (hasMinprec) { paramNode.Nodes.Add(RangeNodeUInt32(bytes, "Minprecision", ref offset, out minprec)); } root.Nodes.Add(paramNode); } } private static void BuildBitstreamForDXIL(byte[] bytes, int offset, TreeNode root) { TreeNode header = RangeNode("DxilProgramHeader"); uint programVersion, programSize, dxilVersion, bcOffset, bcSize; string magic; TreeNode verNode = RangeNodeUInt32(bytes, "ProgramVersion", ref offset, out programVersion); verNode.Text += " - " + DescribeProgramVersion(programVersion); header.Nodes.Add(verNode); header.Nodes.Add(RangeNodeUInt32(bytes, "SizeInUint32", ref offset, out programSize)); int programOffset = offset; header.Nodes.Add(RangeNodeASCII(bytes, "Magic", ref offset, 4, out magic)); header.Nodes.Add(RangeNodeUInt32(bytes, "DXIL Version", ref offset, out dxilVersion)); header.Nodes.Add(RangeNodeUInt32(bytes, "Bitcode Offset", ref offset, out bcOffset)); header.Nodes.Add(RangeNodeUInt32(bytes, "Bitcode Size", ref offset, out bcSize)); int bitcodeOffset = (int)(programOffset + bcOffset * 8); offset = bitcodeOffset; root.Nodes.Add(header); TreeNode bcNode = RangeNode("DXIL bitcode"); try { DxilBitcodeReader.BuildTree(bytes, ref offset, (int)(bcSize * 8), bcNode); } catch (Exception e) { bcNode.Text += e.Message; } root.Nodes.Add(bcNode); } private static string DescribeProgramVersion(UInt32 programVersion) { uint kind, major, minor; kind = ((programVersion & 0xffff0000) >> 16); major = (programVersion & 0xf0) >> 4; minor = (programVersion & 0xf); string[] shaderKinds = "Pixel,Vertex,Geometry,Hull,Domain,Compute".Split(','); return shaderKinds[kind] + " " + major + "." + minor; } private static string DescribeProgramVersionShort(UInt32 programVersion) { uint kind, major, minor; kind = ((programVersion & 0xffff0000) >> 16); major = (programVersion & 0xf0) >> 4; minor = (programVersion & 0xf); string[] shaderKinds = "ps,vs,gs,hs,ds,cs".Split(','); return shaderKinds[kind] + "_" + major + "_" + minor; } private static TreeNode RangeNode(string text) { return new TreeNode(text); } private static TreeNode RangeNode(string text, int offset, int length) { TreeNode result = new TreeNode(text); result.Tag = new TreeNodeRange(offset, length); return result; } private static TreeNode RangeNodeASCII(byte[] bytes, string text, ref int offset, int charLength, out string value) { System.Diagnostics.Debug.Assert(offset % 8 == 0, "else NYI"); int byteOffset = offset / 8; char[] valueChars = new char[charLength]; for (int i = 0; i < charLength; ++i) { valueChars[i] = (char)bytes[byteOffset + i]; } value = new string(valueChars); TreeNode result = RangeNode(text + ": '" + value + "'", offset, charLength * 8); offset += charLength * 8; return result; } private static uint ReadArrayBits(byte[] bytes, int offset, int length) { uint value = 0; int byteOffset = offset / 8; int bitOffset = offset % 8; for (int i = 0; i < length; ++i) { uint bit = (bytes[byteOffset] & (uint)(1 << bitOffset)) >> bitOffset; value |= bit << i; ++bitOffset; if (bitOffset == 8) { byteOffset++; bitOffset = 0; } } return value; } private static TreeNode RangeNodeBits(byte[] bytes, string text, ref int offset, int length, out uint value) { System.Diagnostics.Debug.Assert(length > 0 && length <= 32, "Cannot return zero or more than BitsInWord bits!"); TreeNode result = RangeNode(text, offset, length); value = ReadArrayBits(bytes, offset, length); offset += length; return result; } private static TreeNode RangeNodeVBR(byte[] bytes, string text, ref int offset, int length, out uint value) { value = ReadArrayBits(bytes, offset, length); if ((value & (1 << (length - 1))) == 0) { TreeNode result = RangeNode(text + ": " + value, offset, length); offset += length; return result; } else { throw new NotImplementedException(); } } private static TreeNode RangeNodeBytes(string text, ref int offset, int length) { TreeNode result = RangeNode(text, offset, length); offset += length; return result; } private static TreeNode RangeNodeUInt8(byte[] bytes, string text, ref int offset, out byte value) { System.Diagnostics.Debug.Assert(offset % 8 == 0, "else NYI"); int byteOffset = offset / 8; value = bytes[byteOffset]; TreeNode result = RangeNode(text + ": " + value, offset, 8); offset += 8; return result; } private static TreeNode RangeNodeUInt16(byte[] bytes, string text, ref int offset, out UInt16 value) { System.Diagnostics.Debug.Assert(offset % 8 == 0, "else NYI"); int byteOffset = offset / 8; value = (ushort)((bytes[byteOffset]) + (bytes[byteOffset + 1] << 8)); TreeNode result = RangeNode(text + ": " + value, offset, 16); offset += 16; return result; } private static TreeNode RangeNodeUInt32(byte[] bytes, string text, ref int offset, out UInt32 value) { System.Diagnostics.Debug.Assert(offset % 8 == 0, "else NYI"); int byteOffset = offset / 8; value = (uint)((bytes[byteOffset]) | (bytes[byteOffset + 1] << 8) | (bytes[byteOffset + 2] << 16) | (bytes[byteOffset + 3] << 24)); TreeNode result = RangeNode(text + ": " + value, offset, 32); offset += 32; return result; } #endregion Bitstream generation. private bool IsOKToOverwriteContent() { if (!this.DocModified) return true; return MessageBox.Show(this, "Are you sure you want to lose your changes?", "Changes Pending", MessageBoxButtons.YesNo) == DialogResult.Yes; } private void fileToolStripMenuItem_DropDownOpening(object sender, EventArgs e) { this.RefreshMRUMenu(this.mruManager, this.recentFilesToolStripMenuItem); } private void EditorForm_Load(object sender, EventArgs e) { this.mruManager = new MRUManager(); this.mruManager.LoadFromFile(); this.settingsManager = new SettingsManager(); this.settingsManager.LoadFromFile(); this.CheckSettingsForDxcLibrary(); } private void RefreshMRUMenu(MRUManager mru, ToolStripMenuItem parent) { parent.DropDownItems.Clear(); foreach (var item in mru.Paths) { EventHandler MRUHandler = (_sender, _args) => { if (!System.IO.File.Exists(item)) { MessageBox.Show("File not found"); return; } this.HandleOpenUI(item); }; parent.DropDownItems.Add(item, null, MRUHandler); } } private static IEnumerable<DiagnosticDetail> EnumerateDiagnosticDetails(DxcDiagnosticDisplayOptions options, IDxcTranslationUnit tu) { uint count = tu.GetNumDiagnostics(); for (uint i = 0; i < count; ++i) { uint errorCode; uint errorLine; uint errorColumn; string errorFile; uint errorOffset; uint errorLength; string errorMessage; tu.GetDiagnosticDetails(i, options, out errorCode, out errorLine, out errorColumn, out errorFile, out errorOffset, out errorLength, out errorMessage); yield return new DiagnosticDetail() { ErrorCode = (int)errorCode, ErrorLine = (int)errorLine, ErrorColumn = (int)errorColumn, ErrorFile = errorFile, ErrorOffset = (int)errorOffset, ErrorLength = (int)errorLength, ErrorMessage = errorMessage, }; } } private static List<DiagnosticDetail> ListDiagnosticDetails(DxcDiagnosticDisplayOptions options, IDxcTranslationUnit tu) { return EnumerateDiagnosticDetails(options, tu).ToList(); } private void RefreshDiagnosticDetails() { if (this.diagnosticDetailsGrid == null) { return; } IDxcTranslationUnit tu = this.GetTU(); if (tu == null) { return; } DxcDiagnosticDisplayOptions options = this.isense.GetDefaultDiagnosticDisplayOptions(); this.diagnosticDetails = ListDiagnosticDetails(options, tu); this.diagnosticDetailsGrid.DataSource = this.diagnosticDetails; this.diagnosticDetailsGrid.Columns["ErrorCode"].Visible = false; this.diagnosticDetailsGrid.Columns["ErrorLength"].Visible = false; this.diagnosticDetailsGrid.Columns["ErrorOffset"].Visible = false; } private void DiagnosticDetailsGridDoubleClick(object sender, EventArgs e) { if (this.diagnosticDetailsGrid.SelectedRows.Count == 0) return; DiagnosticDetail detail = this.diagnosticDetailsGrid.SelectedRows[0].DataBoundItem as DiagnosticDetail; if (detail == null) return; this.CodeBox.Select(detail.ErrorOffset, detail.ErrorLength); this.CodeBox.Select(); } class PassArgumentControls { public PassArgInfo ArgInfo { get; set; } public Label PromptLabel { get; set; } public TextBox ValueControl { get; set; } public Label DescriptionLabel { get; set; } public IEnumerable<Control> Controls { get { yield return PromptLabel; yield return ValueControl; yield return DescriptionLabel; } } public static PassArgumentControls FromArg(PassArgInfo arg) { PassArgumentControls result = new MainNs.EditorForm.PassArgumentControls() { ArgInfo = arg, PromptLabel = new Label() { Text = arg.Name, UseMnemonic = true, }, DescriptionLabel = new Label() { Text = arg.Description, UseMnemonic = false, }, ValueControl = new TextBox() { }, }; if (result.DescriptionLabel.Text == "None") { result.DescriptionLabel.Visible = false; } return result; } } private int LayoutVertical(Control container, IEnumerable<Control> controls, int top, int pad) { int result = top; int controlWidth = container.ClientSize.Width - pad * 2; foreach (var c in controls) { if (!c.Visible) continue; c.Top = result; c.Left = pad; c.Width = controlWidth; c.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right; result += c.Height; result += pad; container.Controls.Add(c); } return result; } private void RemoveListBoxItems(ListBox listbox, int startIndex, int endIndexExclusive) { for (int i = endIndexExclusive - 1; i >= startIndex; --i) { listbox.Items.RemoveAt(i); } } private void PassPropertiesMenuItem_Click(object sender, EventArgs e) { ListBox lb = this.SelectedPassesBox; int selectedIndex = lb.SelectedIndex; PassInfoWithValues passInfoValues = lb.SelectedItem as PassInfoWithValues; if (passInfoValues == null) { return; } PassInfo passInfo = passInfoValues.PassInfo; string title = String.Format("{0} properties", passInfo.Name); if (passInfo.Args.Length == 0) { MessageBox.Show(this, "No properties available to set.", title); return; } using (Form form = new Form()) { var argControls = passInfo.Args.Select(p => PassArgumentControls.FromArg(p)).ToDictionary(c => c.ArgInfo); foreach (var val in passInfoValues.Values) argControls[val.Arg].ValueControl.Text = val.Value; int lastTop = LayoutVertical(form, argControls.Values.SelectMany(c => c.Controls), 8, 8); form.ShowInTaskbar = false; form.MinimizeBox = false; form.MaximizeBox = false; form.Text = title; Button okButton = new Button() { Anchor = AnchorStyles.Bottom | AnchorStyles.Right, DialogResult = DialogResult.OK, Text = "OK", Top = lastTop, }; okButton.Left = form.ClientSize.Width - 8 - okButton.Width; form.Controls.Add(okButton); form.AcceptButton = okButton; if (form.ShowDialog(this) == DialogResult.OK) { passInfoValues.Values.Clear(); // Add options with values. foreach (var argValues in argControls.Values) { if (String.IsNullOrEmpty(argValues.ValueControl.Text)) continue; passInfoValues.Values.Add(new PassArgValueInfo() { Arg = argValues.ArgInfo, Value = argValues.ValueControl.Text }); } lb.Items.RemoveAt(selectedIndex); lb.Items.Insert(selectedIndex, passInfoValues); lb.SelectedIndex = selectedIndex; } } } private void copyAllToolStripMenuItem_Click(object sender, EventArgs e) { StringBuilder sb = new StringBuilder(); foreach (var o in this.SelectedPassesBox.Items) sb.AppendLine(o.ToString()); Clipboard.SetText(sb.ToString()); } private void renderToolStripMenuItem_Click(object sender, EventArgs e) { this.RenderLogBox.Clear(); string payloadText = GetShaderOpPayload(); if (this.settingsManager.ExternalRenderEnabled) { string path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "dndxc-ext-render.xml"); try { System.IO.File.WriteAllText(path, payloadText); } catch (Exception writeErr) { HandleException(writeErr, "Unable to write render input to " + path); return; } try { string arguments = this.settingsManager.ExternalRenderCommand; arguments = arguments.Replace("%in", path); var process = System.Diagnostics.Process.Start("cmd.exe", "/c " + arguments); if (process != null) { process.Dispose(); } } catch (Exception runErr) { HandleException(runErr, "Unable to run external render command."); return; } return; } try { this.hlslHost.EnsureActive(); } catch (Exception startErr) { HandleException(startErr, "Unable to start HLSLHost.exe."); return; } try { SendHostMessageAndLogReply(HlslHost.HhMessageId.StartRendererMsgId); this.AnalysisTabControl.SelectedTab = RenderViewTabPage; this.hlslHost.SetParentHwnd(RenderViewTabPage.Handle); this.hlslHost.SendHostMessagePlay(payloadText); System.Windows.Forms.Timer t = new Timer(); t.Interval = 1000; t.Tick += (_, __) => { t.Dispose(); if (!this.TopSplitContainer.Panel2Collapsed) { this.RenderLogBox.Font = this.CodeBox.Font; this.DrainHostLog(); } }; t.Start(); } catch (Exception runError) { System.Diagnostics.Debug.WriteLine(runError); this.hlslHost.IsActive = false; this.HandleException(runError, "Unable to render"); } } private string GetShaderOpPayload() { string fullText = this.CodeBox.Text; string xml = GetShaderOpXmlFragment(fullText); return HlslHost.GetShaderOpPayload(fullText, xml); } private static readonly string ShaderOpStartMarker = "#if SHADER_OP_XML"; private static readonly string ShaderOpStopMarker = "#endif"; private static string GetShaderOpXmlFragment(string text) { int start = text.IndexOf(ShaderOpStartMarker); if (start == -1) throw new InvalidOperationException("Cannot for '" + ShaderOpStartMarker + "' marker"); start += ShaderOpStartMarker.Length; int end = text.IndexOf(ShaderOpStopMarker, start); if (end == -1) throw new InvalidOperationException("Cannot for '" + ShaderOpStopMarker + "' marker"); return text.Substring(start, end - start).Trim(); } private void SendHostMessageAndLogReply(HlslHost.HhMessageId kind) { this.hlslHost.SendHostMessage(kind); LogReply(this.hlslHost.GetReply()); } private HlslHost.HhMessageReply LogReply(HlslHost.HhMessageReply reply) { if (reply == null) return null; string log = HlslHost.GetLogReplyText(reply); if (!String.IsNullOrWhiteSpace(log)) { this.RenderLogBox.AppendText(log + "\r\n"); } return reply; } private void DrainHostLog() { try { this.hlslHost.SendHostMessage(HlslHost.HhMessageId.ReadLogMsgId); for (;;) { if (this.LogReply(this.hlslHost.GetReply()) == null) return; } } catch (Exception hostErr) { this.TheStatusStripLabel.Text = "Unable to contact host."; this.RenderLogBox.AppendText(hostErr.Message); } } private void outputToolStripMenuItem_Click(object sender, EventArgs e) { this.TopSplitContainer.Panel2Collapsed = !this.TopSplitContainer.Panel2Collapsed; if (!this.hlslHost.IsActive) return; this.RenderLogBox.Font = this.CodeBox.Font; this.DrainHostLog(); } private void EditorForm_FormClosing(object sender, FormClosingEventArgs e) { // Consider prompting to save. } private void EditorForm_FormClosed(object sender, FormClosedEventArgs e) { this.hlslHost.IsActive = false; } private void FontGrowToolStripMenuItem_Click(object sender, EventArgs e) { Control target = this.DeepActiveControl; if (target == null) return; target.Font = new Font(target.Font.FontFamily, target.Font.Size * 1.1f); } private void FontShrinkToolStripMenuItem_Click(object sender, EventArgs e) { Control target = this.DeepActiveControl; if (target == null) return; target.Font = new Font(target.Font.FontFamily, target.Font.Size / 1.1f); } private void optionsToolStripMenuItem_Click(object sender, EventArgs e) { Form form = new Form(); PropertyGrid grid = new PropertyGrid(); grid.SelectedObject = this.settingsManager; grid.Dock = DockStyle.Fill; form.Controls.Add(grid); form.FormClosing += (_, __) => { this.settingsManager.SaveToFile(); this.CheckSettingsForDxcLibrary(); }; form.ShowDialog(this); } private void CheckSettingsForDxcLibrary() { try { if (String.IsNullOrWhiteSpace(this.settingsManager.ExternalLib)) { HlslDxcLib.DxcCreateInstanceFn = DefaultDxcLib.GetDxcCreateInstanceFn(); } else { HlslDxcLib.DxcCreateInstanceFn = HlslDxcLib.LoadDxcCreateInstance( this.settingsManager.ExternalLib, this.settingsManager.ExternalFunction); } } catch (Exception e) { HandleException(e); } } private void colorToolStripMenuItem_Click(object sender, EventArgs e) { this.ColorMenuItem.Checked = !this.ColorMenuItem.Checked; CodeBox_SelectionChanged(sender, e); } private void rewriterToolStripMenuItem_Click(object sender, EventArgs e) { IDxcRewriter rewriter = HlslDxcLib.CreateDxcRewriter(); IDxcBlobEncoding code = CreateBlobForCodeText(); IDxcRewriteResult rewriterResult = rewriter.RewriteUnchangedWithInclude(code, "input.hlsl", null, 0, library.CreateIncludeHandler(), 0); IDxcBlobEncoding rewriteBlob = rewriterResult.GetRewrite(); string rewriteText = GetStringFromBlob(rewriteBlob); RewriterOutputTextBox.Text = rewriteText; AnalysisTabControl.SelectTab(RewriterOutputTabPage); } private void rewriteNobodyToolStripMenuItem_Click(object sender, EventArgs e) { IDxcRewriter rewriter = HlslDxcLib.CreateDxcRewriter(); IDxcBlobEncoding code = CreateBlobForCodeText(); IDxcRewriteResult rewriterResult = rewriter.RewriteUnchangedWithInclude(code, "input.hlsl", null, 0, library.CreateIncludeHandler(), 1); IDxcBlobEncoding rewriteBlob = rewriterResult.GetRewrite(); string rewriteText = GetStringFromBlob(rewriteBlob); RewriterOutputTextBox.Text = rewriteText; AnalysisTabControl.SelectTab(RewriterOutputTabPage); } private IEnumerable<string> EnumerateDiaCandidates() { string progPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86); yield return System.IO.Path.Combine(progPath, @"Microsoft Visual Studio\2017\Community\DIA SDK\bin\amd64\msdia140.dll"); yield return System.IO.Path.Combine(progPath, @"Microsoft Visual Studio\2017\Community\Common7\IDE\msdia140.dll"); yield return System.IO.Path.Combine(progPath, @"Microsoft Visual Studio\2017\Community\Common7\IDE\msdia120.dll"); } private string SuggestDiaRegistration() { foreach (string path in EnumerateDiaCandidates()) { if (System.IO.File.Exists(path)) { return "Consider registering with this command:\r\n" + "regsvr32 \"" + path + "\""; } } return null; } private void debugInformationToolStripMenuItem_Click(object sender, EventArgs e) { if (this.SelectedShaderBlob == null) { MessageBox.Show("Compile or load a shader to view debug information."); return; } this.ClearDiaUnimplementedFlags(); IDxcBlob debugInfoBlob; dia2.IDiaDataSource dataSource; uint dfcc; IDxcContainerReflection r = HlslDxcLib.CreateDxcContainerReflection(); r.Load(this.SelectedShaderBlob); if (IsDxilTarget(this.selectedShaderBlobTarget)) { dataSource = HlslDxcLib.CreateDxcDiaDataSource(); dfcc = DFCC_ILDB; } else { try { dataSource = new dia2.DiaDataSource() as dia2.IDiaDataSource; } catch (System.Runtime.InteropServices.COMException ce) { const int REGDB_E_CLASSNOTREG = -2147221164; if (ce.HResult == REGDB_E_CLASSNOTREG) { string suggestion = SuggestDiaRegistration(); string message = "Unable to create dia object."; if (suggestion != null) message += "\r\n" + suggestion; MessageBox.Show(this, message); } else { HandleException(ce); } return; } dfcc = DFCC_SPDB; } uint index; int hr = r.FindFirstPartKind(dfcc, out index); if (hr < 0) { MessageBox.Show("Debug information not found in container."); return; } debugInfoBlob = r.GetPartContent(index); try { dataSource.loadDataFromIStream(Library.CreateStreamFromBlobReadOnly(debugInfoBlob)); string s = dataSource.get_lastError(); if (!String.IsNullOrEmpty(s)) { MessageBox.Show("Failure to load stream: " + s); return; } } catch (Exception ex) { HandleException(ex); return; } var session = dataSource.openSession(); var tables = session.getEnumTables(); uint count = tables.get_Count(); StringBuilder output = new StringBuilder(); output.AppendLine("* Tables"); bool isFirstTable = true; for (uint i = 0; i < count; ++i) { var table = tables.Item(i); if (isFirstTable) isFirstTable = false; else output.AppendLine(); output.AppendLine("** " + table.get_name()); int itemCount = table.get_Count(); output.AppendLine("Record count: " + itemCount); for (int itemIdx = 0; itemIdx < itemCount; itemIdx++) { object o = table.Item((uint)itemIdx); if (TryDumpDiaObject(o as dia2.IDiaSymbol, output)) continue; if (TryDumpDiaObject(o as dia2.IDiaSourceFile, output)) continue; if (TryDumpDiaObject(o as dia2.IDiaLineNumber, output)) continue; if (TryDumpDiaObject(o as dia2.IDiaInjectedSource, output)) continue; if (TryDumpDiaObject(o as dia2.IDiaSectionContrib, output)) continue; if (TryDumpDiaObject(o as dia2.IDiaSegment, output)) continue; } } if (debugInfoTabPage == null) { this.debugInfoTabPage = new TabPage("Debug Info"); this.debugInfoControl = new RichTextBox() { Dock = DockStyle.Fill, Font = this.CodeBox.Font, ReadOnly = true }; this.AnalysisTabControl.TabPages.Add(this.debugInfoTabPage); this.debugInfoTabPage.Controls.Add(this.debugInfoControl); } this.debugInfoControl.Text = output.ToString(); this.AnalysisTabControl.SelectedTab = this.debugInfoTabPage; } private bool TryDumpDiaObject<TIface>(TIface o, StringBuilder sb) { if (o == null) return false; DumpDiaObject(o, sb); return true; } private void ClearDiaUnimplementedFlags() { foreach (var item in TypeWriters) foreach (var writer in item.Value) writer.Unimplemented = false; } private void DumpDiaObject<TIface>(TIface o, StringBuilder sb) { Type type = typeof(TIface); bool hasLine = false; List<DiaTypePropertyWriter> writers; if (SymTagEnumValues == null) { SymTagEnumValues = Enum.GetNames(typeof(dia2.SymTagEnum)); } if (!TypeWriters.TryGetValue(type, out writers)) { writers = new List<DiaTypePropertyWriter>(); foreach (System.Reflection.MethodInfo mi in type.GetMethods()) { Func<string, object, StringBuilder, bool> writer; if (mi.GetParameters().Length > 0) continue; string propertyName = mi.Name; if (!propertyName.StartsWith("get_")) continue; propertyName = propertyName.Substring(4); Type returnType = mi.ReturnType; if (returnType == typeof(string)) writer = WriteDiaValueString; else if (returnType == typeof(uint) && propertyName == "symTag") writer = WriteDiaValueSymTag; else if (returnType == typeof(uint)) writer = WriteDiaValueUInt32; else if (returnType == typeof(UInt64)) writer = WriteDiaValueUInt64; else if (returnType == typeof(bool)) writer = WriteDiaValueBool; else writer = WriteDiaValueAny; writers.Add(new DiaTypePropertyWriter() { MI = mi, PropertyName = propertyName, Writer = writer }); } TypeWriters[type] = writers; } foreach (var writer in writers) { if (writer.Write(o, sb)) hasLine = true; } if (hasLine) sb.AppendLine(); } private static Dictionary<Type, List<DiaTypePropertyWriter>> TypeWriters = new Dictionary<Type, List<DiaTypePropertyWriter>>(); internal static string[] SymTagEnumValues; class DiaTypePropertyWriter { public static object[] EmptyParams = new object[0]; public bool Unimplemented; public System.Reflection.MethodInfo MI; public string PropertyName; public Func<string, object, StringBuilder, bool> Writer; internal bool Write(object instance, StringBuilder sb) { if (Unimplemented) return false; try { object value = MI.Invoke(instance, EmptyParams); return Writer(PropertyName, value, sb); } catch (System.Reflection.TargetInvocationException tie) { if (tie.InnerException is NotImplementedException) { this.Unimplemented = true; } return false; } catch (System.Runtime.InteropServices.COMException) { return false; } } } private static bool WriteDiaValueAny(string propertyName, object propertyValue, StringBuilder sb) { if (null == propertyValue) return false; if (System.Runtime.InteropServices.Marshal.IsComObject(propertyValue)) return false; sb.Append(propertyName); sb.Append(": "); sb.Append(Convert.ToString(propertyValue)); sb.AppendLine(); return true; } private static bool WriteDiaValueSymTag(string propertyName, object propertyValueObj, StringBuilder sb) { uint tag = (uint)propertyValueObj; sb.Append(propertyName); sb.Append(": "); sb.AppendLine(SymTagEnumValues[tag]); return true; } private static bool WriteDiaValueBool(string propertyName, object propertyValueObj, StringBuilder sb) { bool propertyValue = (bool)propertyValueObj; if (false == propertyValue) return false; sb.Append(propertyName); sb.Append(": "); sb.Append(propertyValue); sb.AppendLine(); return true; } private static bool WriteDiaValueUInt32(string propertyName, object propertyValueObj, StringBuilder sb) { uint propertyValue = (uint)propertyValueObj; if (0 == propertyValue) return false; sb.Append(propertyName); sb.Append(": "); sb.Append(propertyValue); sb.AppendLine(); return true; } private static bool WriteDiaValueUInt64(string propertyName, object propertyValueObj, StringBuilder sb) { UInt64 propertyValue = (UInt64)propertyValueObj; if (0 == propertyValue) return false; sb.Append(propertyName); sb.Append(": "); sb.Append(propertyValue); sb.AppendLine(); return true; } private static bool WriteDiaValueString(string propertyName, object propertyValueObj, StringBuilder sb) { string propertyValue = (string)propertyValueObj; if (String.IsNullOrEmpty(propertyValue)) return false; sb.Append(propertyName); sb.Append(": "); sb.AppendLine(propertyValue); return true; } private void PastePassesMenuItem_Click(object sender, EventArgs e) { if (!Clipboard.ContainsText()) { MessageBox.Show(this, "The clipboard does not contain pass information.", "Unable to paste passes"); return; } string passes = Clipboard.GetText(TextDataFormat.UnicodeText); try { passes = passes.Replace("\r\n", "\n"); AddSelectedPassesFromText(passes, false); } catch (Exception ex) { this.HandleException(ex); } } private void DeleteAllPassesMenuItem_Click(object sender, EventArgs e) { this.SelectedPassesBox.Items.Clear(); } public class AssembleResult { public IDxcBlob Blob { get; set; } public string ResultText { get; set; } public bool Succeeded { get; set; } } public class HighLevelCompileResult { public IDxcBlob Blob { get; set; } public string ResultText { get; set; } } public class OptimizeResult { public IDxcBlob Module { get; set; } public string ResultText { get; set; } public bool Succeeded { get; set; } } public static AssembleResult RunAssembly(IDxcLibrary library, IDxcBlob source) { IDxcBlob resultBlob = null; string resultText = ""; bool succeeded; var assembler = HlslDxcLib.CreateDxcAssembler(); var result = assembler.AssembleToContainer(source); if (result.GetStatus() == 0) { resultBlob = result.GetResult(); succeeded = true; } else { resultText = GetStringFromBlob(library, result.GetErrors()); succeeded = false; } return new AssembleResult() { Blob = resultBlob, ResultText = resultText, Succeeded = succeeded }; } public HighLevelCompileResult RunHighLevelCompile() { IDxcCompiler compiler = HlslDxcLib.CreateDxcCompiler(); string fileName = "hlsl.hlsl"; HlslFileVariables fileVars = GetFileVars(); List<string> args = new List<string>(); args.Add("-fcgl"); args.AddRange(tbOptions.Text.Split()); string resultText = ""; IDxcBlob source = null; { try { var result = compiler.Compile(this.CreateBlobForCodeText(), fileName, fileVars.Entry, fileVars.Target, args.ToArray(), args.Count, null, 0, library.CreateIncludeHandler()); if (result.GetStatus() == 0) { source = result.GetResult(); } else { resultText = GetStringFromBlob(result.GetErrors()); } } catch (System.ArgumentException e) { MessageBox.Show(this, $"{e.Message}.", "Invalid form entry"); } } return new HighLevelCompileResult() { Blob = source, ResultText = resultText }; } public static OptimizeResult RunOptimize(IDxcLibrary library, string[] options, string source) { return RunOptimize(library, options, CreateBlobForText(library, source)); } public static OptimizeResult RunOptimize(IDxcLibrary library, string[] options, IDxcBlob source) { IDxcOptimizer opt = HlslDxcLib.CreateDxcOptimizer(); IDxcBlob module = null; string resultText = ""; IDxcBlobEncoding text; bool succeeded = true; try { opt.RunOptimizer(source, options, options.Length, out module, out text); resultText = GetStringFromBlob(library, text); } catch (Exception optException) { succeeded = false; resultText = "Failed to run optimizer: " + optException.Message; } return new OptimizeResult() { Module = module, ResultText = resultText, Succeeded = succeeded }; } private void InteractiveEditorButton_Click(object sender, EventArgs e) { // Do a high-level only compile. HighLevelCompileResult compile = RunHighLevelCompile(); if (compile.Blob == null) { MessageBox.Show("Failed to compile: " + compile.ResultText); return; } string[] options = CreatePassOptions(false, true); OptimizeResult opt = RunOptimize(this.Library, options, compile.Blob); if (!opt.Succeeded) { MessageBox.Show("Failed to optimize: " + opt.ResultText); return; } OptEditorForm form = new OptEditorForm(); form.CodeFont = this.CodeBox.Font; form.HighLevelSource = compile.Blob; form.Library = this.Library; form.Sections = TextSection.EnumerateSections(new string[] { "MODULE-PRINT", "Phase:" }, opt.ResultText).ToArray(); form.StartPosition = FormStartPosition.CenterParent; form.Show(this); } private void CodeBox_HelpRequested(object sender, HelpEventArgs hlpevent) { RichTextBox rtb = this.CodeBox; SelectionExpandResult expand = SelectionExpandResult.Expand(rtb); if (expand.IsEmpty) return; string readmeText; using (System.IO.StreamReader reader = new System.IO.StreamReader(System.Reflection.Assembly.GetEntryAssembly().GetManifestResourceStream("MainNs.README.md"))) { readmeText = reader.ReadToEnd(); } this.HelpControl.Text = readmeText; (this.HelpTabPage.Parent as TabControl).SelectedTab = this.HelpTabPage; int pos = readmeText.IndexOf(expand.Token, StringComparison.InvariantCultureIgnoreCase); if (pos >= 0) { this.HelpControl.Select(pos, 0); this.HelpControl.ScrollToCaret(); } } } public static class RichTextBoxExt { public static void AppendLine(this RichTextBox rtb, string line, Color c) { rtb.SelectionBackColor = c; rtb.AppendText(line); rtb.AppendText("\r\n"); } public static void AppendLines(this RichTextBox rtb, string prefix, string[] lines, int start, int length, Color c) { for (int i = start; i < (start + length); ++i) { rtb.AppendLine(prefix + lines[i], c); } } public static IEnumerable<string> ToStringEnumerable(this ListBox.ObjectCollection collection) { foreach (var item in collection) yield return item.ToString(); } } }
38.623677
192
0.501788
[ "MIT" ]
AlexScapillati/RenderingEngine
Source/External/dxc/tools/clang/tools/dotnetc/EditorForm.cs
135,069
C#
namespace Sharpdown { internal enum MarkdownInHtmlMode { NA, Block, Span, Deep, Off } }
12.636364
36
0.47482
[ "MIT" ]
stevancorre/sharpdown
src/MarkdownInHtmlMode.cs
139
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SoundManager : Singleton<SoundManager> { AudioPlayer m_AudioPlayer; public AudioPlayer AudioPlayer { get { return m_AudioPlayer; } } Player m_Player; GameObject m_PlayerGameObject; bool m_First = false; AnimationState m_CurrentAnimationState; float m_MainSoundStartVolume; public float FadeToSwitchBackgroundSounds = 0.35f; // Start is called before the first frame update void Start() { m_AudioPlayer = GetComponent<AudioPlayer>(); PlayInsideAmbientSound(); } public void DestroyAudioListener() { if(transform.childCount > 0) Destroy(transform.GetChild(0).gameObject); } public void PlayClickSound() { m_AudioPlayer.PlayOnce("Click"); } public void PlayDialogueSound() { m_AudioPlayer.PlayOnce("DialagueTyping"); } public float GetDialogueSoundLength() { return m_AudioPlayer.GetAudioClipLength("DialagueTyping"); } private void Update() { if (GameplayManager.Instance.GameplayStarted) { if(!m_First) { GameObject playerGameObject = GameObject.FindGameObjectWithTag("Player"); if (!(playerGameObject && playerGameObject.activeSelf)) return; m_Player = playerGameObject.GetComponent<Player>(); m_AudioPlayer.PlayLoop("MainMusic", 0); m_MainSoundStartVolume = m_AudioPlayer.GetLoopVolumeScale("MainMusic"); if (m_Player.environment.Equals(EnvironmentType.Garden)) PlayOutsideAmbientSound(); else PlayInsideAmbientSound(); m_First = true; } AnimationState currAnimState = StoryManager.Instance.AnimationState; if(!m_CurrentAnimationState.Equals(currAnimState) && !currAnimState.Equals(AnimationState.Stop)) { if(m_AudioPlayer.IsLoopPlaying("MainMusic")) m_AudioPlayer.StopLoop("MainMusic"); StopAmbientSound(); } else if(!m_CurrentAnimationState.Equals(currAnimState) && currAnimState.Equals(AnimationState.Stop)) { StopSimulation(); m_AudioPlayer.PlayLoop("MainMusic", 0); if (m_Player.environment.Equals(EnvironmentType.Garden)) PlayOutsideAmbientSound(); else PlayInsideAmbientSound(); } m_CurrentAnimationState = currAnimState; } } public void PlayOutsideAmbientSound() { if (m_AudioPlayer.IsLoopPlaying("MainMusic")) m_AudioPlayer.SetLoopVolumeScale("MainMusic", m_MainSoundStartVolume / 4, 0.35f); if(m_AudioPlayer.IsLoopPlaying("AmbientWindInside")) { m_AudioPlayer.StopLoop("AmbientWindInside", FadeToSwitchBackgroundSounds); m_AudioPlayer.StopLoop("AmbientWindInsideExtras", FadeToSwitchBackgroundSounds); } m_AudioPlayer.PlayLoop("AmbientWindOutside", FadeToSwitchBackgroundSounds); m_AudioPlayer.PlayLoop("AmbientWindOutsideExtras", FadeToSwitchBackgroundSounds); m_AudioPlayer.PlayLoop("AmbientWindOutsideDogs", FadeToSwitchBackgroundSounds); } public void StopAmbientSound() { if (m_AudioPlayer.IsLoopPlaying("AmbientWindOutside")) { m_AudioPlayer.StopLoop("AmbientWindOutside"); m_AudioPlayer.StopLoop("AmbientWindOutsideExtras"); m_AudioPlayer.StopLoop("AmbientWindOutsideDogs"); } if (m_AudioPlayer.IsLoopPlaying("AmbientWindInside")) { m_AudioPlayer.StopLoop("AmbientWindInside"); m_AudioPlayer.StopLoop("AmbientWindInsideExtras"); } } public void StopSimulation() { if (m_AudioPlayer.IsLoopPlaying("RewindSimulation")) m_AudioPlayer.StopLoop("RewindSimulation"); if (m_AudioPlayer.IsLoopPlaying("PlaySimulation")) m_AudioPlayer.StopLoop("PlaySimulation"); } public void PlaySimulation() { //if(m_AudioPlayer.IsLoopPlaying("StopSimulation")) if(m_AudioPlayer.IsLoopPlaying("RewindSimulation")) m_AudioPlayer.StopLoop("RewindSimulation"); m_AudioPlayer.PlayLoop("PlaySimulation"); } public void RewindSimulation() { if (m_AudioPlayer.IsLoopPlaying("PlaySimulation")) m_AudioPlayer.StopLoop("PlaySimulation"); m_AudioPlayer.PlayLoop("RewindSimulation"); } public void PlayInsideAmbientSound() { if(m_AudioPlayer.IsLoopPlaying("AmbientWindOutside")) { m_AudioPlayer.StopLoop("AmbientWindOutsideExtras", FadeToSwitchBackgroundSounds); m_AudioPlayer.StopLoop("AmbientWindOutsideDogs", FadeToSwitchBackgroundSounds); m_AudioPlayer.StopLoop("AmbientWindOutside", FadeToSwitchBackgroundSounds); } if (m_AudioPlayer.IsLoopPlaying("MainMusic")) m_AudioPlayer.SetLoopVolumeScale("MainMusic", m_MainSoundStartVolume, 0.35f); m_AudioPlayer.PlayLoop("AmbientWindInside", FadeToSwitchBackgroundSounds); m_AudioPlayer.PlayLoop("AmbientWindInsideExtras", FadeToSwitchBackgroundSounds); } }
33.204819
112
0.642054
[ "Apache-2.0" ]
adrianrodriguesm/Detective-Z
Assets/Scripts/SoundManager.cs
5,512
C#
using System.ComponentModel; using System.Drawing; using YamlDotNet.Serialization; namespace HSDRawViewer.Rendering.GX { public class GXLightParam { [Category("1. Lighting Settings"), DisplayName("Use Camera Light"), Description("When true makes the light source emit from the camera's location")] public bool UseCameraLight { get; set; } = true; [Category("1. Lighting Settings"), DisplayName("Light X"), Description("X position of light in world when camera light is disabled")] public float LightX { get; set; } = 0; [Category("1. Lighting Settings"), DisplayName("Light Y"), Description("Y position of light in world when camera light is disabled")] public float LightY { get; set; } = 10; [Category("1. Lighting Settings"), DisplayName("Light Z"), Description("Z position of light in world when camera light is disabled")] public float LightZ { get; set; } = 50; [Category("2. Lighting Color"), DisplayName("Ambient Intensity"), Description("The intensity of the ambient lighting")] public float AmbientPower { get; set; } = 0.5f; [Category("2. Lighting Color"), DisplayName("Ambient Color"), Description("The color of the ambient light")] [YamlIgnore] public Color AmbientColor { get; set; } = Color.White; [Browsable(false)] public byte AmbientR { get => AmbientColor.R; set => AmbientColor = Color.FromArgb(AmbientColor.A, value, AmbientColor.G, AmbientColor.B); } [Browsable(false)] public byte AmbientG { get => AmbientColor.G; set => AmbientColor = Color.FromArgb(AmbientColor.A, AmbientColor.R, value, AmbientColor.B); } [Browsable(false)] public byte AmbientB { get => AmbientColor.B; set => AmbientColor = Color.FromArgb(AmbientColor.A, AmbientColor.R, AmbientColor.G, value); } [Category("2. Lighting Color"), DisplayName("Diffuse Intensity"), Description("The intensity of the diffuse lighting")] public float DiffusePower { get; set; } = 1; [Category("2. Lighting Color"), DisplayName("Diffuse Color"), Description("The color of the diffuse light")] [YamlIgnore] public Color DiffuseColor { get; set; } = Color.White; [Browsable(false)] public byte DiffuseR { get => DiffuseColor.R; set => DiffuseColor = Color.FromArgb(DiffuseColor.A, value, DiffuseColor.G, DiffuseColor.B); } [Browsable(false)] public byte DiffuseG { get => DiffuseColor.G; set => DiffuseColor = Color.FromArgb(DiffuseColor.A, DiffuseColor.R, value, DiffuseColor.B); } [Browsable(false)] public byte DiffuseB { get => DiffuseColor.B; set => DiffuseColor = Color.FromArgb(DiffuseColor.A, DiffuseColor.R, DiffuseColor.G, value); } [Category("3. Enhancements"), DisplayName("Use Per Pixel Lighting"), Description("Calculates lighting per pixel for a smoother look. Set to false for gamecube style.")] public bool UsePerPixelLighting { get; set; } = true; [Category("3. Enhancements"), DisplayName("Adjust Saturation"), Description("")] public float Saturation { get; set; } = 1; /// <summary> /// /// </summary> /// <param name="shader"></param> public void Bind(Shader shader) { shader.SetFloat("saturate", Saturation); shader.SetBoolToInt("perPixelLighting", UsePerPixelLighting); shader.SetBoolToInt("light.useCamera", UseCameraLight); shader.SetVector3("light.position", LightX, LightY, LightZ); shader.SetColor("light.ambient", AmbientColor, 1); shader.SetFloat("light.ambientPower", AmbientPower); shader.SetColor("light.diffuse", DiffuseColor, 1); shader.SetFloat("light.diffusePower", DiffusePower); //shader.SetColor("light.specular", settings.SpecularColor, 1); //shader.SetFloat("light.specularPower", settings.SpecularPower); } } }
50.1
176
0.657934
[ "MIT" ]
Ploaj/HSDLib
HSDRawViewer/Rendering/GX/GXLightParam.cs
4,010
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30311.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace NuGetGallery { public partial class EnumerationField { protected global::System.Web.UI.WebControls.Literal Literal1; } }
29.421053
80
0.463327
[ "Apache-2.0" ]
0xced/NuGetGallery
src/NuGetGallery/Areas/Admin/DynamicData/FieldTemplates/Enumeration.ascx.designer.cs
559
C#
/* The MIT License (MIT) Copyright (c) 2020 Simon Bogutzky 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 RollerShutter.NET; using UIKit; namespace RollerShutter.iOS { public partial class ViewController : UIViewController { private readonly RollerShutterManager _manager = new RollerShutterManager("192.168.2.56"); public ViewController(IntPtr handle) : base(handle) { } async partial void StopButton_TouchUpInside(UIButton sender) { sender.Enabled = false; await _manager.Stop(); sender.Enabled = true; } async partial void UpButton_TouchUpInside(UIButton sender) { sender.Enabled = false; await _manager.MoveUp(); sender.Enabled = true; } async partial void DownButton_TouchUpInside(UIButton sender) { sender.Enabled = false; await _manager.MoveDown(); sender.Enabled = true; } public override void ViewDidLoad() { base.ViewDidLoad(); } public override void DidReceiveMemoryWarning() { base.DidReceiveMemoryWarning(); } } }
39.280702
461
0.685574
[ "MIT" ]
sbogutzky/RollerShutterApp
iOS/ViewController.cs
2,249
C#
using System; using System.ComponentModel.DataAnnotations.Schema; namespace SmartSchool.Core.Entities { public class Measurement : EntityObject { public int SensorId { get; set; } [ForeignKey(nameof(SensorId))] public Sensor Sensor { get; set; } public DateTime Time { get; set; } public double Value { get; set; } } }
18.9
51
0.637566
[ "MIT" ]
BernhardGrasch/csharp_samples_ef_uow_smartschool-template
source/SmartSchool.Core/Entities/Measurement.cs
380
C#
using System; using UnityEngine; using UnityEngine.Assertions; [CreateAssetMenu(fileName = "Data", menuName = "ScriptableObjects/Weighted Pool")] public class WeightedPoolAsset : ScriptableObject { [Serializable] public class Entry { public GameObject contextGameObject; // but this can be anything really, an enum, int, string, prefab. public float weight; }; public Entry[] entries; public Entry Random() { Assert.IsNotNull(entries, "Weighted Pool " + this.name + " has zero entries"); var totalWeight = 0.0f; // this stores sum of weights of all elements before current var selected = entries[0]; foreach (var entry in entries) { var r = UnityEngine.Random.value * (totalWeight + entry.weight); // random value if (r >= totalWeight) // probability of this is weight/(totalWeight+weight) selected = entry; // it is the probability of discarding last selected element and selecting current one instead totalWeight += entry.weight; // increase weight sum } Assert.IsNotNull(selected); return selected; } }
33.828571
128
0.647804
[ "MIT" ]
ChrisMasterton/SomeUnityUtils
WeightedPool/WeightedPoolAsset.cs
1,186
C#
using System.Text; using System.Web; using System.Collections.Specialized; using System.Diagnostics.CodeAnalysis; namespace SmartStore.Collections { /// <summary> /// http://weblogs.asp.net/bradvincent/archive/2008/10/27/helper-class-querystring-builder-chainable.aspx /// </summary> public class QueryString : NameValueCollection { public QueryString() { } public QueryString(string queryString) { FillFromString(queryString); } public QueryString(NameValueCollection queryString) : base(queryString) { } public static QueryString Current { get { return new QueryString().FromCurrent(); } } /// <summary> /// Extracts a querystring from a full URL /// </summary> /// <param name="s">the string to extract the querystring from</param> /// <returns>a string representing only the querystring</returns> [SuppressMessage("ReSharper", "StringIndexOfIsCultureSpecific.1")] public static string ExtractQuerystring(string s) { if (!string.IsNullOrEmpty(s)) { if (s.Contains("?")) { return s.Substring(s.IndexOf("?") + 1); } } return s; } /// <summary> /// returns a querystring object based on a string /// </summary> /// <param name="s">the string to parse</param> /// <returns>the QueryString object </returns> public QueryString FillFromString(string s, bool urlDecode = false) { base.Clear(); if (string.IsNullOrEmpty(s)) { return this; } foreach (string keyValuePair in ExtractQuerystring(s).Split('&')) { if (string.IsNullOrEmpty(keyValuePair)) { continue; } string[] split = keyValuePair.Split('='); base.Add(split[0], split.Length == 2 ? (urlDecode ? HttpUtility.UrlDecode(split[1]) : split[1]) : ""); } return this; } /// <summary> /// returns a QueryString object based on the current querystring of the request /// </summary> /// <returns>the QueryString object </returns> public QueryString FromCurrent() { if (HttpContext.Current != null) { return FillFromString(HttpContext.Current.Request.QueryString.ToString(), true); } base.Clear(); return this; } /// <summary> /// add a name value pair to the collection /// </summary> /// <param name="name">the name</param> /// <param name="value">the value associated to the name</param> /// <returns>the QueryString object </returns> public new QueryString Add(string name, string value) { return Add(name, value, false); } /// <summary> /// Adds a name value pair to the collection /// </summary> /// <param name="name">the name</param> /// <param name="value">the value associated to the name</param> /// <param name="isUnique">true if the name is unique within the querystring. This allows us to override existing values</param> /// <returns>the QueryString object </returns> public QueryString Add(string name, string value, bool isUnique) { string existingValue = base[name]; if (string.IsNullOrEmpty(existingValue)) { base.Add(name, HttpUtility.UrlEncode(value)); } else if (isUnique) { base[name] = HttpUtility.UrlEncode(value); } else { base[name] += "," + HttpUtility.UrlEncode(value); } return this; } /// <summary> /// Removes a name value pair from the querystring collection /// </summary> /// <param name="name">name of the querystring value to remove</param> /// <returns>the QueryString object</returns> public new QueryString Remove(string name) { string existingValue = base[name]; if (!string.IsNullOrEmpty(existingValue)) { base.Remove(name); } return this; } /// <summary> /// clears the collection /// </summary> /// <returns>the QueryString object </returns> public QueryString Reset() { base.Clear(); return this; } /// <summary> /// overrides the default /// </summary> /// <param name="name"></param> /// <returns>the associated decoded value for the specified name</returns> public new string this[string name] { get { return HttpUtility.UrlDecode(base[name]); } } /// <summary> /// overrides the default indexer /// </summary> /// <param name="index"></param> /// <returns>the associated decoded value for the specified index</returns> public new string this[int index] { get { return HttpUtility.UrlDecode(base[index]); } } /// <summary> /// checks if a name already exists within the query string collection /// </summary> /// <param name="name">the name to check</param> /// <returns>a boolean if the name exists</returns> public bool Contains(string name) { string existingValue = base[name]; return !string.IsNullOrEmpty(existingValue); } /// <summary> /// Outputs the querystring object to a string /// </summary> /// <returns>the encoded querystring as it would appear in a browser</returns> public override string ToString() { return ToString(true); } /// <summary> /// Outputs the querystring object to a string /// </summary> /// <param name="splitValues">Whether to create entries for each comma-separated value</param> /// <returns>the encoded querystring as it would appear in a browser</returns> public string ToString(bool splitValues) { var builder = new StringBuilder(); for (var i = 0; i < base.Keys.Count; i++) { var key = base.Keys[i]; var value = base[key]; if (!string.IsNullOrEmpty(key)) { builder.Append((builder.Length == 0) ? "?" : "&"); if (splitValues) { foreach (string val in value.EmptyNull().Split(',')) { builder.Append(HttpUtility.UrlEncode(key)).Append("=").Append(val); } } else { builder.Append(HttpUtility.UrlEncode(key)).Append("=").Append(value); } } } return builder.ToString(); } } }
30.779736
136
0.544583
[ "MIT" ]
jenmcquade/csharp-snippets
SmartStoreNET-3.x/src/Libraries/SmartStore.Core/Collections/Querystring.cs
6,989
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.IO; using UnityEditor; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.Editor { /// <summary> /// Unity has a strange bug when it tries to import a DLL with a ScriptedImporter and an asset that importer is targeting. /// The first time, it will not invoke the ScriptedImporter as it's just being imported itself; the second time the ScriptedImporter will be constructed but Unity thinks it fails. /// The third time, the import will succeed. This class will invoke the third time import for .gltf, .glb and .room extensions. /// </summary> public class ScriptedImporterAssetReimporter : AssetPostprocessor { private static readonly Dictionary<string, int> assetsAttemptedToReimport = new Dictionary<string, int>(); public static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) { foreach (string asset in importedAssets) { // Ignore the StreamingAssets folder, as this appears to not be required and generates console warnings. if (asset.Contains("Assets/StreamingAssets")) { continue; } string extension = Path.GetExtension(asset); if (extension == ".room" || extension == ".glb" || extension == ".gltf") { Type assetType = AssetDatabase.GetMainAssetTypeAtPath(asset); if (assetType == typeof(DefaultAsset)) { if (!assetsAttemptedToReimport.TryGetValue(asset, out int numAttempts)) { numAttempts = 0; } assetsAttemptedToReimport[asset] = ++numAttempts; if (numAttempts <= 3) { AssetDatabase.ImportAsset(asset); } else { Debug.LogWarning($"Asset '{asset}' appears to have failed the re-import 3 times, will not try again."); } } } } } } }
42.810345
184
0.546516
[ "MIT" ]
HyperLethalVector/ProjectEsky-UnityIntegration
Assets/MRTK/Core/Utilities/Editor/ScriptedImporterAssetReimporter.cs
2,485
C#
using System; using System.Collections.Generic; using System.Linq.Expressions; namespace YEasyModel { /// <summary> /// 排序表达式类型 /// </summary> /// <typeparam name="T">实体类</typeparam> public class OrderBy<T> { Dictionary<Expression<Func<T, object>>, OrderByEnum> orderList; public OrderBy() { orderList = new Dictionary<Expression<Func<T, object>>, OrderByEnum>(); } /// <summary> /// 添加字段排序 /// </summary> /// <param name="field">字段表达式</param> /// <param name="orderByEnum">排序规则</param> public void Add(Expression<Func<T, object>> field, OrderByEnum orderByEnum) { orderList.Add(field, orderByEnum); } /// <summary> /// 获取字段排序表达式 /// </summary> /// <returns></returns> public Dictionary<Expression<Func<T, object>>, OrderByEnum> GetOrderByList() { return orderList; } } }
24.825
84
0.548842
[ "Apache-2.0" ]
michaelyes/LiteORM-For-DotNet
ClassLibrary1/OrderBy.cs
1,063
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Undersoft.Picatch.Agent { using System; using System.Collections.Generic; public partial class dok { public int id { get; set; } public string nazwadok { get; set; } public string typ { get; set; } public Nullable<System.DateTime> data { get; set; } public string device { get; set; } } }
32.708333
84
0.51465
[ "MIT" ]
undersoft-org/NET.Undersoft.Picatch.Devel
NET.Undersoft.Picatch.Agent.Win/Undersoft.Picatch.Agent/dok.cs
785
C#
using System; using Microsoft.Owin.Security.Infrastructure; using Microsoft.Owin; using Owin; using Microsoft.Owin.Logging; using System.Net.Http; using Beginor.Owin.Security.Gdep.Provider; using Microsoft.Owin.Security.DataProtection; using Microsoft.Owin.Security.DataHandler; using Microsoft.Owin.Security; namespace Beginor.Owin.Security.Gdep { public class GdepAuthenticationMiddleware : AuthenticationMiddleware<GdepAuthenticationOptions> { private ILogger logger; private HttpClient httpClient; public GdepAuthenticationMiddleware( OwinMiddleware next, IAppBuilder app, GdepAuthenticationOptions options ) : base(next, options) { if (string.IsNullOrEmpty(Options.AppId)) { throw new ArgumentException("AppId must be provided."); } if (string.IsNullOrEmpty(Options.AppSecret)) { throw new ArgumentException("AppSecret must be provided."); } logger = app.CreateLogger<GdepAuthenticationMiddleware>(); if (Options.Provider == null) { Options.Provider = new GdepAuthenticationProvider(); } if (Options.StateDataFormat == null) { var dataProtector = app.CreateDataProtector( typeof(GdepAuthenticationMiddleware).FullName, Options.AuthenticationType, "v1" ); Options.StateDataFormat = new PropertiesDataFormat(dataProtector); } if (string.IsNullOrEmpty(Options.SignInAsAuthenticationType)) { Options.SignInAsAuthenticationType = app.GetDefaultSignInAsAuthenticationType(); } httpClient = new HttpClient(ResolveHttpMessageHandler(Options)); httpClient.Timeout = Options.BackchannelTimeout; httpClient.MaxResponseContentBufferSize = 1024 * 1024 * 10; // 10M } protected override AuthenticationHandler<GdepAuthenticationOptions> CreateHandler() { return new GdepAuthenticationHandler(httpClient, logger); } private static HttpMessageHandler ResolveHttpMessageHandler(GdepAuthenticationOptions options) { HttpMessageHandler handler = options.BackchannelHttpHandler ?? new WebRequestHandler(); if (options.BackchannelCertificateValidator != null) { var webRequestHandler = handler as WebRequestHandler; if (webRequestHandler == null) { throw new InvalidOperationException("Validator handler is mismatch!"); } webRequestHandler.ServerCertificateValidationCallback = options.BackchannelCertificateValidator.Validate; } return handler; } } }
37.038961
121
0.65007
[ "MIT" ]
beginor/beginor-owin-security-gdep
src/Beginor.Owin.Security.Gdep/GdepAuthenticationMiddleware.cs
2,854
C#
using System; using System.Collections.Generic; using System.Text; namespace KLib { public class KDataFormat { public const SByte BYTE = 1; public const SByte INT = 4; public const SByte UINT = 6; public const SByte NUMBER = 10; public const SByte BOOLEAN = 15; public const SByte STRING = 20; public const SByte BINARY = 30; public const SByte ARRAY = 40; public const SByte TABLE = 50; public const SByte DATE = 60; public const SByte ERROR = 100; public const SByte OBJECT = 120; //不要这个类型了 //public const SByte NULL = 127; } }
18.153846
41
0.559322
[ "MIT" ]
linchenrr/kakaTools
donetCore/KLib/KLib/data/KDataFormat.cs
724
C#
/* Movement.cs - Moves a player around the scene */ using System.Collections; using System.Collections.Generic; using UnityEngine; public class Movement : MonoBehaviour { // Character movement and physics [Header("Character Physics")] public float moveForce = 365f; public float maxSpeed = 5f; public float jumpForce = 1000f; public Transform groundCheck; [HideInInspector] public bool jump = false; private bool grounded = false; private bool facingRight = true; private Rigidbody2D rb2d; // Get Input from the player/CPU private Controls controls; // Get overall state for this fighter private Fighter fighter; // Use this for initialization void Start () { rb2d = GetComponent<Rigidbody2D>(); controls = GetComponent<Controls>(); fighter = GetComponent<Fighter>(); } // Update is called once per frame void Update () { // Jumping grounded = Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground")); if (!fighter.busy && controls.Vertical() > 0 && grounded) { jump = true; } } void FixedUpdate() { if(!fighter.busy) { // Make sure fighter isn't already doing something float h = controls.Horizontal(); if (h * rb2d.velocity.x < maxSpeed) { rb2d.AddForce(Vector2.right * h * moveForce); } if (Mathf.Abs (rb2d.velocity.x) > maxSpeed) { rb2d.velocity = new Vector2(Mathf.Sign (rb2d.velocity.x) * maxSpeed, rb2d.velocity.y); } if (h > 0 && !facingRight) { Flip (); } else if (h < 0 && facingRight) { Flip (); } if (jump) { rb2d.AddForce(new Vector2(0f, jumpForce)); jump = false; } } } void Flip() { facingRight = !facingRight; Vector3 theScale = transform.localScale; theScale.x *= -1; transform.localScale = theScale; } }
22.46988
112
0.64933
[ "MIT" ]
bdickason/mobifight
Assets/Characters/Movement.cs
1,867
C#
using System.Collections.Generic; using System.Linq; using Blockcore.Consensus.ScriptInfo; using Blockcore.Consensus.TransactionInfo; using Blockcore.Networks; using NBitcoin; using NBitcoin.BitcoinCore; namespace OpenExo.Networks.Policies { /// <summary> /// Blockcore sample coin-specific standard transaction definitions. /// </summary> public class OpenExoStandardScriptsRegistry : StandardScriptsRegistry { // See MAX_OP_RETURN_RELAY in Bitcoin Core, <script/standard.h.> // 80 bytes of data, +1 for OP_RETURN, +2 for the pushdata opcodes. public const int MaxOpReturnRelay = 83; // Need a network-specific version of the template list private readonly List<ScriptTemplate> standardTemplates = new List<ScriptTemplate> { PayToPubkeyHashTemplate.Instance, PayToPubkeyTemplate.Instance, PayToScriptHashTemplate.Instance, PayToMultiSigTemplate.Instance, new TxNullDataTemplate(MaxOpReturnRelay), PayToWitTemplate.Instance }; public override List<ScriptTemplate> GetScriptTemplates => standardTemplates; public override void RegisterStandardScriptTemplate(ScriptTemplate scriptTemplate) { if (!standardTemplates.Any(template => (template.Type == scriptTemplate.Type))) { standardTemplates.Add(scriptTemplate); } } public override bool IsStandardTransaction(Transaction tx, Network network) { return base.IsStandardTransaction(tx, network); } public override bool AreOutputsStandard(Network network, Transaction tx) { return base.AreOutputsStandard(network, tx); } public override ScriptTemplate GetTemplateFromScriptPubKey(Script script) { return standardTemplates.FirstOrDefault(t => t.CheckScriptPubKey(script)); } public override bool IsStandardScriptPubKey(Network network, Script scriptPubKey) { return base.IsStandardScriptPubKey(network, scriptPubKey); } public override bool AreInputsStandard(Network network, Transaction tx, CoinsView coinsView) { return base.AreInputsStandard(network, tx, coinsView); } } }
35
100
0.675906
[ "MIT" ]
Botcoin-Abacus/blockcore
src/Networks/Blockcore.Networks.OpenExo/Networks/Policies/OpenExoStandardScriptRegistry.cs
2,347
C#
namespace RJCP.Diagnostics.Log.Dlt.Control { using ControlArgs; using NUnit.Framework; using RJCP.Core; [TestFixture(DecoderType.Line, Endianness.Little)] [TestFixture(DecoderType.Packet, Endianness.Little)] [TestFixture(DecoderType.Specialized, Endianness.Little)] [TestFixture(DecoderType.Line, Endianness.Big)] [TestFixture(DecoderType.Packet, Endianness.Big)] [TestFixture(DecoderType.Specialized, Endianness.Big)] public class BufferOverflowNotificationDecoderTest : ControlDecoderTestBase<BufferOverflowNotificationRequestDecoder, BufferOverflowNotificationResponseDecoder> { public BufferOverflowNotificationDecoderTest(DecoderType decoderType, Endianness endian) : base(decoderType, endian, 0x23, typeof(BufferOverflowNotificationRequest), typeof(BufferOverflowNotificationResponse)) { } [Test] public void DecodeRequest() { byte[] payload = Endian == Endianness.Little ? new byte[] { 0x23, 0x00, 0x00, 0x00 } : new byte[] { 0x00, 0x00, 0x00, 0x23 }; Decode(DltType.CONTROL_REQUEST, payload, "0x23_BufferOverflowNotificationRequest", out IControlArg service); BufferOverflowNotificationRequest request = (BufferOverflowNotificationRequest)service; Assert.That(request.ToString(), Is.EqualTo("[buffer_overflow]")); } [TestCase(0x00, new byte[] { 0x00, 0x00, 0x00, 0x00 }, "[buffer_overflow ok] 0", TestName = "DecodeResponsePositive")] [TestCase(0x00, new byte[] { 0x00, 0x00, 0x27, 0x10 }, "[buffer_overflow ok] 10000", TestName = "DecodeResponsePositive10000")] [TestCase(0x00, new byte[] { 0xFF, 0xFF, 0xFF, 0xFF }, "[buffer_overflow ok] 4294967295", TestName = "DecodeResponsePositiveLarge")] public void DecodeResponse(byte status, byte[] data, string result) { int counter = BitOperations.To32ShiftBigEndian(data, 0); byte[] payload = Endian == Endianness.Little ? new byte[] { 0x23, 0x00, 0x00, 0x00, status, data[3], data[2], data[1], data[0] } : new byte[] { 0x00, 0x00, 0x00, 0x23, status, data[0], data[1], data[2], data[3] }; Decode(DltType.CONTROL_RESPONSE, payload, $"0x23_BufferOverflowNotificationResponse_{status:x2}_{counter:x08}", out IControlArg service); BufferOverflowNotificationResponse response = (BufferOverflowNotificationResponse)service; Assert.That(response.Status, Is.EqualTo(status)); Assert.That(response.ToString(), Is.EqualTo(result)); Assert.That(response.Counter, Is.EqualTo(counter)); } [TestCase(0x01, "[buffer_overflow not_supported]")] [TestCase(0x02, "[buffer_overflow error]")] public void DecodeResponseError(byte status, string result) { byte[] payload = Endian == Endianness.Little ? new byte[] { 0x23, 0x00, 0x00, 0x00, status } : new byte[] { 0x00, 0x00, 0x00, 0x23, status }; Decode(DltType.CONTROL_RESPONSE, payload, $"0x23_BufferOverflowNotificationResponse_{status:x2}_Error", out IControlArg service); ControlErrorNotSupported response = (ControlErrorNotSupported)service; Assert.That(response.ServiceId, Is.EqualTo(0x23)); Assert.That(response.Status, Is.EqualTo(status)); Assert.That(response.ToString(), Is.EqualTo(result)); } } }
53.938462
149
0.667998
[ "MIT" ]
jcurl/RJCP.DLL.Log
TraceReader.Dlt/DltTraceReaderTest/Dlt/Control/BufferOverflowNotificationDecoderTest.cs
3,508
C#
//------------------------------------------------------------------------------ // <copyright file="ExternDll.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System { internal class ExternDll { public const string DbNetLib = "dbnetlib.dll"; public const string Kernel32 = "kernel32.dll"; public const string Odbc32 = "odbc32.dll"; public const string Oleaut32 = "oleaut32.dll"; public const string Ole32 = "ole32.dll"; public const string Advapi32 = "advapi32.dll"; } }
36.736842
81
0.485673
[ "Unlicense" ]
bestbat/Windows-Server
com/netfx/src/framework/data/system/data/common/externdll.cs
698
C#
// Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. using System; using System.Numerics; using System.Runtime.CompilerServices; namespace SixLabors.ImageSharp.PixelFormats { /// <summary> /// Packed pixel type containing four 8-bit unsigned integer values, ranging from 0 to 255. /// <para> /// Ranges from [0, 0, 0, 0] to [255, 255, 255, 255] in vector form. /// </para> /// </summary> public struct Byte4 : IPixel<Byte4>, IPackedVector<uint> { /// <summary> /// Initializes a new instance of the <see cref="Byte4"/> struct. /// </summary> /// <param name="vector"> /// A vector containing the initial values for the components of the Byte4 structure. /// </param> public Byte4(Vector4 vector) => this.PackedValue = Pack(ref vector); /// <summary> /// Initializes a new instance of the <see cref="Byte4"/> struct. /// </summary> /// <param name="x">The x-component</param> /// <param name="y">The y-component</param> /// <param name="z">The z-component</param> /// <param name="w">The w-component</param> public Byte4(float x, float y, float z, float w) { var vector = new Vector4(x, y, z, w); this.PackedValue = Pack(ref vector); } /// <inheritdoc/> public uint PackedValue { get; set; } /// <summary> /// Compares two <see cref="Byte4"/> objects for equality. /// </summary> /// <param name="left">The <see cref="Byte4"/> on the left side of the operand.</param> /// <param name="right">The <see cref="Byte4"/> on the right side of the operand.</param> /// <returns> /// True if the <paramref name="left"/> parameter is equal to the <paramref name="right"/> parameter; otherwise, false. /// </returns> [MethodImpl(InliningOptions.ShortMethod)] public static bool operator ==(Byte4 left, Byte4 right) => left.Equals(right); /// <summary> /// Compares two <see cref="Byte4"/> objects for equality. /// </summary> /// <param name="left">The <see cref="Byte4"/> on the left side of the operand.</param> /// <param name="right">The <see cref="Byte4"/> on the right side of the operand.</param> /// <returns> /// True if the <paramref name="left"/> parameter is not equal to the <paramref name="right"/> parameter; otherwise, false. /// </returns> [MethodImpl(InliningOptions.ShortMethod)] public static bool operator !=(Byte4 left, Byte4 right) => !left.Equals(right); /// <inheritdoc /> public readonly PixelOperations<Byte4> CreatePixelOperations() => new PixelOperations<Byte4>(); /// <inheritdoc/> [MethodImpl(InliningOptions.ShortMethod)] public void FromScaledVector4(Vector4 vector) => this.FromVector4(vector * 255F); /// <inheritdoc/> [MethodImpl(InliningOptions.ShortMethod)] public readonly Vector4 ToScaledVector4() => this.ToVector4() / 255F; /// <inheritdoc /> [MethodImpl(InliningOptions.ShortMethod)] public void FromVector4(Vector4 vector) => this.PackedValue = Pack(ref vector); /// <inheritdoc /> [MethodImpl(InliningOptions.ShortMethod)] public readonly Vector4 ToVector4() { return new Vector4( this.PackedValue & 0xFF, (this.PackedValue >> 0x8) & 0xFF, (this.PackedValue >> 0x10) & 0xFF, (this.PackedValue >> 0x18) & 0xFF); } /// <inheritdoc /> [MethodImpl(InliningOptions.ShortMethod)] public void FromArgb32(Argb32 source) => this.FromScaledVector4(source.ToScaledVector4()); /// <inheritdoc /> [MethodImpl(InliningOptions.ShortMethod)] public void FromBgr24(Bgr24 source) => this.FromScaledVector4(source.ToScaledVector4()); /// <inheritdoc /> [MethodImpl(InliningOptions.ShortMethod)] public void FromBgra32(Bgra32 source) => this.FromScaledVector4(source.ToScaledVector4()); /// <inheritdoc/> [MethodImpl(InliningOptions.ShortMethod)] public void FromL8(L8 source) => this.FromScaledVector4(source.ToScaledVector4()); /// <inheritdoc/> [MethodImpl(InliningOptions.ShortMethod)] public void FromL16(L16 source) => this.FromScaledVector4(source.ToScaledVector4()); /// <inheritdoc/> [MethodImpl(InliningOptions.ShortMethod)] public void FromLa16(La16 source) => this.FromScaledVector4(source.ToScaledVector4()); /// <inheritdoc/> [MethodImpl(InliningOptions.ShortMethod)] public void FromLa32(La32 source) => this.FromScaledVector4(source.ToScaledVector4()); /// <inheritdoc /> [MethodImpl(InliningOptions.ShortMethod)] public void FromRgb24(Rgb24 source) => this.FromScaledVector4(source.ToScaledVector4()); /// <inheritdoc /> [MethodImpl(InliningOptions.ShortMethod)] public void FromBgra5551(Bgra5551 source) => this.FromScaledVector4(source.ToScaledVector4()); /// <inheritdoc /> [MethodImpl(InliningOptions.ShortMethod)] public void FromRgba32(Rgba32 source) => this.FromScaledVector4(source.ToScaledVector4()); /// <inheritdoc /> [MethodImpl(InliningOptions.ShortMethod)] public void ToRgba32(ref Rgba32 dest) { dest.FromScaledVector4(this.ToScaledVector4()); } /// <inheritdoc/> [MethodImpl(InliningOptions.ShortMethod)] public void FromRgb48(Rgb48 source) => this.FromScaledVector4(source.ToScaledVector4()); /// <inheritdoc/> [MethodImpl(InliningOptions.ShortMethod)] public void FromRgba64(Rgba64 source) => this.FromScaledVector4(source.ToScaledVector4()); /// <inheritdoc /> public override readonly bool Equals(object obj) => obj is Byte4 byte4 && this.Equals(byte4); /// <inheritdoc /> [MethodImpl(InliningOptions.ShortMethod)] public readonly bool Equals(Byte4 other) => this.PackedValue.Equals(other.PackedValue); /// <inheritdoc /> [MethodImpl(InliningOptions.ShortMethod)] public override readonly int GetHashCode() => this.PackedValue.GetHashCode(); /// <inheritdoc /> public override readonly string ToString() { var vector = this.ToVector4(); return FormattableString.Invariant($"Byte4({vector.X:#0.##}, {vector.Y:#0.##}, {vector.Z:#0.##}, {vector.W:#0.##})"); } /// <summary> /// Packs a vector into a uint. /// </summary> /// <param name="vector">The vector containing the values to pack.</param> /// <returns>The <see cref="uint"/> containing the packed values.</returns> [MethodImpl(InliningOptions.ShortMethod)] private static uint Pack(ref Vector4 vector) { const float Max = 255F; // Clamp the value between min and max values vector = Vector4Utilities.FastClamp(vector, Vector4.Zero, new Vector4(Max)); uint byte4 = (uint)Math.Round(vector.X) & 0xFF; uint byte3 = ((uint)Math.Round(vector.Y) & 0xFF) << 0x8; uint byte2 = ((uint)Math.Round(vector.Z) & 0xFF) << 0x10; uint byte1 = ((uint)Math.Round(vector.W) & 0xFF) << 0x18; return byte4 | byte3 | byte2 | byte1; } } }
41.086486
131
0.610972
[ "Apache-2.0" ]
asmodat/ImageSharp
src/ImageSharp/PixelFormats/PixelImplementations/Byte4.cs
7,601
C#
using System; using System.Collections.Generic; using System.Linq; namespace Core.Math.Polynomials { public static partial class PolynomialExtensionMethods { public static Polynomial<double> Integrate(this Polynomial<int> polynomial, int initial_value) { int n = polynomial.Coefficients.Count(); double[] coefficients_integrated = new double[n+1]; coefficients_integrated[0] = initial_value; for (int i = 0; i < n; i++) { coefficients_integrated[i + 1] = (double) polynomial.Coefficients.ElementAt<int>(i) / (i + 1); } Polynomial<double> integration = new Polynomial<double>(coefficients_integrated); return integration; } public static Polynomial<int> Derive(this Polynomial<int> polynomial) { int n = polynomial.Coefficients.Count(); int[] coefficients_derived = new int[n - 1]; for (int i = 1; i < n - 1; i++) { coefficients_derived[i - 1] = polynomial.Coefficients.ElementAt<int>(i) * i; } Polynomial<int> derivation = new Polynomial<int>(); return derivation; } } }
30.536585
110
0.583866
[ "MIT" ]
HolisticWare/HolisticWare.Core.Math.Polynomials
source/HolisticWare.Core.Math.Polynomials/Core/Math/Polynomials/Polynomial.ExtensionMethods.Calculus.cs
1,254
C#
namespace CommandLineSyntax { public class ProgramConfoguration { [Option] [OptionAlias("--help")] [OptionAlias("-h")] public bool ShowHelp { get; set; } [Option] [OptionAlias("--version")] [OptionAlias("-v")] public bool ShowVersion { get; set; } [MainInputAttribute] public string ThisIsMainArgument { get; set; } } }
23
54
0.557971
[ "MIT" ]
sebastiandymel/CLI-Argument-Parser
src/CommandLineParser/CommandLineSyntax/ProgramConfoguration.cs
416
C#
namespace Example.Library { public class AnotherConfig { public string Name { get; set; } } }
16.285714
40
0.605263
[ "MIT" ]
xpike/settings
examples/Example.Library/AnotherConfig.cs
116
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.Rds.Outputs { [OutputType] public sealed class ProxyDefaultTargetGroupConnectionPoolConfig { /// <summary> /// The number of seconds for a proxy to wait for a connection to become available in the connection pool. Only applies when the proxy has opened its maximum number of connections and all connections are busy with client sessions. /// </summary> public readonly int? ConnectionBorrowTimeout; /// <summary> /// One or more SQL statements for the proxy to run when opening each new database connection. Typically used with `SET` statements to make sure that each connection has identical settings such as time zone and character set. This setting is empty by default. For multiple statements, use semicolons as the separator. You can also include multiple variables in a single `SET` statement, such as `SET x=1, y=2`. /// </summary> public readonly string? InitQuery; /// <summary> /// The maximum size of the connection pool for each target in a target group. For Aurora MySQL, it is expressed as a percentage of the max_connections setting for the RDS DB instance or Aurora DB cluster used by the target group. /// </summary> public readonly int? MaxConnectionsPercent; /// <summary> /// Controls how actively the proxy closes idle database connections in the connection pool. A high value enables the proxy to leave a high percentage of idle connections open. A low value causes the proxy to close idle client connections and return the underlying database connections to the connection pool. For Aurora MySQL, it is expressed as a percentage of the max_connections setting for the RDS DB instance or Aurora DB cluster used by the target group. /// </summary> public readonly int? MaxIdleConnectionsPercent; /// <summary> /// Each item in the list represents a class of SQL operations that normally cause all later statements in a session using a proxy to be pinned to the same underlying database connection. Including an item in the list exempts that class of SQL operations from the pinning behavior. Currently, the only allowed value is `EXCLUDE_VARIABLE_SETS`. /// </summary> public readonly ImmutableArray<string> SessionPinningFilters; [OutputConstructor] private ProxyDefaultTargetGroupConnectionPoolConfig( int? connectionBorrowTimeout, string? initQuery, int? maxConnectionsPercent, int? maxIdleConnectionsPercent, ImmutableArray<string> sessionPinningFilters) { ConnectionBorrowTimeout = connectionBorrowTimeout; InitQuery = initQuery; MaxConnectionsPercent = maxConnectionsPercent; MaxIdleConnectionsPercent = maxIdleConnectionsPercent; SessionPinningFilters = sessionPinningFilters; } } }
57.561404
469
0.718379
[ "ECL-2.0", "Apache-2.0" ]
Otanikotani/pulumi-aws
sdk/dotnet/Rds/Outputs/ProxyDefaultTargetGroupConnectionPoolConfig.cs
3,281
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.ComponentModel.Composition; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Highlighting { [Export(typeof(IViewTaggerProvider))] [TagType(typeof(KeywordHighlightTag))] [ContentType(ContentTypeNames.CSharpContentType)] [ContentType(ContentTypeNames.VisualBasicContentType)] [TextViewRole(PredefinedTextViewRoles.Interactive)] internal class HighlighterViewTaggerProvider : AsynchronousViewTaggerProvider<KeywordHighlightTag> { private readonly IHighlightingService _highlightingService; // Whenever an edit happens, clear all highlights. When moving the caret, preserve // highlights if the caret stays within an existing tag. protected override TaggerCaretChangeBehavior CaretChangeBehavior => TaggerCaretChangeBehavior.RemoveAllTagsOnCaretMoveOutsideOfTag; protected override TaggerTextChangeBehavior TextChangeBehavior => TaggerTextChangeBehavior.RemoveAllTags; protected override IEnumerable<PerLanguageOption<bool>> PerLanguageOptions => SpecializedCollections.SingletonEnumerable(FeatureOnOffOptions.KeywordHighlighting); [ImportingConstructor] public HighlighterViewTaggerProvider( IThreadingContext threadingContext, IHighlightingService highlightingService, IForegroundNotificationService notificationService, IAsynchronousOperationListenerProvider listenerProvider) : base(threadingContext, listenerProvider.GetListener(FeatureAttribute.KeywordHighlighting), notificationService) { _highlightingService = highlightingService; } protected override ITaggerEventSource CreateEventSource(ITextView textView, ITextBuffer subjectBuffer) { return TaggerEventSources.Compose( TaggerEventSources.OnTextChanged(subjectBuffer, TaggerDelay.OnIdle), TaggerEventSources.OnCaretPositionChanged(textView, subjectBuffer, TaggerDelay.NearImmediate), TaggerEventSources.OnParseOptionChanged(subjectBuffer, TaggerDelay.NearImmediate)); } protected override async Task ProduceTagsAsync(TaggerContext<KeywordHighlightTag> context, DocumentSnapshotSpan documentSnapshotSpan, int? caretPosition) { var cancellationToken = context.CancellationToken; var document = documentSnapshotSpan.Document; // https://devdiv.visualstudio.com/DevDiv/_workitems/edit/763988 // It turns out a document might be associated with a project of wrong language, e.g. C# document in a Xaml project. // Even though we couldn't repro the crash above, a fix is made in one of possibly multiple code paths that could cause // us to end up in this situation. // Regardless of the effective of the fix, we want to enhance the guard aginst such scenario here until an audit in // workspace is completed to eliminate the root cause. if (document?.SupportsSyntaxTree != true) { return; } var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); if (!documentOptions.GetOption(FeatureOnOffOptions.KeywordHighlighting)) { return; } if (!caretPosition.HasValue) { return; } var snapshotSpan = documentSnapshotSpan.SnapshotSpan; var position = caretPosition.Value; var snapshot = snapshotSpan.Snapshot; // See if the user is just moving their caret around in an existing tag. If so, we don't // want to actually go recompute things. Note: this only works for containment. If the // user moves their caret to the end of a highlighted reference, we do want to recompute // as they may now be at the start of some other reference that should be highlighted instead. var existingTags = context.GetExistingContainingTags(new SnapshotPoint(snapshot, position)); if (!existingTags.IsEmpty()) { context.SetSpansTagged(SpecializedCollections.EmptyEnumerable<DocumentSnapshotSpan>()); return; } using (Logger.LogBlock(FunctionId.Tagger_Highlighter_TagProducer_ProduceTags, cancellationToken)) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var spans = _highlightingService.GetHighlights(root, position, cancellationToken); foreach (var span in spans) { context.AddTag(new TagSpan<KeywordHighlightTag>(span.ToSnapshotSpan(snapshot), KeywordHighlightTag.Instance)); } } } } }
51.225225
170
0.711748
[ "Apache-2.0" ]
GigabyteUB1B1/roslyn
src/EditorFeatures/Core/Implementation/KeywordHighlighting/HighlighterViewTaggerProvider.cs
5,688
C#
using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Test.Common; using Test.Common.Models; using Horse.Messaging.Server.Queues; using Xunit; namespace Test.Persistency { public class QueueFillTest { [Fact] public async Task FillJson() { List<QueueMessageA> items = new List<QueueMessageA>(); for (int i = 0; i < 10; i++) items.Add(new QueueMessageA("No #" + i)); TestHorseRider server = new TestHorseRider(); await server.Initialize(); server.Start(300, 300); HorseQueue push = server.Rider.Queue.Find("push-a"); Assert.NotNull(push); QueueFiller fillerPushA = new QueueFiller(push); fillerPushA.FillJson(items, false, false); await Task.Delay(500); Assert.NotEqual(0, push.Manager.MessageStore.Count()); server.Stop(); } [Fact] public async Task FillString() { List<string> items = new List<string>(); for (int i = 0; i < 10; i++) items.Add("No #" + i); TestHorseRider server = new TestHorseRider(); await server.Initialize(); server.Start(300, 300); HorseQueue queue = server.Rider.Queue.Find("push-a"); Assert.NotNull(queue); QueueFiller filler = new QueueFiller(queue); filler.FillString(items, false, true); filler.FillString(items, false, false); await Task.Delay(500); Assert.NotEqual(0, queue.Manager.PriorityMessageStore.Count()); Assert.NotEqual(0, queue.Manager.MessageStore.Count()); server.Stop(); } [Fact] public async Task FillData() { List<byte[]> items = new List<byte[]>(); for (int i = 0; i < 10; i++) items.Add(Encoding.UTF8.GetBytes("No #" + i)); TestHorseRider server = new TestHorseRider(); await server.Initialize(); server.Start(300, 300); HorseQueue queue = server.Rider.Queue.Find("push-a"); Assert.NotNull(queue); QueueFiller filler = new QueueFiller(queue); filler.FillData(items, false, true); filler.FillData(items, false, false); await Task.Delay(500); Assert.NotEqual(0, queue.Manager.PriorityMessageStore.Count()); Assert.NotEqual(0, queue.Manager.MessageStore.Count()); server.Stop(); } } }
31.119048
75
0.555853
[ "Apache-2.0" ]
horse-framework/horse-messaging
src/Tests/Test.Persistency/QueueFillTest.cs
2,614
C#
/* Copyright 2006 Jerry Huxtable 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 GeoAPI.Geometries; using Proj4Net.Utility; namespace Proj4Net.Projection { public class Eckert2Projection : Projection { private const double FXC = 0.46065886596178063902; private const double FYC = 1.44720250911653531871; private const double C13 = 0.33333333333333333333; private const double ONEEPS = 1.0000001; public override Coordinate Project(double lplam, double lpphi, Coordinate xy) { xy.X = FXC * lplam * (xy.Y = Math.Sqrt(4.0 - 3.0 * Math.Sin(Math.Abs(lpphi)))); xy.Y = FYC * (2.0 - xy.Y); if (lpphi < 0.0) xy.Y = -xy.Y; return xy; } public override Coordinate ProjectInverse(double xyx, double xyy, Coordinate lp) { lp.X = xyx / (FXC * (lp.Y = 2.0 - Math.Abs(xyy) / FYC)); lp.Y = (4.0 - lp.Y * lp.Y) * C13; if (Math.Abs(lp.Y) >= 1.0) { if (Math.Abs(lp.Y) > ONEEPS) throw new ProjectionException("I"); else lp.Y = lp.Y < 0.0 ? -ProjectionMath.PiHalf : ProjectionMath.PiHalf; } else lp.Y = Math.Asin(lp.Y); if (xyy < 0) lp.Y = -lp.Y; return lp; } public override Boolean HasInverse { get { return true; } } public override String ToString() { return "Eckert II"; } } }
30.294118
91
0.585437
[ "Apache-2.0" ]
jugstalt/gview5
gView.Proj/Proj4Net/Projection/Eckert2Projection.cs
2,060
C#
using AutoMapper; using Diploms.Core; using Diploms.Dto.Specialities; namespace Diploms.Services.Specialities { public class SpecialitiesMappings : Profile { public SpecialitiesMappings() { CreateMap<SpecialityEditDto, Speciality>(); } } }
20.571429
55
0.673611
[ "MIT" ]
vanonavi/dcs
src/Diploms.Services/Specialities/SpecialitiesMappings.cs
288
C#
using System.Threading.Tasks; using ActiveMQ.Artemis.Client.TestUtils; using Xunit; namespace ActiveMQ.Artemis.Client.Testing.UnitTests; public class SubscriptionSpec { [Fact] public async Task Should_subscribe_on_a_given_address() { var endpoint = EndpointUtil.GetUniqueEndpoint(); using var testKit = new TestKit(endpoint); var testAddress = "test_address"; using var subscription = testKit.Subscribe(testAddress); var connectionFactory = new ConnectionFactory(); await using var connection = await connectionFactory.CreateAsync(endpoint); await using var producer = await connection.CreateProducerAsync(testAddress); await producer.SendAsync(new Message("foo")); var message = await subscription.ReceiveAsync(); Assert.Equal("foo", message.GetBody<string>()); } }
32.148148
85
0.715438
[ "MIT" ]
Havret/ActiveMQ.Net
test/ArtemisNetClient.Testing.UnitTests/SubscriptionSpec.cs
868
C#
using System; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // 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("AWSSDK.CodePipeline")] #if BCL35 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS CodePipeline. AWS CodePipeline is a continuous delivery service for fast and reliable application updates.")] #elif BCL45 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - AWS CodePipeline. AWS CodePipeline is a continuous delivery service for fast and reliable application updates.")] #elif PCL [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (PCL) - AWS CodePipeline. AWS CodePipeline is a continuous delivery service for fast and reliable application updates.")] #elif UNITY [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (Unity) - AWS CodePipeline. AWS CodePipeline is a continuous delivery service for fast and reliable application updates.")] #elif NETSTANDARD13 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 1.3)- AWS CodePipeline. AWS CodePipeline is a continuous delivery service for fast and reliable application updates.")] #elif NETSTANDARD20 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0)- AWS CodePipeline. AWS CodePipeline is a continuous delivery service for fast and reliable application updates.")] #else #error Unknown platform constant - unable to set correct AssemblyDescription #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 2009-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [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)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.3")] [assembly: AssemblyFileVersion("3.3.104.15")] #if WINDOWS_PHONE || UNITY [assembly: System.CLSCompliant(false)] # else [assembly: System.CLSCompliant(true)] #endif #if BCL [assembly: System.Security.AllowPartiallyTrustedCallers] #endif
48.610169
201
0.775802
[ "Apache-2.0" ]
gnurg/aws-sdk-net
sdk/src/Services/CodePipeline/Properties/AssemblyInfo.cs
2,868
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Pomelo.EntityFrameworkCore.MySql.IntegrationTests.Models; using Microsoft.EntityFrameworkCore; using MySqlConnector; using Pomelo.EntityFrameworkCore.MySql.Tests.TestUtilities.Attributes; using Pomelo.EntityFrameworkCore.MySql.Storage; using Xunit; namespace Pomelo.EntityFrameworkCore.MySql.IntegrationTests.Tests.Models { public class GeneratedTypesTest { [SupportedServerVersionCondition(ServerVersion.JsonSupportKey, Skip = "Version of MySQL/MariaDB does not support JSON")] public async Task TestGeneratedContact() { const string email = "bob@example.com"; const string address = "123 Entity Framework Ln"; const string city = "Redmond"; const string state = "WA"; const string zip = "99999"; var addressFormatted = string.Join(", ", address, city, state, zip); using (var scope = new AppDbScope()) { var db = scope.AppDb; void TestContact(GeneratedContact contact) { var csb = new MySqlConnectionStringBuilder(db.Database.GetDbConnection().ConnectionString); var guidHexStr = csb.OldGuids ? BitConverter.ToString(contact.Id.ToByteArray().Take(8).ToArray()).Replace("-", "") : contact.Id.ToString().Replace("-", "").Substring(0, 16); var guidTicks = Convert.ToInt64("0x" + guidHexStr, 16); var guidDateTime = new DateTime(guidTicks); Assert.InRange(guidDateTime - DateTime.UtcNow, TimeSpan.FromSeconds(-5), TimeSpan.FromSeconds(5)); Assert.Equal(email, contact.Email); Assert.Equal(addressFormatted, contact.Address); } var gen = new GeneratedContact { Names = new JsonObject<List<string>>(new List<string> {"Bob", "Bobby"}), ContactInfo = new JsonObject<Dictionary<string, string>>(new Dictionary<string, string> { {"Email", email}, {"Address", address}, {"City", city}, {"State", state}, {"Zip", zip}, }), }; // test the entity after saving to the db db.GeneratedContacts.Add(gen); await db.SaveChangesAsync(); TestContact(gen); // test the entity after fresh retreival from the database var genDb = await db.GeneratedContacts.FirstOrDefaultAsync(m => m.Id == gen.Id); TestContact(genDb); } } [Fact] public async Task TestGeneratedTime() { var gt = new GeneratedTime {Name = "test"}; using (var scope = new AppDbScope()) { var db = scope.AppDb; db.GeneratedTime.Add(gt); await db.SaveChangesAsync(); Assert.Equal(gt.CreatedDateTime, gt.UpdatedDateTime); Assert.Equal(gt.CreatedDateTime3, gt.UpdatedDateTime3); Assert.Equal(gt.CreatedDateTime6, gt.UpdatedDateTime6); Assert.Equal(gt.CreatedTimestamp, gt.UpdatedTimetamp); Assert.Equal(gt.CreatedTimestamp3, gt.UpdatedTimetamp3); Assert.Equal(gt.CreatedTimestamp6, gt.UpdatedTimetamp6); Assert.InRange(gt.CreatedDateTime3 - gt.CreatedDateTime, TimeSpan.Zero, TimeSpan.FromMilliseconds(999)); Assert.InRange(gt.CreatedDateTime6 - gt.CreatedDateTime3, TimeSpan.Zero, TimeSpan.FromMilliseconds(0.999)); Assert.InRange(gt.CreatedTimestamp3 - gt.CreatedTimestamp, TimeSpan.Zero, TimeSpan.FromMilliseconds(999)); Assert.InRange(gt.CreatedTimestamp6 - gt.CreatedTimestamp3, TimeSpan.Zero, TimeSpan.FromMilliseconds(0.999)); await Task.Delay(TimeSpan.FromSeconds(1)); gt.Name = "test2"; await db.SaveChangesAsync(); Assert.NotEqual(gt.CreatedDateTime, gt.UpdatedDateTime); Assert.NotEqual(gt.CreatedDateTime3, gt.UpdatedDateTime3); Assert.NotEqual(gt.CreatedDateTime6, gt.UpdatedDateTime6); Assert.NotEqual(gt.CreatedTimestamp, gt.UpdatedTimetamp); Assert.NotEqual(gt.CreatedTimestamp3, gt.UpdatedTimetamp3); Assert.NotEqual(gt.CreatedTimestamp6, gt.UpdatedTimetamp6); } } [Fact] public async Task TestGeneratedConcurrencyToken() { var gct = new GeneratedConcurrencyCheck { Gen = 1 }; using (var scope = new AppDbScope()) { var db = scope.AppDb; db.GeneratedConcurrencyCheck.Add(gct); await db.SaveChangesAsync(); using (var scope2 = new AppDbScope()) { var db2 = scope2.AppDb; var gct2 = await db2.GeneratedConcurrencyCheck.FindAsync(gct.Id); gct2.Gen++; await db2.SaveChangesAsync(); } gct.Gen++; await Assert.ThrowsAsync<DbUpdateConcurrencyException>(() => db.SaveChangesAsync()); } } [Fact] public async Task TestGeneratedRowVersion() { var gct = new GeneratedRowVersion { Gen = 1 }; using (var scope = new AppDbScope()) { var db = scope.AppDb; db.GeneratedRowVersion.Add(gct); await db.SaveChangesAsync(); using (var scope2 = new AppDbScope()) { var db2 = scope2.AppDb; var gct2 = await db2.GeneratedRowVersion.FindAsync(gct.Id); gct2.Gen++; await db2.SaveChangesAsync(); } gct.Gen++; await Assert.ThrowsAsync<DbUpdateConcurrencyException>(() => db.SaveChangesAsync()); } } } }
34.635762
128
0.672658
[ "MIT" ]
lauxjpn/Pomelo.EntityFrameworkCore.MySql
test/EFCore.MySql.IntegrationTests/Tests/Models/GeneratedTypesTest.cs
5,232
C#
using System; namespace Lucene.Net.Codecs.Lucene40 { /* * 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. */ /// <summary> /// Lucene 4.0 Field Infos format. /// <para/> /// <para>Field names are stored in the field info file, with suffix <tt>.fnm</tt>.</para> /// <para>FieldInfos (.fnm) --&gt; Header,FieldsCount, &lt;FieldName,FieldNumber, /// FieldBits,DocValuesBits,Attributes&gt; <sup>FieldsCount</sup></para> /// <para>Data types: /// <list type="bullet"> /// <item><description>Header --&gt; CodecHeader (<see cref="CodecUtil.WriteHeader(Store.DataOutput, string, int)"/>) </description></item> /// <item><description>FieldsCount --&gt; VInt (<see cref="Store.DataOutput.WriteVInt32(int)"/>) </description></item> /// <item><description>FieldName --&gt; String (<see cref="Store.DataOutput.WriteString(string)"/>) </description></item> /// <item><description>FieldBits, DocValuesBits --&gt; Byte (<see cref="Store.DataOutput.WriteByte(byte)"/>) </description></item> /// <item><description>FieldNumber --&gt; VInt (<see cref="Store.DataOutput.WriteInt32(int)"/>) </description></item> /// <item><description>Attributes --&gt; IDictionary&lt;String,String&gt; (<see cref="Store.DataOutput.WriteStringStringMap(System.Collections.Generic.IDictionary{string, string})"/>) </description></item> /// </list> /// </para> /// Field Descriptions: /// <list type="bullet"> /// <item><description>FieldsCount: the number of fields in this file.</description></item> /// <item><description>FieldName: name of the field as a UTF-8 String.</description></item> /// <item><description>FieldNumber: the field's number. Note that unlike previous versions of /// Lucene, the fields are not numbered implicitly by their order in the /// file, instead explicitly.</description></item> /// <item><description>FieldBits: a byte containing field options. /// <list type="bullet"> /// <item><description>The low-order bit is one for indexed fields, and zero for non-indexed /// fields.</description></item> /// <item><description>The second lowest-order bit is one for fields that have term vectors /// stored, and zero for fields without term vectors.</description></item> /// <item><description>If the third lowest order-bit is set (0x4), offsets are stored into /// the postings list in addition to positions.</description></item> /// <item><description>Fourth bit is unused.</description></item> /// <item><description>If the fifth lowest-order bit is set (0x10), norms are omitted for the /// indexed field.</description></item> /// <item><description>If the sixth lowest-order bit is set (0x20), payloads are stored for the /// indexed field.</description></item> /// <item><description>If the seventh lowest-order bit is set (0x40), term frequencies and /// positions omitted for the indexed field.</description></item> /// <item><description>If the eighth lowest-order bit is set (0x80), positions are omitted for the /// indexed field.</description></item> /// </list> /// </description></item> /// <item><description>DocValuesBits: a byte containing per-document value types. The type /// recorded as two four-bit integers, with the high-order bits representing /// <c>norms</c> options, and the low-order bits representing /// <see cref="Index.DocValues"/> options. Each four-bit integer can be decoded as such: /// <list type="bullet"> /// <item><description>0: no DocValues for this field.</description></item> /// <item><description>1: variable-width signed integers. (<see cref="LegacyDocValuesType.VAR_INTS"/>)</description></item> /// <item><description>2: 32-bit floating point values. (<see cref="LegacyDocValuesType.FLOAT_32"/>)</description></item> /// <item><description>3: 64-bit floating point values. (<see cref="LegacyDocValuesType.FLOAT_64"/>)</description></item> /// <item><description>4: fixed-length byte array values. (<see cref="LegacyDocValuesType.BYTES_FIXED_STRAIGHT"/>)</description></item> /// <item><description>5: fixed-length dereferenced byte array values. (<see cref="LegacyDocValuesType.BYTES_FIXED_DEREF"/>)</description></item> /// <item><description>6: variable-length byte array values. (<see cref="LegacyDocValuesType.BYTES_VAR_STRAIGHT"/>)</description></item> /// <item><description>7: variable-length dereferenced byte array values. (<see cref="LegacyDocValuesType.BYTES_VAR_DEREF"/>)</description></item> /// <item><description>8: 16-bit signed integers. (<see cref="LegacyDocValuesType.FIXED_INTS_16"/>)</description></item> /// <item><description>9: 32-bit signed integers. (<see cref="LegacyDocValuesType.FIXED_INTS_32"/>)</description></item> /// <item><description>10: 64-bit signed integers. (<see cref="LegacyDocValuesType.FIXED_INTS_64"/>)</description></item> /// <item><description>11: 8-bit signed integers. (<see cref="LegacyDocValuesType.FIXED_INTS_8"/>)</description></item> /// <item><description>12: fixed-length sorted byte array values. (<see cref="LegacyDocValuesType.BYTES_FIXED_SORTED"/>)</description></item> /// <item><description>13: variable-length sorted byte array values. (<see cref="LegacyDocValuesType.BYTES_VAR_SORTED"/>)</description></item> /// </list> /// </description></item> /// <item><description>Attributes: a key-value map of codec-private attributes.</description></item> /// </list> /// /// @lucene.experimental /// </summary> [Obsolete("Only for reading old 4.0 and 4.1 segments")] public class Lucene40FieldInfosFormat : FieldInfosFormat { private readonly FieldInfosReader reader = new Lucene40FieldInfosReader(); /// <summary> /// Sole constructor. </summary> public Lucene40FieldInfosFormat() { } public override FieldInfosReader FieldInfosReader { get { return reader; } } public override FieldInfosWriter FieldInfosWriter { get { throw new System.NotSupportedException("this codec can only be used for reading"); } } /// <summary> /// Extension of field infos </summary> internal const string FIELD_INFOS_EXTENSION = "fnm"; internal const string CODEC_NAME = "Lucene40FieldInfos"; internal const int FORMAT_START = 0; internal const int FORMAT_CURRENT = FORMAT_START; internal const sbyte IS_INDEXED = 0x1; internal const sbyte STORE_TERMVECTOR = 0x2; internal const sbyte STORE_OFFSETS_IN_POSTINGS = 0x4; internal const sbyte OMIT_NORMS = 0x10; internal const sbyte STORE_PAYLOADS = 0x20; internal const sbyte OMIT_TERM_FREQ_AND_POSITIONS = 0x40; internal const sbyte OMIT_POSITIONS = -128; } }
61.338346
211
0.645379
[ "Apache-2.0" ]
DiogenesPolanco/lucenenet
src/Lucene.Net/Codecs/Lucene40/Lucene40FieldInfosFormat.cs
8,158
C#
using Microsoft.AspNetCore.Mvc; using NetDream.Web.Areas.Blog.Repositories; namespace NetDream.Web.Areas.Blog.Controllers { [Area("Blog")] public class TagController : Controller { private readonly BlogRepository _repository; public TagController(BlogRepository repository) { _repository = repository; } public IActionResult Index() { ViewData["items"] = _repository.GetTags(); return View(); } } }
23.181818
55
0.617647
[ "MIT" ]
zx648383079/netdream
src/NetDream.Web/Areas/Blog/Controllers/TagController.cs
512
C#
using System; using System.Linq; namespace CodeBreaker.Core { public struct Code : IEquatable<Code> { public static Code Empty = new Code(); public Code(int[] digits) { Digits = digits; } public int[] Digits { get; } public CodeResult Match(Code code) { if (code.Equals(Code.Empty)) { throw new ArgumentNullException(nameof(code)); } if (code.Digits.Length != Digits.Length) { return new CodeResult(code, 0, 0); } int match = 0; for(int i = 0; i < Digits.Length; i++) { if (Digits[i] == code.Digits[i]) { match++; } } int exists = Digits.Intersect(code.Digits).Count() - match; if (exists < 0) { exists = 0; } return new CodeResult(code, match, exists); } public bool Equals(Code other) { return Equals((object)other); } public override bool Equals(object obj) { if (obj is Code) { var code = (Code)obj; if (Digits == null || code.Digits == null) { return Digits == code.Digits; } return Enumerable.SequenceEqual(Digits, code.Digits); } return false; } public override int GetHashCode() { if (Digits == null) { return 0; } int result = 0; int shift = 0; for (int i = 0; i < Digits.Length; i++) { shift = (shift + 11) % 21; result ^= (Digits[i]+1024) << shift; } return result; } public override string ToString() { return String.Join(",", Digits); } public static Code Generate(int digits, int minValue, int maxValue) { var code = new int[digits]; var random = new Random(); for(int i = 0; i < digits; i++) { code[i] = random.Next(minValue, maxValue + 1); } return new Code(code); } } }
25.765306
76
0.397624
[ "MIT" ]
vlesierse/codebreaker
src/CodeBreaker.Core/Code.cs
2,527
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18408 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Lpp.Dns.PubHealth.Views { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Web; using System.Web.Helpers; using System.Web.Security; using System.Web.UI; using System.Web.WebPages; using System.Web.Mvc; using System.Web.Mvc.Ajax; using System.Web.Mvc.Html; using System.Web.Routing; using Lpp; using Lpp.Mvc; using Lpp.Mvc.Application; using Lpp.Mvc.Controls; using Lpp.Dns.PubHealth; using Lpp.Dns.PubHealth.Models; public partial class Create : System.Web.Mvc.WebViewPage<Lpp.Dns.PubHealth.Models.PubHealthModel> { #line hidden public Create() { } protected System.Web.HttpApplication ApplicationInstance { get { return ((System.Web.HttpApplication)(Context.ApplicationInstance)); } } public override void Execute() { #line 2 "C:\Users\Administrator\Documents\Projects\DNS\Source\PMN-OS\trunk\Plugins\CHORDS\Chords.Dns.PubHealth\Chords.Dns.PubHealth\Views\Create.cshtml" this.Stylesheet("PubHealth.css"); var id = Html.UniqueId(); #line default #line hidden WriteLiteral(@" <div class=""SqlEditor ui-form""> <div class=""ui-form""> <div id='errorLocation' style=""font-size: small; color: Gray;""></div> <div class=""ui-groupbox""> <div class=""ui-groupbox-header""><span>Sql Query</span></div> <label>Enter the query string to execute at DataMarts</label> "); #line 14 "C:\Users\Administrator\Documents\Projects\DNS\Source\PMN-OS\trunk\Plugins\CHORDS\Chords.Dns.PubHealth\Chords.Dns.PubHealth\Views\Create.cshtml" Write(Html.TextAreaFor(m => m.SqlQuery)); #line default #line hidden WriteLiteral("\r\n </div>\r\n </div> \r\n</div>\r\n "); } } }
29.082353
165
0.563107
[ "Apache-2.0" ]
Missouri-BMI/popmednet
Plugins/CHORDS/Chords.Dns.PubHealth/Chords.Dns.PubHealth/Views/Create.cs
2,474
C#
// This is an automatically generated file, based on settings.json and PackageSettingsGen.tt /* settings.json content: { "settings": [ { "name": "CollectMetrics", "type": "bool", "default": "true" }, { "name": "EditorComments", "type": "bool", "default": "false" }, { "name": "UIState", "type": "object", "typename": "UIState", "default": "null" }, { "name": "HideTeamExplorerWelcomeMessage", "type": "bool", "default": "false" } ] } */ using GitHub.Settings; using GitHub.Primitives; using GitHub.VisualStudio.Helpers; namespace GitHub.VisualStudio.Settings { public partial class PackageSettings : NotificationAwareObject, IPackageSettings { bool collectMetrics; public bool CollectMetrics { get { return collectMetrics; } set { collectMetrics = value; this.RaisePropertyChange(); } } bool editorComments; public bool EditorComments { get { return editorComments; } set { editorComments = value; this.RaisePropertyChange(); } } UIState uIState; public UIState UIState { get { return uIState; } set { uIState = value; this.RaisePropertyChange(); } } bool hideTeamExplorerWelcomeMessage; public bool HideTeamExplorerWelcomeMessage { get { return hideTeamExplorerWelcomeMessage; } set { hideTeamExplorerWelcomeMessage = value; this.RaisePropertyChange(); } } void LoadSettings() { CollectMetrics = (bool)settingsStore.Read("CollectMetrics", true); EditorComments = (bool)settingsStore.Read("EditorComments", false); UIState = SimpleJson.DeserializeObject<UIState>((string)settingsStore.Read("UIState", "{}")); HideTeamExplorerWelcomeMessage = (bool)settingsStore.Read("HideTeamExplorerWelcomeMessage", false); } void SaveSettings() { settingsStore.Write("CollectMetrics", CollectMetrics); settingsStore.Write("EditorComments", EditorComments); settingsStore.Write("UIState", SimpleJson.SerializeObject(UIState)); settingsStore.Write("HideTeamExplorerWelcomeMessage", HideTeamExplorerWelcomeMessage); } } }
28.470588
111
0.603719
[ "MIT" ]
alsamer2008/VisualStudio
src/GitHub.VisualStudio/Settings/generated/PackageSettingsGen.cs
2,422
C#
using System; using System.Collections.Generic; using System.Globalization; using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Linq { internal class JPath { private readonly string _expression; public List<object> Parts { get; private set; } private int _currentIndex; public JPath(string expression) { ValidationUtils.ArgumentNotNull(expression, "expression"); _expression = expression; Parts = new List<object>(); ParseMain(); } private void ParseMain() { int currentPartStartIndex = _currentIndex; bool followingIndexer = false; while (_currentIndex < _expression.Length) { char currentChar = _expression[_currentIndex]; switch (currentChar) { case '[': case '(': if (_currentIndex > currentPartStartIndex) { string member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex); Parts.Add(member); } ParseIndexer(currentChar); currentPartStartIndex = _currentIndex + 1; followingIndexer = true; break; case ']': case ')': throw new Exception("Unexpected character while parsing path: " + currentChar); case '.': if (_currentIndex > currentPartStartIndex) { string member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex); Parts.Add(member); } currentPartStartIndex = _currentIndex + 1; followingIndexer = false; break; default: if (followingIndexer) throw new Exception("Unexpected character following indexer: " + currentChar); break; } _currentIndex++; } if (_currentIndex - 1 > currentPartStartIndex) { string member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex); Parts.Add(member); } } private void ParseIndexer(char indexerOpenChar) { _currentIndex++; char indexerCloseChar = (indexerOpenChar == '[') ? ']' : ')'; int indexerStart = _currentIndex; int indexerLength = 0; bool indexerClosed = false; while (_currentIndex < _expression.Length) { char currentCharacter = _expression[_currentIndex]; if (char.IsDigit(currentCharacter)) { indexerLength++; } else if (currentCharacter == indexerCloseChar) { indexerClosed = true; break; } else { throw new Exception("Unexpected character while parsing path indexer: " + currentCharacter); } _currentIndex++; } if (!indexerClosed) throw new Exception("Path ended with open indexer. Expected " + indexerCloseChar); if (indexerLength == 0) throw new Exception("Empty path indexer."); string indexer = _expression.Substring(indexerStart, indexerLength); Parts.Add(Convert.ToInt32(indexer, CultureInfo.InvariantCulture)); } internal JToken Evaluate(JToken root, bool errorWhenNoMatch) { JToken current = root; foreach (object part in Parts) { string propertyName = part as string; if (propertyName != null) { JObject o = current as JObject; if (o != null) { current = o[propertyName]; if (current == null && errorWhenNoMatch) throw new Exception("Property '{0}' does not exist on JObject.".FormatWith(CultureInfo.InvariantCulture, propertyName)); } else { if (errorWhenNoMatch) throw new Exception("Property '{0}' not valid on {1}.".FormatWith(CultureInfo.InvariantCulture, propertyName, current.GetType().Name)); return null; } } else { int index = (int) part; JArray a = current as JArray; if (a != null) { if (a.Count <= index) { if (errorWhenNoMatch) throw new IndexOutOfRangeException("Index {0} outside the bounds of JArray.".FormatWith(CultureInfo.InvariantCulture, index)); return null; } current = a[index]; } else { if (errorWhenNoMatch) throw new Exception("Index {0} not valid on {1}.".FormatWith(CultureInfo.InvariantCulture, index, current.GetType().Name)); return null; } } } return current; } } }
28.170588
149
0.572144
[ "Apache-2.0" ]
DanielLazarov/test_me-windows_phone_ui
test_me-windows_phone_ui/json/Source/Src/Newtonsoft.Json/Linq/JPath.cs
4,789
C#
using System.Collections.Generic; using UnityEngine; namespace ET { namespace EventType { public struct AppStart { } public struct ChangePosition { public Unit Unit; } public struct ChangeRotation { public Unit Unit; } public struct PingChange { public Scene ZoneScene; public long Ping; } public struct AfterCreateZoneScene { public Scene ZoneScene; } public struct AfterCreateLoginScene { public Scene LoginScene; } public struct AppStartInitFinish { public Scene ZoneScene; } public struct LoginGateFinish { public Scene ZoneScene; } public struct LoginOrRegsiteFail { public string ErrorMessage; public Scene ZoneScene; } public struct LoadingBegin { public Scene Scene; } public struct LoadingFinish { public Scene Scene; } public struct EnterMapFinish { public Scene ZoneScene; } public struct AfterHeroCreate_CreateGo { public int HeroConfigId; public Unit Unit; } public struct AfterHeroSpilingCreate_CreateGO { public int HeroSpilingConfigId; public Unit Unit; } public struct AfterBulletCreate_CreateGO { public Unit FireUnit; public Unit BulletUnit; public Unit TargetUnit; public int BulletConfigId; public Vector3 BulletPos; public Vector3 BulletDir; } public struct MoveStart { public Unit Unit; public float Speed; } public struct MoveStop { public Unit Unit; } public struct NumericChange { public NumericComponent NumericComponent; public NumericType NumericType; public float Result; } public struct View_PrepareFire { public Scene DomainScene; public Unit FiredUnit; public float DirX; public float DirZ; } public struct View_RealFire { public Scene DomainScene; public Unit FiredUnit; public Unit TargetUnit; } public struct CreateRoom { public Scene DomainScene; } public struct LoginLobbyFinish { public Scene DomainScene; } public struct JoinRoom { public Scene DomainScene; public List<PlayerInfoRoom> PlayerInfoRooms; public int Camp; } public struct CreatePlayerCard { public Scene DomainScene; public long RoomId; public long PlayerId; public string PlayerAccount; public int Camp; } public struct LeaveRoom { public Scene DomainScene; public long PlayerId; public long RoomId; public string PlayerAccount; public int Camp; } public struct SpriteReceiveDamage { public Unit Sprite; public float DamageValue; } public struct UnitChangeProperty { public Unit Sprite; public NumericType NumericType; public float FinalValue; } public struct SpriteResurrection { public Unit Sprite; } public struct BattleEnd { public Scene ZoneScene; public List<(string name, int score)> Scores; } } }
21.743169
57
0.512943
[ "MIT" ]
futouyiba/ClubET
Unity/Assets/Model/NKGMOBA/EventType.cs
3,981
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEditor; using AnswerTypes; public class TriviaDesignerWindow : EditorWindow { Texture2D headerSectionTexture; Texture2D mainSectionTexture; Color headerSectionColor = new Color(0f/255f, 125f/255f, 255f/255f, 1); Rect headerSection; Rect mainSection; public static QuestionData QuestionInfo { get; private set; } [MenuItem("Window/TriviaDesigner")] static void OpenWindow() { TriviaDesignerWindow window = (TriviaDesignerWindow)GetWindow(typeof(TriviaDesignerWindow)); window.minSize = new Vector2(300, 300); window.Show(); } /// <summary> /// Similar to Start() or Awake() /// </summary> void OnEnable() { InitTextures(); InitData(); } public static void InitData() { QuestionInfo = (QuestionData)CreateInstance(typeof(QuestionData)); AddQuestion(); } /// <summary> /// Adds a placeholder question in. /// </summary> public static void AddQuestion() { QuestionInfo.question.Add("Replace me"); QuestionInfo.answer1.Add("Replace me"); QuestionInfo.answer2.Add("Replace me"); QuestionInfo.answer3.Add("Replace me"); QuestionInfo.answer4.Add("Replace me"); QuestionInfo.answerType1.Add(AnswerType.CORRECT); QuestionInfo.answerType2.Add(AnswerType.CORRECT); QuestionInfo.answerType3.Add(AnswerType.CORRECT); QuestionInfo.answerType4.Add(AnswerType.CORRECT); } /// <summary> /// Initialize Texture2D values /// </summary> void InitTextures() { headerSectionTexture = new Texture2D(1, 1); headerSectionTexture.SetPixel(0, 0, headerSectionColor); headerSectionTexture.Apply(); mainSectionTexture = new Texture2D(1, 1); mainSectionTexture.SetPixel(0, 0, Color.white); mainSectionTexture.Apply(); } /// <summary> /// Similar to any Update function /// Not called once per frame. Called 1 or more times per interaction. /// </summary> void OnGUI() { DrawLayouts(); DrawHeader(); DrawQuestionSettings(); } /// <summary> /// Defines Rect values and paints textures based on Rects /// </summary> void DrawLayouts() { headerSection.x = 0; headerSection.y = 0; headerSection.width = Screen.width; headerSection.height = 100; mainSection.x = 0; mainSection.y = headerSection.height; mainSection.width = Screen.width; mainSection.height = Screen.height; GUI.DrawTexture(headerSection, headerSectionTexture); GUI.DrawTexture(mainSection, mainSectionTexture); } /// <summary> /// Draw Contents of header /// </summary> void DrawHeader() { GUILayout.BeginArea(headerSection); GUI.skin.label.fontSize = 25; GUI.skin.label.alignment = TextAnchor.MiddleCenter; GUI.skin.label.padding.top = 35; GUI.skin.label.fontStyle = FontStyle.Bold; GUILayout.Label("Trivia Designer"); GUI.skin.label.fontSize = 16; GUI.skin.label.padding.top = 5; GUI.skin.label.padding.bottom = 10; GUILayout.EndArea(); } /// <summary> /// Draw contents of Question region /// </summary> void DrawQuestionSettings() { GUILayout.BeginArea(mainSection); GUILayout.Label("Question Settings"); EditorGUILayout.BeginHorizontal(); GUI.skin.label.fontStyle = FontStyle.Normal; GUI.skin.label.padding.top = 0; GUI.skin.label.alignment = TextAnchor.MiddleLeft; GUILayout.Label("Canvas:"); QuestionInfo.canvas = (GameObject)EditorGUILayout.ObjectField(QuestionInfo.canvas, typeof(GameObject), false); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); GUILayout.Label("Question #:", GUILayout.Width(120)); if (GUILayout.Button("-", GUILayout.Height(20), GUILayout.Width(20))) { if (QuestionInfo.number > 1) { //remove the current item from each list with a remove button QuestionInfo.number--; } } GUI.skin.label.alignment = TextAnchor.MiddleCenter; GUILayout.Label(QuestionInfo.number + "", GUILayout.Width(25)); if (GUILayout.Button("+", GUILayout.Height(20), GUILayout.Width(20))) { if (QuestionInfo.number == QuestionInfo.question.Count) { //add an empty string to each item in the list AddQuestion(); } QuestionInfo.number++; } EditorGUILayout.EndHorizontal(); if (GUILayout.Button("Edit", GUILayout.Height(40))) { GeneralSettings.OpenWindow(); } if (QuestionInfo.canvas == null) { EditorGUILayout.HelpBox("This Trivia needs a [canvas] before it can be created.", MessageType.Warning); } else if (GUILayout.Button("Finish and Save", GUILayout.Height(40))) { SaveQuestionData(); } GUILayout.EndArea(); GUI.skin.label.alignment = TextAnchor.MiddleLeft; GUI.skin.label.padding.bottom = 0; GUI.skin.label.fontSize = 14; //Debug.Log(QuestionInfo.number); //Debug.Log(QuestionInfo.question.Count); } public static Button CreateButton(Button buttonPrefab, Canvas canvas, Vector2 cornerTopRight, Vector2 cornerBottomLeft) { var button = Object.Instantiate(buttonPrefab, Vector3.zero, Quaternion.identity) as Button; var rectTransform = button.GetComponent<RectTransform>(); rectTransform.SetParent(canvas.transform); rectTransform.anchorMax = cornerTopRight; rectTransform.anchorMin = cornerBottomLeft; rectTransform.offsetMax = Vector2.zero; rectTransform.offsetMin = Vector2.zero; return button; } void SaveQuestionData() { string prefabPath; string newPrefabPath = "Assets/prefabs/"; string dataPath = "Assets/resources/triviaData/data/"; dataPath += TriviaDesignerWindow.QuestionInfo.question + ".asset"; AssetDatabase.CreateAsset(TriviaDesignerWindow.QuestionInfo, dataPath); newPrefabPath += "" + TriviaDesignerWindow.QuestionInfo.question + ".prefab"; prefabPath = AssetDatabase.GetAssetPath(TriviaDesignerWindow.QuestionInfo.canvas); AssetDatabase.CopyAsset(prefabPath, newPrefabPath); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); GameObject canvasPrefab = (GameObject)AssetDatabase.LoadAssetAtPath(newPrefabPath, typeof(GameObject)); if (!canvasPrefab.GetComponent<Question>()) canvasPrefab.AddComponent(typeof(Question)); canvasPrefab.GetComponent<Question>().questionData = TriviaDesignerWindow.QuestionInfo; } } public class GeneralSettings : EditorWindow { static GeneralSettings window; public static void OpenWindow() { window = (GeneralSettings)GetWindow(typeof(GeneralSettings)); window.minSize = new Vector2(250, 200); window.Show(); } void OnGUI() { DrawSettings(TriviaDesignerWindow.QuestionInfo); } void DrawSettings(QuestionData qData) { //qData.question = new List<string>(2); //qData.answer1 = new List<string>(2); //qData.answer2 = new List<string>(2); //qData.answer3 = new List<string>(2); //qData.answer4 = new List<string>(2); //qData.answerType1 = new List<AnswerType>(2); //qData.answerType2 = new List<AnswerType>(2); //qData.answerType3 = new List<AnswerType>(2); //qData.answerType4 = new List<AnswerType>(2); //Debug.Log(qData.number); //Debug.Log(qData.question.Count); EditorGUILayout.BeginHorizontal(); GUILayout.Label("Question:"); qData.question[qData.number-1] = EditorGUILayout.TextField(qData.question[qData.number-1]); EditorGUILayout.EndHorizontal(); GUILayout.Label("Answers:"); EditorGUILayout.BeginHorizontal(); qData.answer1[qData.number-1] = EditorGUILayout.TextField(qData.answer1[qData.number-1]); GUILayout.Label("Correct or Incorrect?"); qData.answerType1[qData.number-1] = (AnswerType)EditorGUILayout.EnumPopup(qData.answerType1[qData.number-1]); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); qData.answer2[qData.number-1] = EditorGUILayout.TextField(qData.answer2[qData.number-1]); GUILayout.Label("Correct or Incorrect?"); qData.answerType2[qData.number-1] = (AnswerType)EditorGUILayout.EnumPopup(qData.answerType2[qData.number-1]); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); qData.answer3[qData.number-1] = EditorGUILayout.TextField(qData.answer3[qData.number-1]); GUILayout.Label("Correct or Incorrect?"); qData.answerType3[qData.number-1] = (AnswerType)EditorGUILayout.EnumPopup(qData.answerType3[qData.number-1]); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); qData.answer4[qData.number-1] = EditorGUILayout.TextField(qData.answer4[qData.number-1]); GUILayout.Label("Correct or Incorrect?"); qData.answerType4[qData.number-1] = (AnswerType)EditorGUILayout.EnumPopup(qData.answerType4[qData.number-1]); EditorGUILayout.EndHorizontal(); if (GUILayout.Button("Save", GUILayout.Height(30))) { window.Close(); } } }
34.072917
123
0.644655
[ "MIT" ]
hsm170330/Trivia-System-Developer-Tool
Assets/editor/TriviaDesignerWindow.cs
9,815
C#
using Core.Block; using Core.Block.Blocks; using Game.World.Interface.DataStore; namespace Game.World.Interface.Event { public class BlockRemoveEventProperties { public readonly Coordinate Coordinate; public readonly IBlock Block; public BlockRemoveEventProperties(Coordinate coordinate, IBlock block) { Coordinate = coordinate; Block = block; } } }
23.722222
78
0.672131
[ "MIT" ]
moorestech/moorestech
Game.World.Interface/Event/BlockRemoveEventProperties.cs
427
C#