content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using UnityEngine.Purchasing.Extension; namespace UnityEngine.Purchasing { interface IGooglePlayStoreExtensionsInternal { void SetStoreCallback(IStoreCallback storeCallback); } }
19.454545
60
0.775701
[ "Apache-2.0" ]
ASlugin/Homework-2sem
SCP-087/Library/PackageCache/com.unity.purchasing@4.1.4/Runtime/Stores/Android/GooglePlay/Interfaces/IGooglePlayStoreExtensionsInternal.cs
214
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="CurrentPlayerResult.cs" company="SyndicatedLife"> // Copyright(c) 2018 Ryan Wilson &amp;lt;syndicated.life@gmail.com&amp;gt; (http://syndicated.life/) // Licensed under the MIT license. See LICENSE.md in the solution root for full license information. // </copyright> // <summary> // CurrentPlayerResult.cs Implementation // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Sharlayan.Models.ReadResults { using Sharlayan.Core; public class CurrentPlayerResult { public CurrentPlayer CurrentPlayer { get; set; } = new CurrentPlayer(); } }
46.941176
120
0.506266
[ "MIT" ]
MusicalMiqo/sharlayan
Sharlayan/Models/ReadResults/CurrentPlayerResult.cs
800
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace KubernetesService.Models { using Microsoft.Rest; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// SecretList is a list of Secret. /// </summary> public partial class Iok8sapicorev1SecretList { /// <summary> /// Initializes a new instance of the Iok8sapicorev1SecretList class. /// </summary> public Iok8sapicorev1SecretList() { CustomInit(); } /// <summary> /// Initializes a new instance of the Iok8sapicorev1SecretList class. /// </summary> /// <param name="items">Items is a list of secret objects. More info: /// https://kubernetes.io/docs/concepts/configuration/secret</param> /// <param name="apiVersion">APIVersion defines the versioned schema of /// this representation of an object. Servers should convert recognized /// schemas to the latest internal value, and may reject unrecognized /// values. More info: /// https://git.k8s.io/community/contributors/devel/api-conventions.md#resources</param> /// <param name="kind">Kind is a string value representing the REST /// resource this object represents. Servers may infer this from the /// endpoint the client submits requests to. Cannot be updated. In /// CamelCase. More info: /// https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds</param> /// <param name="metadata">Standard list metadata. More info: /// https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds</param> public Iok8sapicorev1SecretList(IList<Iok8sapicorev1Secret> items, string apiVersion = default(string), string kind = default(string), Iok8sapimachinerypkgapismetav1ListMeta metadata = default(Iok8sapimachinerypkgapismetav1ListMeta)) { ApiVersion = apiVersion; Items = items; Kind = kind; Metadata = metadata; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets aPIVersion defines the versioned schema of this /// representation of an object. Servers should convert recognized /// schemas to the latest internal value, and may reject unrecognized /// values. More info: /// https://git.k8s.io/community/contributors/devel/api-conventions.md#resources /// </summary> [JsonProperty(PropertyName = "apiVersion")] public string ApiVersion { get; set; } /// <summary> /// Gets or sets items is a list of secret objects. More info: /// https://kubernetes.io/docs/concepts/configuration/secret /// </summary> [JsonProperty(PropertyName = "items")] public IList<Iok8sapicorev1Secret> Items { get; set; } /// <summary> /// Gets or sets kind is a string value representing the REST resource /// this object represents. Servers may infer this from the endpoint /// the client submits requests to. Cannot be updated. In CamelCase. /// More info: /// https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds /// </summary> [JsonProperty(PropertyName = "kind")] public string Kind { get; set; } /// <summary> /// Gets or sets standard list metadata. More info: /// https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds /// </summary> [JsonProperty(PropertyName = "metadata")] public Iok8sapimachinerypkgapismetav1ListMeta Metadata { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (Items == null) { throw new ValidationException(ValidationRules.CannotBeNull, "Items"); } if (Items != null) { foreach (var element in Items) { if (element != null) { element.Validate(); } } } } } }
40.177966
241
0.605147
[ "MIT" ]
tonnyeremin/kubernetes_gen
KubernetesService/Source/CSharp_Kubernetes/Models/Iok8sapicorev1SecretList.cs
4,741
C#
using System; using System.Xml.Serialization; using System.ComponentModel.DataAnnotations; using BroadWorksConnector.Ocip.Validation; using System.Collections.Generic; namespace BroadWorksConnector.Ocip.Models { /// <summary> /// Request the user's Call Center Monitoring settings. /// The response is either a UserCallCenterMonitoringGetResponse23 or an ErrorResponse. /// <see cref="UserCallCenterMonitoringGetResponse23"/> /// <see cref="ErrorResponse"/> /// </summary> [Serializable] [XmlRoot(Namespace = "")] [Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""41b968f87257b8dd553215179161ccb4:150""}]")] public class UserCallCenterMonitoringGetRequest23 : BroadWorksConnector.Ocip.Models.C.OCIRequest { private string _userId; [XmlElement(ElementName = "userId", IsNullable = false, Namespace = "")] [Group(@"41b968f87257b8dd553215179161ccb4:150")] [MinLength(1)] [MaxLength(161)] public string UserId { get => _userId; set { UserIdSpecified = true; _userId = value; } } [XmlIgnore] protected bool UserIdSpecified { get; set; } } }
29.813953
129
0.640406
[ "MIT" ]
Rogn/broadworks-connector-net
BroadworksConnector/Ocip/Models/UserCallCenterMonitoringGetRequest23.cs
1,282
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the rds-2014-10-31.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.RDS.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.RDS.Model.Internal.MarshallTransformations { /// <summary> /// RestoreDBClusterToPointInTime Request Marshaller /// </summary> public class RestoreDBClusterToPointInTimeRequestMarshaller : IMarshaller<IRequest, RestoreDBClusterToPointInTimeRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((RestoreDBClusterToPointInTimeRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(RestoreDBClusterToPointInTimeRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.RDS"); request.Parameters.Add("Action", "RestoreDBClusterToPointInTime"); request.Parameters.Add("Version", "2014-10-31"); if(publicRequest != null) { if(publicRequest.IsSetBacktrackWindow()) { request.Parameters.Add("BacktrackWindow", StringUtils.FromLong(publicRequest.BacktrackWindow)); } if(publicRequest.IsSetDBClusterIdentifier()) { request.Parameters.Add("DBClusterIdentifier", StringUtils.FromString(publicRequest.DBClusterIdentifier)); } if(publicRequest.IsSetDBClusterParameterGroupName()) { request.Parameters.Add("DBClusterParameterGroupName", StringUtils.FromString(publicRequest.DBClusterParameterGroupName)); } if(publicRequest.IsSetDBSubnetGroupName()) { request.Parameters.Add("DBSubnetGroupName", StringUtils.FromString(publicRequest.DBSubnetGroupName)); } if(publicRequest.IsSetDeletionProtection()) { request.Parameters.Add("DeletionProtection", StringUtils.FromBool(publicRequest.DeletionProtection)); } if(publicRequest.IsSetEnableCloudwatchLogsExports()) { int publicRequestlistValueIndex = 1; foreach(var publicRequestlistValue in publicRequest.EnableCloudwatchLogsExports) { request.Parameters.Add("EnableCloudwatchLogsExports" + "." + "member" + "." + publicRequestlistValueIndex, StringUtils.FromString(publicRequestlistValue)); publicRequestlistValueIndex++; } } if(publicRequest.IsSetEnableIAMDatabaseAuthentication()) { request.Parameters.Add("EnableIAMDatabaseAuthentication", StringUtils.FromBool(publicRequest.EnableIAMDatabaseAuthentication)); } if(publicRequest.IsSetKmsKeyId()) { request.Parameters.Add("KmsKeyId", StringUtils.FromString(publicRequest.KmsKeyId)); } if(publicRequest.IsSetOptionGroupName()) { request.Parameters.Add("OptionGroupName", StringUtils.FromString(publicRequest.OptionGroupName)); } if(publicRequest.IsSetPort()) { request.Parameters.Add("Port", StringUtils.FromInt(publicRequest.Port)); } if(publicRequest.IsSetRestoreToTimeUtc()) { request.Parameters.Add("RestoreToTime", StringUtils.FromDateTimeToISO8601(publicRequest.RestoreToTimeUtc)); } if(publicRequest.IsSetRestoreType()) { request.Parameters.Add("RestoreType", StringUtils.FromString(publicRequest.RestoreType)); } if(publicRequest.IsSetSourceDBClusterIdentifier()) { request.Parameters.Add("SourceDBClusterIdentifier", StringUtils.FromString(publicRequest.SourceDBClusterIdentifier)); } if(publicRequest.IsSetTags()) { int publicRequestlistValueIndex = 1; foreach(var publicRequestlistValue in publicRequest.Tags) { if(publicRequestlistValue.IsSetKey()) { request.Parameters.Add("Tags" + "." + "member" + "." + publicRequestlistValueIndex + "." + "Key", StringUtils.FromString(publicRequestlistValue.Key)); } if(publicRequestlistValue.IsSetValue()) { request.Parameters.Add("Tags" + "." + "member" + "." + publicRequestlistValueIndex + "." + "Value", StringUtils.FromString(publicRequestlistValue.Value)); } publicRequestlistValueIndex++; } } if(publicRequest.IsSetUseLatestRestorableTime()) { request.Parameters.Add("UseLatestRestorableTime", StringUtils.FromBool(publicRequest.UseLatestRestorableTime)); } if(publicRequest.IsSetVpcSecurityGroupIds()) { int publicRequestlistValueIndex = 1; foreach(var publicRequestlistValue in publicRequest.VpcSecurityGroupIds) { request.Parameters.Add("VpcSecurityGroupIds" + "." + "member" + "." + publicRequestlistValueIndex, StringUtils.FromString(publicRequestlistValue)); publicRequestlistValueIndex++; } } } return request; } private static RestoreDBClusterToPointInTimeRequestMarshaller _instance = new RestoreDBClusterToPointInTimeRequestMarshaller(); internal static RestoreDBClusterToPointInTimeRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static RestoreDBClusterToPointInTimeRequestMarshaller Instance { get { return _instance; } } } }
45.372781
182
0.589724
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/RDS/Generated/Model/Internal/MarshallTransformations/RestoreDBClusterToPointInTimeRequestMarshaller.cs
7,668
C#
namespace Projekat { partial class StudentForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.ObrisiButton = new System.Windows.Forms.Button(); this.UnesiButton = new System.Windows.Forms.Button(); this.tabControl1 = new System.Windows.Forms.TabControl(); this.tabPage1 = new System.Windows.Forms.TabPage(); this.comboBox7 = new System.Windows.Forms.ComboBox(); this.comboBox6 = new System.Windows.Forms.ComboBox(); this.comboBox5 = new System.Windows.Forms.ComboBox(); this.label9 = new System.Windows.Forms.Label(); this.comboBox2 = new System.Windows.Forms.ComboBox(); this.label11 = new System.Windows.Forms.Label(); this.textBox6 = new System.Windows.Forms.TextBox(); this.label8 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.textBox4 = new System.Windows.Forms.TextBox(); this.label5 = new System.Windows.Forms.Label(); this.textBox3 = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.textBox2 = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.textBox1 = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.tabPage2 = new System.Windows.Forms.TabPage(); this.comboBox8 = new System.Windows.Forms.ComboBox(); this.comboBox9 = new System.Windows.Forms.ComboBox(); this.comboBox10 = new System.Windows.Forms.ComboBox(); this.comboBox3 = new System.Windows.Forms.ComboBox(); this.textBox7 = new System.Windows.Forms.TextBox(); this.label13 = new System.Windows.Forms.Label(); this.label14 = new System.Windows.Forms.Label(); this.label15 = new System.Windows.Forms.Label(); this.textBox9 = new System.Windows.Forms.TextBox(); this.label16 = new System.Windows.Forms.Label(); this.textBox10 = new System.Windows.Forms.TextBox(); this.label17 = new System.Windows.Forms.Label(); this.textBox11 = new System.Windows.Forms.TextBox(); this.label18 = new System.Windows.Forms.Label(); this.textBox12 = new System.Windows.Forms.TextBox(); this.label19 = new System.Windows.Forms.Label(); this.label10 = new System.Windows.Forms.Label(); this.IzmeniButton = new System.Windows.Forms.Button(); this.comboBox1 = new System.Windows.Forms.ComboBox(); this.label12 = new System.Windows.Forms.Label(); this.tabPage3 = new System.Windows.Forms.TabPage(); this.comboBox4 = new System.Windows.Forms.ComboBox(); this.label20 = new System.Windows.Forms.Label(); this.tabControl1.SuspendLayout(); this.tabPage1.SuspendLayout(); this.tabPage2.SuspendLayout(); this.tabPage3.SuspendLayout(); this.SuspendLayout(); // // ObrisiButton // this.ObrisiButton.Location = new System.Drawing.Point(197, 351); this.ObrisiButton.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.ObrisiButton.Name = "ObrisiButton"; this.ObrisiButton.Size = new System.Drawing.Size(111, 42); this.ObrisiButton.TabIndex = 114; this.ObrisiButton.Text = "Obrisi"; this.ObrisiButton.UseVisualStyleBackColor = true; this.ObrisiButton.Click += new System.EventHandler(this.ObrisiButton_Click); // // UnesiButton // this.UnesiButton.Location = new System.Drawing.Point(188, 503); this.UnesiButton.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.UnesiButton.Name = "UnesiButton"; this.UnesiButton.Size = new System.Drawing.Size(111, 42); this.UnesiButton.TabIndex = 109; this.UnesiButton.Text = "Unesi"; this.UnesiButton.UseVisualStyleBackColor = true; this.UnesiButton.Click += new System.EventHandler(this.UnesiButton_Click); // // tabControl1 // this.tabControl1.Controls.Add(this.tabPage1); this.tabControl1.Controls.Add(this.tabPage2); this.tabControl1.Controls.Add(this.tabPage3); this.tabControl1.Location = new System.Drawing.Point(3, 0); this.tabControl1.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size(511, 666); this.tabControl1.TabIndex = 115; // // tabPage1 // this.tabPage1.Controls.Add(this.comboBox7); this.tabPage1.Controls.Add(this.comboBox6); this.tabPage1.Controls.Add(this.comboBox5); this.tabPage1.Controls.Add(this.label9); this.tabPage1.Controls.Add(this.comboBox2); this.tabPage1.Controls.Add(this.UnesiButton); this.tabPage1.Controls.Add(this.label11); this.tabPage1.Controls.Add(this.textBox6); this.tabPage1.Controls.Add(this.label8); this.tabPage1.Controls.Add(this.label7); this.tabPage1.Controls.Add(this.label6); this.tabPage1.Controls.Add(this.textBox4); this.tabPage1.Controls.Add(this.label5); this.tabPage1.Controls.Add(this.textBox3); this.tabPage1.Controls.Add(this.label4); this.tabPage1.Controls.Add(this.textBox2); this.tabPage1.Controls.Add(this.label3); this.tabPage1.Controls.Add(this.textBox1); this.tabPage1.Controls.Add(this.label2); this.tabPage1.Controls.Add(this.label1); this.tabPage1.Location = new System.Drawing.Point(4, 25); this.tabPage1.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.tabPage1.Name = "tabPage1"; this.tabPage1.Padding = new System.Windows.Forms.Padding(4, 4, 4, 4); this.tabPage1.Size = new System.Drawing.Size(503, 637); this.tabPage1.TabIndex = 0; this.tabPage1.Text = "Unos studenta"; this.tabPage1.UseVisualStyleBackColor = true; // // comboBox7 // this.comboBox7.FormattingEnabled = true; this.comboBox7.Location = new System.Drawing.Point(344, 331); this.comboBox7.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.comboBox7.Name = "comboBox7"; this.comboBox7.Size = new System.Drawing.Size(96, 24); this.comboBox7.TabIndex = 156; // // comboBox6 // this.comboBox6.FormattingEnabled = true; this.comboBox6.Location = new System.Drawing.Point(272, 331); this.comboBox6.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.comboBox6.Name = "comboBox6"; this.comboBox6.Size = new System.Drawing.Size(63, 24); this.comboBox6.TabIndex = 155; this.comboBox6.SelectedIndexChanged += new System.EventHandler(this.comboBox6_SelectedIndexChanged); // // comboBox5 // this.comboBox5.FormattingEnabled = true; this.comboBox5.Location = new System.Drawing.Point(201, 331); this.comboBox5.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.comboBox5.Name = "comboBox5"; this.comboBox5.Size = new System.Drawing.Size(61, 24); this.comboBox5.TabIndex = 154; // // label9 // this.label9.AutoSize = true; this.label9.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label9.Location = new System.Drawing.Point(-5, -26); this.label9.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(372, 25); this.label9.TabIndex = 153; this.label9.Text = "Izaberite studenta za azurianje ili brisanje:"; // // comboBox2 // this.comboBox2.FormattingEnabled = true; this.comboBox2.Location = new System.Drawing.Point(201, 431); this.comboBox2.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.comboBox2.Name = "comboBox2"; this.comboBox2.Size = new System.Drawing.Size(239, 24); this.comboBox2.TabIndex = 152; // // label11 // this.label11.AutoSize = true; this.label11.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F); this.label11.Location = new System.Drawing.Point(107, 62); this.label11.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(285, 25); this.label11.TabIndex = 149; this.label11.Text = "Podaci za unos novog studenta"; // // textBox6 // this.textBox6.Location = new System.Drawing.Point(201, 380); this.textBox6.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.textBox6.Name = "textBox6"; this.textBox6.Size = new System.Drawing.Size(239, 22); this.textBox6.TabIndex = 148; // // label8 // this.label8.AutoSize = true; this.label8.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label8.Location = new System.Drawing.Point(77, 432); this.label8.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(49, 20); this.label8.TabIndex = 147; this.label8.Text = "Smer"; // // label7 // this.label7.AutoSize = true; this.label7.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label7.Location = new System.Drawing.Point(72, 380); this.label7.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(64, 20); this.label7.TabIndex = 146; this.label7.Text = "Telefon"; // // label6 // this.label6.AutoSize = true; this.label6.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label6.Location = new System.Drawing.Point(39, 331); this.label6.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(123, 20); this.label6.TabIndex = 144; this.label6.Text = "Datum rodjenja"; // // textBox4 // this.textBox4.Location = new System.Drawing.Point(201, 279); this.textBox4.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.textBox4.Name = "textBox4"; this.textBox4.Size = new System.Drawing.Size(239, 22); this.textBox4.TabIndex = 143; // // label5 // this.label5.AutoSize = true; this.label5.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label5.Location = new System.Drawing.Point(75, 281); this.label5.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(50, 20); this.label5.TabIndex = 142; this.label5.Text = "Jmbg"; // // textBox3 // this.textBox3.Location = new System.Drawing.Point(201, 229); this.textBox3.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.textBox3.Name = "textBox3"; this.textBox3.Size = new System.Drawing.Size(239, 22); this.textBox3.TabIndex = 141; // // label4 // this.label4.AutoSize = true; this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label4.Location = new System.Drawing.Point(68, 229); this.label4.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(71, 20); this.label4.TabIndex = 140; this.label4.Text = "Prezime"; // // textBox2 // this.textBox2.Location = new System.Drawing.Point(201, 180); this.textBox2.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.textBox2.Name = "textBox2"; this.textBox2.Size = new System.Drawing.Size(239, 22); this.textBox2.TabIndex = 139; // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.Location = new System.Drawing.Point(88, 181); this.label3.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(36, 20); this.label3.TabIndex = 138; this.label3.Text = "Ime"; // // textBox1 // this.textBox1.Location = new System.Drawing.Point(201, 133); this.textBox1.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(239, 22); this.textBox1.TabIndex = 137; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.Location = new System.Drawing.Point(77, 133); this.label2.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(48, 20); this.label2.TabIndex = 136; this.label2.Text = "Index"; // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(11, -32); this.label1.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(0, 25); this.label1.TabIndex = 135; // // tabPage2 // this.tabPage2.Controls.Add(this.comboBox8); this.tabPage2.Controls.Add(this.comboBox9); this.tabPage2.Controls.Add(this.comboBox10); this.tabPage2.Controls.Add(this.comboBox3); this.tabPage2.Controls.Add(this.textBox7); this.tabPage2.Controls.Add(this.label13); this.tabPage2.Controls.Add(this.label14); this.tabPage2.Controls.Add(this.label15); this.tabPage2.Controls.Add(this.textBox9); this.tabPage2.Controls.Add(this.label16); this.tabPage2.Controls.Add(this.textBox10); this.tabPage2.Controls.Add(this.label17); this.tabPage2.Controls.Add(this.textBox11); this.tabPage2.Controls.Add(this.label18); this.tabPage2.Controls.Add(this.textBox12); this.tabPage2.Controls.Add(this.label19); this.tabPage2.Controls.Add(this.label10); this.tabPage2.Controls.Add(this.IzmeniButton); this.tabPage2.Controls.Add(this.comboBox1); this.tabPage2.Controls.Add(this.label12); this.tabPage2.Location = new System.Drawing.Point(4, 25); this.tabPage2.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.tabPage2.Name = "tabPage2"; this.tabPage2.Padding = new System.Windows.Forms.Padding(4, 4, 4, 4); this.tabPage2.Size = new System.Drawing.Size(503, 637); this.tabPage2.TabIndex = 1; this.tabPage2.Text = "Azuriranje studenta"; this.tabPage2.UseVisualStyleBackColor = true; // // comboBox8 // this.comboBox8.FormattingEnabled = true; this.comboBox8.Location = new System.Drawing.Point(212, 357); this.comboBox8.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.comboBox8.Name = "comboBox8"; this.comboBox8.Size = new System.Drawing.Size(60, 24); this.comboBox8.TabIndex = 172; // // comboBox9 // this.comboBox9.FormattingEnabled = true; this.comboBox9.Location = new System.Drawing.Point(283, 357); this.comboBox9.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.comboBox9.Name = "comboBox9"; this.comboBox9.Size = new System.Drawing.Size(63, 24); this.comboBox9.TabIndex = 171; this.comboBox9.SelectedIndexChanged += new System.EventHandler(this.comboBox9_SelectedIndexChanged); // // comboBox10 // this.comboBox10.FormattingEnabled = true; this.comboBox10.Location = new System.Drawing.Point(355, 358); this.comboBox10.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.comboBox10.Name = "comboBox10"; this.comboBox10.Size = new System.Drawing.Size(96, 24); this.comboBox10.TabIndex = 170; // // comboBox3 // this.comboBox3.FormattingEnabled = true; this.comboBox3.Location = new System.Drawing.Point(212, 458); this.comboBox3.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.comboBox3.Name = "comboBox3"; this.comboBox3.Size = new System.Drawing.Size(239, 24); this.comboBox3.TabIndex = 169; // // textBox7 // this.textBox7.Location = new System.Drawing.Point(212, 407); this.textBox7.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.textBox7.Name = "textBox7"; this.textBox7.Size = new System.Drawing.Size(239, 22); this.textBox7.TabIndex = 168; // // label13 // this.label13.AutoSize = true; this.label13.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label13.Location = new System.Drawing.Point(88, 459); this.label13.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label13.Name = "label13"; this.label13.Size = new System.Drawing.Size(49, 20); this.label13.TabIndex = 167; this.label13.Text = "Smer"; // // label14 // this.label14.AutoSize = true; this.label14.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label14.Location = new System.Drawing.Point(83, 407); this.label14.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label14.Name = "label14"; this.label14.Size = new System.Drawing.Size(64, 20); this.label14.TabIndex = 166; this.label14.Text = "Telefon"; // // label15 // this.label15.AutoSize = true; this.label15.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label15.Location = new System.Drawing.Point(49, 358); this.label15.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label15.Name = "label15"; this.label15.Size = new System.Drawing.Size(123, 20); this.label15.TabIndex = 164; this.label15.Text = "Datum rodjenja"; // // textBox9 // this.textBox9.Location = new System.Drawing.Point(212, 306); this.textBox9.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.textBox9.Name = "textBox9"; this.textBox9.Size = new System.Drawing.Size(239, 22); this.textBox9.TabIndex = 163; // // label16 // this.label16.AutoSize = true; this.label16.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label16.Location = new System.Drawing.Point(85, 308); this.label16.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label16.Name = "label16"; this.label16.Size = new System.Drawing.Size(50, 20); this.label16.TabIndex = 162; this.label16.Text = "Jmbg"; // // textBox10 // this.textBox10.Location = new System.Drawing.Point(212, 256); this.textBox10.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.textBox10.Name = "textBox10"; this.textBox10.Size = new System.Drawing.Size(239, 22); this.textBox10.TabIndex = 161; // // label17 // this.label17.AutoSize = true; this.label17.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label17.Location = new System.Drawing.Point(79, 256); this.label17.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label17.Name = "label17"; this.label17.Size = new System.Drawing.Size(71, 20); this.label17.TabIndex = 160; this.label17.Text = "Prezime"; // // textBox11 // this.textBox11.Location = new System.Drawing.Point(212, 207); this.textBox11.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.textBox11.Name = "textBox11"; this.textBox11.Size = new System.Drawing.Size(239, 22); this.textBox11.TabIndex = 159; // // label18 // this.label18.AutoSize = true; this.label18.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label18.Location = new System.Drawing.Point(99, 208); this.label18.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label18.Name = "label18"; this.label18.Size = new System.Drawing.Size(36, 20); this.label18.TabIndex = 158; this.label18.Text = "Ime"; // // textBox12 // this.textBox12.Location = new System.Drawing.Point(212, 160); this.textBox12.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.textBox12.Name = "textBox12"; this.textBox12.Size = new System.Drawing.Size(239, 22); this.textBox12.TabIndex = 157; // // label19 // this.label19.AutoSize = true; this.label19.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label19.Location = new System.Drawing.Point(88, 160); this.label19.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label19.Name = "label19"; this.label19.Size = new System.Drawing.Size(48, 20); this.label19.TabIndex = 156; this.label19.Text = "Index"; // // label10 // this.label10.AutoSize = true; this.label10.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F); this.label10.Location = new System.Drawing.Point(63, 89); this.label10.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(367, 25); this.label10.TabIndex = 155; this.label10.Text = "Podaci za azuriranje odabranog studenta"; // // IzmeniButton // this.IzmeniButton.Location = new System.Drawing.Point(179, 560); this.IzmeniButton.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.IzmeniButton.Name = "IzmeniButton"; this.IzmeniButton.Size = new System.Drawing.Size(111, 42); this.IzmeniButton.TabIndex = 154; this.IzmeniButton.Text = "Izmeni"; this.IzmeniButton.UseVisualStyleBackColor = true; this.IzmeniButton.Click += new System.EventHandler(this.IzmeniButton_Click_1); // // comboBox1 // this.comboBox1.FormattingEnabled = true; this.comboBox1.Location = new System.Drawing.Point(223, 28); this.comboBox1.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.comboBox1.Name = "comboBox1"; this.comboBox1.Size = new System.Drawing.Size(217, 24); this.comboBox1.TabIndex = 153; // // label12 // this.label12.AutoSize = true; this.label12.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label12.Location = new System.Drawing.Point(64, 30); this.label12.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(142, 20); this.label12.TabIndex = 152; this.label12.Text = "Izaberite studenta"; // // tabPage3 // this.tabPage3.Controls.Add(this.comboBox4); this.tabPage3.Controls.Add(this.label20); this.tabPage3.Controls.Add(this.ObrisiButton); this.tabPage3.Location = new System.Drawing.Point(4, 25); this.tabPage3.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.tabPage3.Name = "tabPage3"; this.tabPage3.Padding = new System.Windows.Forms.Padding(4, 4, 4, 4); this.tabPage3.Size = new System.Drawing.Size(503, 637); this.tabPage3.TabIndex = 2; this.tabPage3.Text = "Brisanje studenta"; this.tabPage3.UseVisualStyleBackColor = true; // // comboBox4 // this.comboBox4.FormattingEnabled = true; this.comboBox4.Location = new System.Drawing.Point(229, 156); this.comboBox4.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.comboBox4.Name = "comboBox4"; this.comboBox4.Size = new System.Drawing.Size(217, 24); this.comboBox4.TabIndex = 155; // // label20 // this.label20.AutoSize = true; this.label20.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label20.Location = new System.Drawing.Point(71, 158); this.label20.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label20.Name = "label20"; this.label20.Size = new System.Drawing.Size(142, 20); this.label20.TabIndex = 154; this.label20.Text = "Izaberite studenta"; // // StudentForm // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(512, 663); this.Controls.Add(this.tabControl1); this.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.Name = "StudentForm"; this.Text = "Student"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.StudentForm_FormClosing); this.Load += new System.EventHandler(this.StudentForm_Load); this.tabControl1.ResumeLayout(false); this.tabPage1.ResumeLayout(false); this.tabPage1.PerformLayout(); this.tabPage2.ResumeLayout(false); this.tabPage2.PerformLayout(); this.tabPage3.ResumeLayout(false); this.tabPage3.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button ObrisiButton; private System.Windows.Forms.Button UnesiButton; private System.Windows.Forms.TabControl tabControl1; private System.Windows.Forms.TabPage tabPage1; private System.Windows.Forms.Label label9; private System.Windows.Forms.ComboBox comboBox2; private System.Windows.Forms.Label label11; private System.Windows.Forms.TextBox textBox6; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label label6; private System.Windows.Forms.TextBox textBox4; private System.Windows.Forms.Label label5; private System.Windows.Forms.TextBox textBox3; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox textBox2; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label1; private System.Windows.Forms.TabPage tabPage2; private System.Windows.Forms.Button IzmeniButton; private System.Windows.Forms.ComboBox comboBox1; private System.Windows.Forms.Label label12; private System.Windows.Forms.TabPage tabPage3; private System.Windows.Forms.ComboBox comboBox3; private System.Windows.Forms.TextBox textBox7; private System.Windows.Forms.Label label13; private System.Windows.Forms.Label label14; private System.Windows.Forms.Label label15; private System.Windows.Forms.TextBox textBox9; private System.Windows.Forms.Label label16; private System.Windows.Forms.TextBox textBox10; private System.Windows.Forms.Label label17; private System.Windows.Forms.TextBox textBox11; private System.Windows.Forms.Label label18; private System.Windows.Forms.TextBox textBox12; private System.Windows.Forms.Label label19; private System.Windows.Forms.Label label10; private System.Windows.Forms.ComboBox comboBox4; private System.Windows.Forms.Label label20; private System.Windows.Forms.ComboBox comboBox7; private System.Windows.Forms.ComboBox comboBox6; private System.Windows.Forms.ComboBox comboBox5; private System.Windows.Forms.ComboBox comboBox8; private System.Windows.Forms.ComboBox comboBox9; private System.Windows.Forms.ComboBox comboBox10; } }
52.313343
170
0.576018
[ "MIT" ]
while1618/College
C#/Projekat/Projekat/admin/StudentForm.designer.cs
34,895
C#
using System; using Prism.Mvvm; using Xamarin.Forms; using System.ComponentModel; using System.Threading.Tasks; namespace MVVMEasy.Pages { public class LoginPageViewModel_FodyPropertyChanged : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public LoginPageViewModel_FodyPropertyChanged () { ErrorMessage = ""; LoginInProgress = false; Username = ""; Password = ""; Login = new Command (async _ => { ErrorMessage = ""; LoginInProgress = true; Login.ChangeCanExecute (); try { // perform login await Task.Delay (5000); } catch (Exception e) { ErrorMessage = e.Message; } LoginInProgress = false; Login.ChangeCanExecute (); }, _ => !LoginInProgress && (Username.Length > 0 && Password.Length > 0)); } public Command Login { get; set; } public string ErrorMessage { get; set; } public bool IsError { get { return ErrorMessage != ""; } } public bool LoginInProgress { get; set; } public bool LoginNotInProgress { get { return !LoginInProgress; } } public string Username { get; set; } public string Password { get; set; } } }
28.372549
86
0.542502
[ "MIT" ]
pshomov/mvvmeasy
Pages/LoginPageViewModel_FodyPropertyChanged.cs
1,449
C#
using TypeCast.Attributes; using TypeCast.ContentTypes; using TypeCast.DataTypes.BuiltIn; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace TypeCast.TestTarget.TypeSet1 { [DocumentType(allowAtRoot: true)] public class Master : DocumentTypeBase { [ContentProperty] public virtual Textstring MasterTextstringRoot { get; set; } [ContentProperty] public virtual TrueFalse MasterTrueFalseRoot { get; set; } [ContentProperty] public virtual Numeric MasterNumericRoot { get; set; } [ContentTab] public virtual MasterTab MasterTab { get; set; } } [CodeFirstCommonBase] public class CommonTabBase : TabBase { [ContentProperty] public virtual TrueFalse CommonTabBaseTrueFalse { get; set; } } public class MasterTab : CommonTabBase { [ContentProperty] public virtual RichtextEditor MasterRichtextEditorTab { get; set; } [ContentProperty] public virtual DatePicker MasterDatePickerTab { get; set; } } [DocumentType] public class Child1 : Master { [ContentProperty] public virtual Textstring Child1TextstringRoot { get; set; } [ContentProperty] public virtual TrueFalse Child1TrueFalseRoot { get; set; } [ContentProperty] public virtual Numeric Child1NumericRoot { get; set; } [ContentTab] public virtual Child1Tab Child1Tab { get; set; } } public class Child1Tab : CommonTabBase { [ContentProperty] public virtual RichtextEditor Child1RichtextEditorTab { get; set; } [ContentProperty] public virtual DatePicker Child1DatePickerTab { get; set; } } [DocumentType] public class Child2 : Master { [ContentProperty] public virtual Textstring Child2TextstringRoot { get; set; } [ContentProperty] public virtual TrueFalse Child2TrueFalseRoot { get; set; } [ContentProperty] public virtual Numeric Child2NumericRoot { get; set; } } [DocumentType] public class GrandChild1 : Child1 { [ContentProperty] public virtual Textstring Grandchild1TextstringRoot { get; set; } [ContentProperty] public virtual TrueFalse Grandchild1TrueFalseRoot { get; set; } [ContentProperty] public virtual Numeric Grandchild1NumericRoot { get; set; } [ContentTab] public virtual GrandChild1Tab Grandchild1Tab { get; set; } } public class GrandChild1Tab : CommonTabBase { [ContentProperty] public virtual RichtextEditor Grandchild1RichtextEditorTab { get; set; } [ContentProperty] public virtual DatePicker Grandchild1DatePickerTab { get; set; } } }
27.047619
80
0.66338
[ "MIT" ]
eviathan/TypeCast
TypeCast.Tests/TypeSet1/DocTypes.cs
2,842
C#
using System; using AssetReference.Runtime.References; using UnityEngine; namespace AssetReference.Runtime.References { [Serializable] public class AssetReferenceRuntimeAnimatorController : AssetReference<RuntimeAnimatorController> { } }
21.916667
100
0.775665
[ "MIT" ]
JingFengJi/AssetReferenceSelectEditor
AssetReferenceSelectEditor/Assets/AssetReference/Runtime/References/AssetReferenceRuntimeAnimatorController.cs
263
C#
using DotnetGraph.Model.Properties; using System.Collections.Generic; using System.Diagnostics; namespace DotnetGraph.Model.Implementations.Graph.DirectedGraph { [DebuggerDisplay("Node {Id}")] public class DirectedGraphNode : IHasOutgoingArcs<DirectedGraphArc>, IHasId { private readonly List<DirectedGraphArc> outgoingArcs; public DirectedGraphNode(int id, IList<DirectedGraphArc> outgoingArcs = null) { Id = id; this.outgoingArcs = outgoingArcs is null ? new List<DirectedGraphArc>() : new List<DirectedGraphArc>(outgoingArcs); } public IReadOnlyCollection<DirectedGraphArc> OutgoingArcs => outgoingArcs; public int Id { get; } public void Add(DirectedGraphArc arc) { outgoingArcs.Add(arc); } } }
31.259259
127
0.668246
[ "Apache-2.0" ]
jasdefer/DotnetGraph
DotnetGraph/Source/DotnetGraph/Model/Implementations/Graph/DirectedGraph/DirectedGraphNode.cs
846
C#
using System; using System.Collections.Generic; using System.Linq; namespace IdeagenCalculator { public class RecursionCalculator : Calculator { public override double Calculate(string expression) { if (!IsExpressionValid(expression)) { throw new InvalidExpressionException(ExceptionType.InvalidExpression, "Invalid expression."); } var tokens = expression.Split().ToList(); // return the value as it is. if (tokens.Count == 1) { return double.TryParse(tokens[0], out var result) ? result : 0; } // Simple arithmetric will just end here. if (tokens.Count == 3) { return Resolve(ToDouble(tokens[0]), ToDouble(tokens[2]), tokens[1]); } // Perform all the bracket operation first. tokens = PerformBracketArithmetric(tokens); // Then follow by multiplication and division. tokens = PerformArithmetric(tokens, MULTIPLICATION_OPERATOR, DIVISION_OPERATOR); // Then follow by addition and substraction. tokens = PerformArithmetric(tokens, SUMMATION_OPERATOR, SUBTRACTION_OPERATOR); // At this point the tokens list should only have 1 item left, and the last item is the result. return ToDouble(tokens.First()); } /// <summary> /// Resolve bracketed operation. /// </summary> /// <param name="tokens">Tokenized expression</param> /// <returns>Tokenized expression after the operation</returns> private List<string> PerformBracketArithmetric(List<string> tokens) { var subExpressionBody = new List<string>(); // Keep track on how many opening bracket along the way, so we can find correct closing bracket. int leftParenthesesCount = 0; bool foundOpeningBracket = false; for (var i = 0; i < tokens.Count; i++) { // Skip when empty which is possible after the operation in the nested loop. if (String.IsNullOrEmpty(tokens[i])) continue; // When a bracket opening is found, start a nested loop to search for the closing bracket. if (tokens[i] == LEFT_PARENTHESES && !foundOpeningBracket) { // To know we actually want to start extract value now foundOpeningBracket = true; // Remove the left parentheses. tokens[i] = String.Empty; // Move the next iteration continue; } // Increment when found a opening bracket. if (tokens[i] == LEFT_PARENTHESES && foundOpeningBracket) { leftParenthesesCount++; } // When a closing bracket is found if (tokens[i] == RIGHT_PARENTHESES && foundOpeningBracket) { // See if we have any inner bracket. // If yes, decrement the count and continue the search. if (leftParenthesesCount > 0) { leftParenthesesCount--; } // Otherwise, mean this is the correct closing bracket // Create a subexpression by removing the opening and closing bracket, and recall this method through recursion. // Also break out of the nested loop to continue searching for next outer opening bracket. else { var subExpression = String.Join(" ", subExpressionBody); var subOperationResult = Calculate(subExpression).ToString(); tokens[i] = subOperationResult; // Reset these foundOpeningBracket = false; leftParenthesesCount = 0; subExpressionBody.Clear(); continue; } } if (foundOpeningBracket) { // Push all the items into the list along the way. subExpressionBody.Add(tokens[i]); // Also set ALL the item along the way to empty so we could clear them later. tokens[i] = String.Empty; } } return RemoveEmptyString(tokens); } /// <summary> /// Resolve sum, substract, multiply, and divide. /// </summary> /// <param name="tokens">Tokenized expression</param> /// <param name="operators">The operator to resolve</param> /// <returns>Tokenized expression after the operation</returns> private List<string> PerformArithmetric(List<string> tokens, params string[] operators) { var indexes = FindIndex(tokens, operators); for (var i = 0; i < indexes.Count(); i++) { var index = indexes[i]; var subExpression = String.Join(" ", new List<string>() { tokens[index - 1], tokens[index], tokens[index + 1] }); var subOperationResult = Calculate(subExpression).ToString(); tokens[index + 1] = subOperationResult; tokens[index - 1] = String.Empty; tokens[index] = String.Empty; } return RemoveEmptyString(tokens); } /// <summary> /// Finding all the index(s) in the expressions /// </summary> /// <param name="tokens">Tokenized expression</param> /// <param name="operators">Operator to look for</param> /// <returns></returns> private List<int> FindIndex(IEnumerable<string> tokens, params string[] operators) { return tokens.Select((token, index) => new { token, index }) .Where(x => operators.Any(oper => oper == x.token)) .Select(x => x.index) .ToList(); } /// <summary> /// Clean up all empty token in the expression. /// </summary> /// <param name="tokens"></param> /// <returns></returns> private List<string> RemoveEmptyString(IEnumerable<string> tokens) { return tokens.Where(token => !String.IsNullOrEmpty(token)).ToList(); } } }
39.640719
132
0.529305
[ "MIT" ]
hylimR/calculator
RecursionCalculator.cs
6,622
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SEDC.NotesApp.Repositories { public interface IRepository<T> { List<T> GetAll(); T GetById(int id); void Add(T entity); void Remove(int id); void Update(T entity); } }
19.352941
36
0.638298
[ "MIT" ]
sedc-codecademy/skwd9-09-aspnetwebapi
G3/Class_04/SEDC.NotesApp/SEDC.NotesApp/Repositories/IRepository.cs
331
C#
namespace UnityStandardAssets.CinematicEffects { using UnityEngine; using UnityEditor; using UnityEditorInternal; using System.Reflection; using System.Collections.Generic; using System.Linq; [CanEditMultipleObjects, CustomEditor(typeof(TonemappingColorGrading))] public class TonemappingColorGradingEditor : Editor { #region Property drawers [CustomPropertyDrawer(typeof(TonemappingColorGrading.ColorWheelGroup))] private class ColorWheelGroupDrawer : PropertyDrawer { int m_RenderSizePerWheel; int m_NumberOfWheels; public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { var wheelAttribute = (TonemappingColorGrading.ColorWheelGroup)attribute; property.isExpanded = true; m_NumberOfWheels = property.CountInProperty() - 1; if (m_NumberOfWheels == 0) return 0f; m_RenderSizePerWheel = Mathf.FloorToInt((EditorGUIUtility.currentViewWidth) / m_NumberOfWheels) - 30; m_RenderSizePerWheel = Mathf.Clamp(m_RenderSizePerWheel, wheelAttribute.minSizePerWheel, wheelAttribute.maxSizePerWheel); m_RenderSizePerWheel = Mathf.FloorToInt(pixelRatio * m_RenderSizePerWheel); return ColorWheel.GetColorWheelHeight(m_RenderSizePerWheel); } public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { if (m_NumberOfWheels == 0) return; var width = position.width; Rect newPosition = new Rect(position.x, position.y, width / m_NumberOfWheels, position.height); foreach (SerializedProperty prop in property) { if (prop.propertyType == SerializedPropertyType.Color) prop.colorValue = ColorWheel.DoGUI(newPosition, prop.displayName, prop.colorValue, m_RenderSizePerWheel); newPosition.x += width / m_NumberOfWheels; } } } [CustomPropertyDrawer(typeof(TonemappingColorGrading.IndentedGroup))] private class IndentedGroupDrawer : PropertyDrawer { public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { return 0f; } public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { EditorGUILayout.LabelField(label, EditorStyles.boldLabel); EditorGUI.indentLevel++; foreach (SerializedProperty prop in property) EditorGUILayout.PropertyField(prop); EditorGUI.indentLevel--; } } [CustomPropertyDrawer(typeof(TonemappingColorGrading.ChannelMixer))] private class ChannelMixerDrawer : PropertyDrawer { public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { return 0f; } public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { // TODO: Hardcoded variable names, rewrite this function if (property.type != "ChannelMixerSettings") return; SerializedProperty currentChannel = property.FindPropertyRelative("currentChannel"); int intCurrentChannel = currentChannel.intValue; EditorGUILayout.LabelField(label, EditorStyles.boldLabel); EditorGUI.indentLevel++; EditorGUILayout.BeginHorizontal(); { EditorGUILayout.PrefixLabel("Channel"); if (GUILayout.Toggle(intCurrentChannel == 0, "Red", EditorStyles.miniButtonLeft)) intCurrentChannel = 0; if (GUILayout.Toggle(intCurrentChannel == 1, "Green", EditorStyles.miniButtonMid)) intCurrentChannel = 1; if (GUILayout.Toggle(intCurrentChannel == 2, "Blue", EditorStyles.miniButtonRight)) intCurrentChannel = 2; } EditorGUILayout.EndHorizontal(); SerializedProperty serializedChannel = property.FindPropertyRelative("channels").GetArrayElementAtIndex(intCurrentChannel); currentChannel.intValue = intCurrentChannel; Vector3 v = serializedChannel.vector3Value; v.x = EditorGUILayout.Slider("Red", v.x, -2f, 2f); v.y = EditorGUILayout.Slider("Green", v.y, -2f, 2f); v.z = EditorGUILayout.Slider("Blue", v.z, -2f, 2f); serializedChannel.vector3Value = v; EditorGUI.indentLevel--; } } [CustomPropertyDrawer(typeof(TonemappingColorGrading.Curve))] private class CurveDrawer : PropertyDrawer { public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { TonemappingColorGrading.Curve attribute = (TonemappingColorGrading.Curve)base.attribute; if (property.propertyType != SerializedPropertyType.AnimationCurve) { EditorGUI.LabelField(position, label.text, "Use ClampCurve with an AnimationCurve."); return; } property.animationCurveValue = EditorGUI.CurveField(position, label, property.animationCurveValue, attribute.color, new Rect(0f, 0f, 1f, 1f)); } } #endregion #region Styling private static Styles s_Styles; private class Styles { public GUIStyle thumb2D = "ColorPicker2DThumb"; public Vector2 thumb2DSize; internal Styles() { thumb2DSize = new Vector2( !Mathf.Approximately(thumb2D.fixedWidth, 0f) ? thumb2D.fixedWidth : thumb2D.padding.horizontal, !Mathf.Approximately(thumb2D.fixedHeight, 0f) ? thumb2D.fixedHeight : thumb2D.padding.vertical ); } } public static readonly Color masterCurveColor = new Color(1f, 1f, 1f, 2f); public static readonly Color redCurveColor = new Color(1f, 0f, 0f, 2f); public static readonly Color greenCurveColor = new Color(0f, 1f, 0f, 2f); public static readonly Color blueCurveColor = new Color(0f, 1f, 1f, 2f); #endregion private TonemappingColorGrading concreteTarget { get { return target as TonemappingColorGrading; } } private static float pixelRatio { get { #if !(UNITY_3 || UNITY_4 || UNITY_5_0 || UNITY_5_1 || UNITY_5_2 || UNITY_5_3) return EditorGUIUtility.pixelsPerPoint; #else return 1f; #endif } } private bool isHistogramSupported { get { return concreteTarget.histogramComputeShader != null && ImageEffectHelper.supportsDX11 && concreteTarget.histogramShader != null && concreteTarget.histogramShader.isSupported; } } private enum HistogramMode { Red = 0, Green = 1, Blue = 2, Luminance = 3, RGB, } private HistogramMode m_HistogramMode = HistogramMode.RGB; private Rect m_HistogramRect; private Material m_HistogramMaterial; private ComputeBuffer m_HistogramBuffer; private RenderTexture m_HistogramTexture; // settings group <setting, property reference> private Dictionary<FieldInfo, List<SerializedProperty>> m_GroupFields = new Dictionary<FieldInfo, List<SerializedProperty>>(); private void PopulateMap(FieldInfo group) { var searchPath = group.Name + "."; foreach (var setting in group.FieldType.GetFields(BindingFlags.Instance | BindingFlags.Public)) { List<SerializedProperty> settingsGroup; if (!m_GroupFields.TryGetValue(group, out settingsGroup)) { settingsGroup = new List<SerializedProperty>(); m_GroupFields[group] = settingsGroup; } var property = serializedObject.FindProperty(searchPath + setting.Name); if (property != null) settingsGroup.Add(property); } } private void OnEnable() { var settingsGroups = typeof(TonemappingColorGrading).GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).Where(x => x.GetCustomAttributes(typeof(TonemappingColorGrading.SettingsGroup), false).Any()); foreach (var settingGroup in settingsGroups) PopulateMap(settingGroup); concreteTarget.onFrameEndEditorOnly = OnFrameEnd; } private void OnDisable() { concreteTarget.onFrameEndEditorOnly = null; if (m_HistogramMaterial != null) DestroyImmediate(m_HistogramMaterial); if (m_HistogramTexture != null) DestroyImmediate(m_HistogramTexture); if (m_HistogramBuffer != null) m_HistogramBuffer.Release(); } private void SetLUTImportSettings(TextureImporter importer) { importer.textureType = TextureImporterType.Default; importer.anisoLevel = 0; importer.mipmapEnabled = false; importer.linearTexture = true; importer.textureFormat = TextureImporterFormat.RGB24; importer.SaveAndReimport(); } private void DrawFields() { foreach (var group in m_GroupFields) { var enabledField = group.Value.FirstOrDefault(x => x.propertyPath == group.Key.Name + ".enabled"); var groupProperty = serializedObject.FindProperty(group.Key.Name); GUILayout.Space(5); bool display = EditorGUIHelper.Header(groupProperty, enabledField); if (!display) continue; GUILayout.BeginHorizontal(); { GUILayout.Space(10); GUILayout.BeginVertical(); { GUILayout.Space(3); foreach (var field in group.Value.Where(x => x.propertyPath != group.Key.Name + ".enabled")) { // Special case for the tonemapping curve field if (group.Key.FieldType == typeof(TonemappingColorGrading.TonemappingSettings) && field.propertyType == SerializedPropertyType.AnimationCurve && concreteTarget.tonemapping.tonemapper != TonemappingColorGrading.Tonemapper.Curve) continue; // Special case for the neutral tonemapper bool neutralParam = field.name.StartsWith("neutral"); if (group.Key.FieldType == typeof(TonemappingColorGrading.TonemappingSettings) && concreteTarget.tonemapping.tonemapper != TonemappingColorGrading.Tonemapper.Neutral && neutralParam) continue; if (neutralParam) EditorGUILayout.PropertyField(field, new GUIContent(ObjectNames.NicifyVariableName(field.name.Substring(7)))); else EditorGUILayout.PropertyField(field); } // Bake button if (group.Key.FieldType == typeof(TonemappingColorGrading.ColorGradingSettings)) { EditorGUI.BeginDisabledGroup(!enabledField.boolValue); if (GUILayout.Button("Export LUT as PNG", EditorStyles.miniButton)) { string path = EditorUtility.SaveFilePanelInProject("Export LUT as PNG", "LUT.png", "png", "Please enter a file name to save the LUT texture to"); if (!string.IsNullOrEmpty(path)) { Texture2D lut = concreteTarget.BakeLUT(); if (!concreteTarget.isGammaColorSpace) { var pixels = lut.GetPixels(); for (int i = 0; i < pixels.Length; i++) pixels[i] = pixels[i].linear; lut.SetPixels(pixels); lut.Apply(); } byte[] bytes = lut.EncodeToPNG(); System.IO.File.WriteAllBytes(path, bytes); DestroyImmediate(lut); AssetDatabase.Refresh(); TextureImporter importer = (TextureImporter)AssetImporter.GetAtPath(path); SetLUTImportSettings(importer); } } EditorGUI.EndDisabledGroup(); } } GUILayout.EndVertical(); } GUILayout.EndHorizontal(); } } public override void OnInspectorGUI() { if (s_Styles == null) s_Styles = new Styles(); serializedObject.Update(); GUILayout.Label("All following effects will use LDR color buffers.", EditorStyles.miniBoldLabel); if (concreteTarget.tonemapping.enabled) { Camera camera = concreteTarget.GetComponent<Camera>(); if (camera != null && !camera.allowHDR) EditorGUILayout.HelpBox("The camera is not HDR enabled. This will likely break the tonemapper.", MessageType.Warning); else if (!concreteTarget.validRenderTextureFormat) EditorGUILayout.HelpBox("The input to tonemapper is not in HDR. Make sure that all effects prior to this are executed in HDR.", MessageType.Warning); } if (concreteTarget.lut.enabled && concreteTarget.lut.texture != null) { if (!concreteTarget.validUserLutSize) { EditorGUILayout.HelpBox("Invalid LUT size. Should be \"height = sqrt(width)\" (e.g. 256x16).", MessageType.Error); } else { // Checks import settings on the lut, offers to fix them if invalid TextureImporter importer = (TextureImporter)AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(concreteTarget.lut.texture)); bool valid = importer.anisoLevel == 0 && importer.mipmapEnabled == false && importer.linearTexture == true && (importer.textureFormat == TextureImporterFormat.RGB24 || importer.textureFormat == TextureImporterFormat.AutomaticTruecolor); if (!valid) { EditorGUILayout.HelpBox("Invalid LUT import settings.", MessageType.Warning); GUILayout.Space(-32); EditorGUILayout.BeginHorizontal(); { GUILayout.FlexibleSpace(); if (GUILayout.Button("Fix", GUILayout.Width(60))) { SetLUTImportSettings(importer); AssetDatabase.Refresh(); } GUILayout.Space(8); } EditorGUILayout.EndHorizontal(); GUILayout.Space(11); } } } DrawFields(); serializedObject.ApplyModifiedProperties(); } private static readonly GUIContent k_HistogramTitle = new GUIContent("Histogram"); public override GUIContent GetPreviewTitle() { return k_HistogramTitle; } public override bool HasPreviewGUI() { return isHistogramSupported && targets.Length == 1 && concreteTarget != null && concreteTarget.enabled; } public override void OnPreviewGUI(Rect r, GUIStyle background) { serializedObject.Update(); if (Event.current.type == EventType.Repaint) { // If m_HistogramRect isn't set the preview was just opened so refresh the render to get the histogram data if (m_HistogramRect.width == 0 && m_HistogramRect.height == 0) InternalEditorUtility.RepaintAllViews(); // Sizing float width = Mathf.Min(512f, r.width); float height = Mathf.Min(128f, r.height); m_HistogramRect = new Rect( Mathf.Floor(r.x + r.width / 2f - width / 2f), Mathf.Floor(r.y + r.height / 2f - height / 2f), width, height ); if (m_HistogramTexture != null) GUI.DrawTexture(m_HistogramRect, m_HistogramTexture); } // Toolbar GUILayout.BeginHorizontal(); EditorGUI.BeginChangeCheck(); { concreteTarget.histogramRefreshOnPlay = GUILayout.Toggle(concreteTarget.histogramRefreshOnPlay, new GUIContent("Refresh on Play", "Keep refreshing the histogram in play mode; this may impact performances."), EditorStyles.miniButton); GUILayout.FlexibleSpace(); m_HistogramMode = (HistogramMode)EditorGUILayout.EnumPopup(m_HistogramMode); } GUILayout.EndHorizontal(); serializedObject.ApplyModifiedProperties(); if (EditorGUI.EndChangeCheck()) InternalEditorUtility.RepaintAllViews(); } private void OnFrameEnd(RenderTexture source) { if (Application.isPlaying && !concreteTarget.histogramRefreshOnPlay) return; if (Mathf.Approximately(m_HistogramRect.width, 0) || Mathf.Approximately(m_HistogramRect.height, 0) || !isHistogramSupported) return; // No need to process the full frame to get an histogram, resize the input to a max-size of 512 int rw = Mathf.Min(Mathf.Max(source.width, source.height), 512); RenderTexture rt = RenderTexture.GetTemporary(rw, rw, 0); Graphics.Blit(source, rt); UpdateHistogram(rt, m_HistogramRect, m_HistogramMode); Repaint(); RenderTexture.ReleaseTemporary(rt); RenderTexture.active = null; } private static readonly int[] k_EmptyBuffer = new int[256 << 2]; void UpdateHistogram(RenderTexture source, Rect rect, HistogramMode mode) { if (m_HistogramMaterial == null) m_HistogramMaterial = ImageEffectHelper.CheckShaderAndCreateMaterial(concreteTarget.histogramShader); if (m_HistogramBuffer == null) m_HistogramBuffer = new ComputeBuffer(256, sizeof(uint) << 2); m_HistogramBuffer.SetData(k_EmptyBuffer); ComputeShader cs = concreteTarget.histogramComputeShader; int kernel = cs.FindKernel("KHistogramGather"); cs.SetBuffer(kernel, "_Histogram", m_HistogramBuffer); cs.SetTexture(kernel, "_Source", source); int[] channels = null; switch (mode) { case HistogramMode.Luminance: channels = new[] { 0, 0, 0, 1 }; break; case HistogramMode.RGB: channels = new[] { 1, 1, 1, 0 }; break; case HistogramMode.Red: channels = new[] { 1, 0, 0, 0 }; break; case HistogramMode.Green: channels = new[] { 0, 1, 0, 0 }; break; case HistogramMode.Blue: channels = new[] { 0, 0, 1, 0 }; break; } cs.SetInts("_Channels", channels); cs.SetInt("_IsLinear", concreteTarget.isGammaColorSpace ? 0 : 1); cs.Dispatch(kernel, Mathf.CeilToInt(source.width / 32f), Mathf.CeilToInt(source.height / 32f), 1); kernel = cs.FindKernel("KHistogramScale"); cs.SetBuffer(kernel, "_Histogram", m_HistogramBuffer); cs.SetFloat("_Height", rect.height); cs.Dispatch(kernel, 1, 1, 1); if (m_HistogramTexture == null) { DestroyImmediate(m_HistogramTexture); m_HistogramTexture = new RenderTexture((int)rect.width, (int)rect.height, 0, RenderTextureFormat.ARGB32); m_HistogramTexture.hideFlags = HideFlags.HideAndDontSave; } m_HistogramMaterial.SetBuffer("_Histogram", m_HistogramBuffer); m_HistogramMaterial.SetVector("_Size", new Vector2(m_HistogramTexture.width, m_HistogramTexture.height)); m_HistogramMaterial.SetColor("_ColorR", redCurveColor); m_HistogramMaterial.SetColor("_ColorG", greenCurveColor); m_HistogramMaterial.SetColor("_ColorB", blueCurveColor); m_HistogramMaterial.SetColor("_ColorL", masterCurveColor); m_HistogramMaterial.SetInt("_Channel", (int)mode); Graphics.Blit(m_HistogramTexture, m_HistogramTexture, m_HistogramMaterial, (mode == HistogramMode.RGB) ? 1 : 0); } public static class ColorWheel { // Constants private const float PI_2 = Mathf.PI / 2f; private const float PI2 = Mathf.PI * 2f; // hue Wheel private static Texture2D s_WheelTexture; private static float s_LastDiameter; private static GUIStyle s_CenteredStyle; public static Color DoGUI(Rect area, string title, Color color, float diameter) { var labelrect = area; labelrect.height = EditorGUIUtility.singleLineHeight; if (s_CenteredStyle == null) { s_CenteredStyle = new GUIStyle(GUI.skin.GetStyle("Label")) { alignment = TextAnchor.UpperCenter }; } GUI.Label(labelrect, title, s_CenteredStyle); // Figure out the wheel draw area var wheelDrawArea = area; wheelDrawArea.y += EditorGUIUtility.singleLineHeight; wheelDrawArea.height = diameter; if (wheelDrawArea.width > wheelDrawArea.height) { wheelDrawArea.x += (wheelDrawArea.width - wheelDrawArea.height) / 2.0f; wheelDrawArea.width = area.height; } wheelDrawArea.width = wheelDrawArea.height; var radius = diameter / 2.0f; Vector3 hsv; Color.RGBToHSV(color, out hsv.x, out hsv.y, out hsv.z); // Retina/HDPI screens handling wheelDrawArea.width /= pixelRatio; wheelDrawArea.height /= pixelRatio; float scaledRadius = radius / pixelRatio; if (Event.current.type == EventType.Repaint) { if (!Mathf.Approximately(diameter, s_LastDiameter)) { s_LastDiameter = diameter; UpdateHueWheel((int)diameter); } // Wheel GUI.DrawTexture(wheelDrawArea, s_WheelTexture); // Thumb Vector2 thumbPos = Vector2.zero; float theta = hsv.x * PI2; float len = hsv.y * scaledRadius; thumbPos.x = Mathf.Cos(theta + PI_2); thumbPos.y = Mathf.Sin(theta - PI_2); thumbPos *= len; Vector2 thumbSize = s_Styles.thumb2DSize; Color oldColor = GUI.color; GUI.color = Color.black; Vector2 thumbSizeH = thumbSize / 2f; Handles.color = Color.white; Handles.DrawAAPolyLine(new Vector2(wheelDrawArea.x + scaledRadius + thumbSizeH.x, wheelDrawArea.y + scaledRadius + thumbSizeH.y), new Vector2(wheelDrawArea.x + scaledRadius + thumbPos.x, wheelDrawArea.y + scaledRadius + thumbPos.y)); s_Styles.thumb2D.Draw(new Rect(wheelDrawArea.x + scaledRadius + thumbPos.x - thumbSizeH.x, wheelDrawArea.y + scaledRadius + thumbPos.y - thumbSizeH.y, thumbSize.x, thumbSize.y), false, false, false, false); GUI.color = oldColor; } hsv = GetInput(wheelDrawArea, hsv, scaledRadius); var sliderDrawArea = wheelDrawArea; sliderDrawArea.y = sliderDrawArea.yMax; sliderDrawArea.height = EditorGUIUtility.singleLineHeight; hsv.y = GUI.HorizontalSlider(sliderDrawArea, hsv.y, 1e-04f, 1f); color = Color.HSVToRGB(hsv.x, hsv.y, hsv.z); return color; } private static readonly int k_ThumbHash = "colorWheelThumb".GetHashCode(); private static Vector3 GetInput(Rect bounds, Vector3 hsv, float radius) { Event e = Event.current; var id = GUIUtility.GetControlID(k_ThumbHash, FocusType.Passive, bounds); Vector2 mousePos = e.mousePosition; Vector2 relativePos = mousePos - new Vector2(bounds.x, bounds.y); if (e.type == EventType.MouseDown && e.button == 0 && GUIUtility.hotControl == 0) { if (bounds.Contains(mousePos)) { Vector2 center = new Vector2(bounds.x + radius, bounds.y + radius); float dist = Vector2.Distance(center, mousePos); if (dist <= radius) { e.Use(); GetWheelHueSaturation(relativePos.x, relativePos.y, radius, out hsv.x, out hsv.y); GUIUtility.hotControl = id; } } } else if (e.type == EventType.MouseDrag && e.button == 0 && GUIUtility.hotControl == id) { Vector2 center = new Vector2(bounds.x + radius, bounds.y + radius); float dist = Vector2.Distance(center, mousePos); if (dist <= radius) { e.Use(); GetWheelHueSaturation(relativePos.x, relativePos.y, radius, out hsv.x, out hsv.y); } } else if (e.type == EventType.MouseUp && e.button == 0 && GUIUtility.hotControl == id) { e.Use(); GUIUtility.hotControl = 0; } return hsv; } private static void GetWheelHueSaturation(float x, float y, float radius, out float hue, out float saturation) { float dx = (x - radius) / radius; float dy = (y - radius) / radius; float d = Mathf.Sqrt(dx * dx + dy * dy); hue = Mathf.Atan2(dx, -dy); hue = 1f - ((hue > 0) ? hue : PI2 + hue) / PI2; saturation = Mathf.Clamp01(d); } private static void UpdateHueWheel(int diameter) { CleanTexture(s_WheelTexture); s_WheelTexture = MakeTexture(diameter); var radius = diameter / 2.0f; Color[] pixels = s_WheelTexture.GetPixels(); for (int y = 0; y < diameter; y++) { for (int x = 0; x < diameter; x++) { int index = y * diameter + x; float dx = (x - radius) / radius; float dy = (y - radius) / radius; float d = Mathf.Sqrt(dx * dx + dy * dy); // Out of the wheel, early exit if (d >= 1f) { pixels[index] = new Color(0f, 0f, 0f, 0f); continue; } // red (0) on top, counter-clockwise (industry standard) float saturation = d; float hue = Mathf.Atan2(dx, dy); hue = 1f - ((hue > 0) ? hue : PI2 + hue) / PI2; Color color = Color.HSVToRGB(hue, saturation, 1f); // Quick & dirty antialiasing color.a = (saturation > 0.99) ? (1f - saturation) * 100f : 1f; pixels[index] = color; } } s_WheelTexture.SetPixels(pixels); s_WheelTexture.Apply(); } private static Texture2D MakeTexture(int dimension) { return new Texture2D(dimension, dimension, TextureFormat.ARGB32, false, true) { filterMode = FilterMode.Point, wrapMode = TextureWrapMode.Clamp, hideFlags = HideFlags.HideAndDontSave, alphaIsTransparency = true }; } private static void CleanTexture(Texture2D texture) { if (texture != null) DestroyImmediate(texture); } public static float GetColorWheelHeight(int renderSizePerWheel) { // wheel height + title label + alpha slider return renderSizePerWheel + 2 * EditorGUIUtility.singleLineHeight; } } } }
42.483039
253
0.530469
[ "MIT" ]
DanielOaks/PoniGame
PonyGame/Assets/Standard Assets/Effects/TonemappingColorGrading/Editor/TonemappingColorGradingEditor.cs
31,310
C#
namespace PhotoShare.Models { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using Validation; public class User { public User() { this.FriendsAdded = new HashSet<Friendship>(); this.AddedAsFriendBy = new HashSet<Friendship>(); this.AlbumRoles = new HashSet<AlbumRole>(); } public int Id { get; set; } public string Username { get; set; } [Password(6, 50, ContainsDigit = true, ContainsLowercase = true, ErrorMessage = "Invalid password")] public string Password { get; set; } [Email] public string Email { get; set; } public int? ProfilePictureId { get; set; } public Picture ProfilePicture { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string FullName => $"{this.FirstName} {this.LastName}"; public int? BornTownId { get; set; } public Town BornTown { get; set; } public int? CurrentTownId { get; set; } public Town CurrentTown { get; set; } public DateTime? RegisteredOn { get; set; } public DateTime? LastTimeLoggedIn { get; set; } [Age] public int? Age { get; set; } public bool? IsDeleted { get; set; } public ICollection<Friendship> FriendsAdded { get; set; } public ICollection<Friendship> AddedAsFriendBy { get; set; } public ICollection<AlbumRole> AlbumRoles { get; set; } public override string ToString() { return $"{this.Username} {this.Email} {this.Age} {this.FullName}"; } } }
27.365079
108
0.588747
[ "MIT" ]
ewgeni-dinew/04.Databases_Advanced-Entity_Framework
10.Best Practices and Arhitecture/PhotoShare/PhotoShare.Models/User.cs
1,726
C#
using System.Collections.Generic; using System.Threading.Tasks; using Bakana.Core.Entities; using Bakana.Core.Repositories; using Bakana.ServiceModels.Steps; using ServiceStack; namespace Bakana.ServiceInterface.Steps { public class StepArtifactService : Service { private readonly IBatchRepository batchRepository; private readonly IStepRepository stepRepository; public StepArtifactService( IBatchRepository batchRepository, IStepRepository stepRepository) { this.batchRepository = batchRepository; this.stepRepository = stepRepository; } public async Task<CreateStepArtifactResponse> Post(CreateStepArtifactRequest request) { if (!await batchRepository.DoesBatchExist(request.BatchId)) throw Err.BatchNotFound(request.BatchId); var step = await stepRepository.Get(request.BatchId, request.StepName); if (step == null) throw Err.StepNotFound(request.StepName); if (await stepRepository.DoesStepArtifactExist(request.BatchId, request.StepName, request.ArtifactName)) throw Err.StepArtifactAlreadyExists(request.ArtifactName); var stepArtifact = request.ConvertTo<StepArtifact>(); stepArtifact.StepId = step.Id; await stepRepository.CreateStepArtifact(stepArtifact); return new CreateStepArtifactResponse(); } public async Task<GetStepArtifactResponse> Get(GetStepArtifactRequest request) { if (!await batchRepository.DoesBatchExist(request.BatchId)) throw Err.BatchNotFound(request.BatchId); var step = await stepRepository.Get(request.BatchId, request.StepName); if (step == null) throw Err.StepNotFound(request.StepName); var stepArtifact = await stepRepository.GetStepArtifact(step.Id, request.ArtifactName); if (stepArtifact == null) throw Err.StepArtifactNotFound(request.ArtifactName); return stepArtifact.ConvertTo<GetStepArtifactResponse>(); } public async Task<GetAllStepArtifactResponse> Get(GetAllStepArtifactRequest request) { if (!await batchRepository.DoesBatchExist(request.BatchId)) throw Err.BatchNotFound(request.BatchId); var step = await stepRepository.Get(request.BatchId, request.StepName); if (step == null) throw Err.StepNotFound(request.StepName); var stepArtifacts = await stepRepository.GetAllStepArtifacts(step.Id); var response = new GetAllStepArtifactResponse { Artifacts = stepArtifacts.ConvertTo<List<DomainModels.StepArtifact>>() }; return response; } public async Task<UpdateStepArtifactResponse> Put(UpdateStepArtifactRequest request) { if (!await batchRepository.DoesBatchExist(request.BatchId)) throw Err.BatchNotFound(request.BatchId); var step = await stepRepository.Get(request.BatchId, request.StepName); if (step == null) throw Err.StepNotFound(request.StepName); var existingStepArtifact = await stepRepository.GetStepArtifact(step.Id, request.ArtifactName); if (existingStepArtifact == null) throw Err.StepArtifactNotFound(request.ArtifactName); var stepArtifact = request.ConvertTo<StepArtifact>(); stepArtifact.StepId = step.Id; stepArtifact.Id = existingStepArtifact.Id; await stepRepository.UpdateStepArtifact(stepArtifact); return new UpdateStepArtifactResponse(); } public async Task<DeleteStepArtifactResponse> Delete(DeleteStepArtifactRequest request) { if (!await batchRepository.DoesBatchExist(request.BatchId)) throw Err.BatchNotFound(request.BatchId); var step = await stepRepository.Get(request.BatchId, request.StepName); if (step == null) throw Err.StepNotFound(request.StepName); var existingStepArtifact = await stepRepository.GetStepArtifact(step.Id, request.ArtifactName); if (existingStepArtifact == null) throw Err.StepArtifactNotFound(request.ArtifactName); await stepRepository.DeleteStepArtifact(existingStepArtifact.Id); return new DeleteStepArtifactResponse(); } public async Task<CreateStepArtifactOptionResponse> Post(CreateStepArtifactOptionRequest request) { if (!await batchRepository.DoesBatchExist(request.BatchId)) throw Err.BatchNotFound(request.BatchId); var step = await stepRepository.Get(request.BatchId, request.StepName); if (step == null) throw Err.StepNotFound(request.StepName); var existingStepArtifact = await stepRepository.GetStepArtifact(step.Id, request.ArtifactName); if (existingStepArtifact == null) throw Err.StepArtifactNotFound(request.ArtifactName); if (await stepRepository.DoesStepArtifactOptionExist(request.BatchId, request.StepName, request.ArtifactName, request.OptionName)) throw Err.StepArtifactOptionAlreadyExists(request.OptionName); var stepArtifactOption = request.ConvertTo<StepArtifactOption>(); stepArtifactOption.StepArtifactId = existingStepArtifact.Id; await stepRepository.CreateOrUpdateStepArtifactOption(stepArtifactOption); return new CreateStepArtifactOptionResponse(); } public async Task<GetStepArtifactOptionResponse> Get(GetStepArtifactOptionRequest request) { if (!await batchRepository.DoesBatchExist(request.BatchId)) throw Err.BatchNotFound(request.BatchId); var step = await stepRepository.Get(request.BatchId, request.StepName); if (step == null) throw Err.StepNotFound(request.StepName); var existingStepArtifact = await stepRepository.GetStepArtifact(step.Id, request.ArtifactName); if (existingStepArtifact == null) throw Err.StepArtifactNotFound(request.ArtifactName); var stepArtifactOption = await stepRepository.GetStepArtifactOption(existingStepArtifact.Id, request.OptionName); if (stepArtifactOption == null) throw Err.StepArtifactOptionNotFound(request.OptionName); return stepArtifactOption.ConvertTo<GetStepArtifactOptionResponse>(); } public async Task<GetAllStepArtifactOptionResponse> Get(GetAllStepArtifactOptionRequest request) { if (!await batchRepository.DoesBatchExist(request.BatchId)) throw Err.BatchNotFound(request.BatchId); var step = await stepRepository.Get(request.BatchId, request.StepName); if (step == null) throw Err.StepNotFound(request.StepName); var existingStepArtifact = await stepRepository.GetStepArtifact(step.Id, request.ArtifactName); if (existingStepArtifact == null) throw Err.StepArtifactNotFound(request.ArtifactName); var response = new GetAllStepArtifactOptionResponse { Options = existingStepArtifact.Options.ConvertTo<List<DomainModels.Option>>() }; return response; } public async Task<UpdateStepArtifactOptionResponse> Put(UpdateStepArtifactOptionRequest request) { if (!await batchRepository.DoesBatchExist(request.BatchId)) throw Err.BatchNotFound(request.BatchId); var step = await stepRepository.Get(request.BatchId, request.StepName); if (step == null) throw Err.StepNotFound(request.StepName); var existingStepArtifact = await stepRepository.GetStepArtifact(step.Id, request.ArtifactName); if (existingStepArtifact == null) throw Err.StepArtifactNotFound(request.ArtifactName); var existingStepArtifactOption = await stepRepository.GetStepArtifactOption(existingStepArtifact.Id, request.OptionName); if (existingStepArtifactOption == null) throw Err.StepArtifactOptionNotFound(request.OptionName); var stepArtifactOption = request.ConvertTo<StepArtifactOption>(); stepArtifactOption.Id = existingStepArtifactOption.Id; stepArtifactOption.StepArtifactId = existingStepArtifact.Id; await stepRepository.CreateOrUpdateStepArtifactOption(stepArtifactOption); return new UpdateStepArtifactOptionResponse(); } public async Task<DeleteStepArtifactOptionResponse> Delete(DeleteStepArtifactOptionRequest request) { if (!await batchRepository.DoesBatchExist(request.BatchId)) throw Err.BatchNotFound(request.BatchId); var step = await stepRepository.Get(request.BatchId, request.StepName); if (step == null) throw Err.StepNotFound(request.StepName); var existingStepArtifact = await stepRepository.GetStepArtifact(step.Id, request.ArtifactName); if (existingStepArtifact == null) throw Err.StepArtifactNotFound(request.ArtifactName); var existingStepArtifactOption = await stepRepository.GetStepArtifactOption(existingStepArtifact.Id, request.OptionName); if (existingStepArtifactOption == null) throw Err.StepArtifactOptionNotFound(request.OptionName); await stepRepository.DeleteStepArtifactOption(existingStepArtifactOption.Id); return new DeleteStepArtifactOptionResponse(); } } }
42.696203
142
0.66133
[ "MIT" ]
BacanCI/Bacan
src/Bakana.ServiceInterface/Steps/StepArtifactService.cs
10,119
C#
namespace Medikit.Api.Patient.Application { public static class Constants { public static class QueueNames { public const string Patient = "patient"; } } }
18.636364
52
0.590244
[ "Apache-2.0" ]
ddonabedian/medikit
src/Medikit/Medikit.Api.Patient.Application/Constants.cs
207
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("Arson")] [assembly: AssemblyDescription("A Cities: Skylines mod")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Arson")] [assembly: AssemblyCopyright("Copyright © 2022 algernon")] [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("2ddddb9b-7bac-4cb7-b4ff-7e6878c92639")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.081081
84
0.747339
[ "MIT" ]
algernon-A/Arson
Properties/AssemblyInfo.cs
1,412
C#
using UnityEngine.SceneManagement; using UnityEngine; public class Editor_SceneChange : MonoBehaviour { public GameObject MenuUI; private bool Check; void Start() { MenuUI.SetActive(false); Check = false; } public void Menu() { MenuUI.SetActive(!Check); Check = !Check; } public void BackToMain() { SceneManager.LoadScene("Main"); } public void SetCheck(bool Check) { this.Check = Check; } }
16.7
47
0.590818
[ "BSD-3-Clause" ]
Eskeptor/Unity
ShootingGame2D/Assets/Script/GameEditor/Editor_SceneChange.cs
503
C#
using Microsoft.AspNetCore.Mvc.Rendering; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace Konveyor.Core.ViewModels { public class EmployeeEditViewModel : EmployeeBaseViewModel { [Display(Name = "Gender")] public List<SelectListItem> GenderOptions { get; set; } [DataType(DataType.Password)] [Required(ErrorMessage = "Choose a password for signing into your account."), MaxLength(50)] public string Password { get; set; } [Required(ErrorMessage = "Assign a user role to this employee.")] [Display(Name = "User Role")] public List<SelectListItem> RoleOptions { get; set; } } }
30.347826
100
0.686246
[ "MIT" ]
Philipeano/Konveyor
Konveyor.Core/ViewModels/EmployeeEditViewModel.cs
700
C#
using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace IdentityUtils.Commons { public class RestResult { public RestResult() { } public IEnumerable<string> ErrorMessages { get; set; } = Enumerable.Empty<string>(); public int StatusCode { get; set; } public bool Success => StatusCode == 200; } /// <summary> /// API result with payload /// </summary> /// <typeparam name="T"></typeparam> public class RestResult<T> : RestResult { public RestResult() : base() { } public RestResult(string rawData, T data) : base() { ResponseDataRaw = rawData; ResponseData = data; } public T ResponseData { get; set; } public string ResponseDataRaw { get; set; } } }
23.702703
92
0.574686
[ "MIT" ]
intellegens-hr/utils-identity
dotnetcore/IdentityUtils.Commons/RestResult.cs
879
C#
namespace Oasis.EntityFramework.Mapper.InternalLogic; using Oasis.EntityFramework.Mapper.Exceptions; internal sealed class ScalarTypeConverter : IScalarTypeConverter { private readonly IReadOnlyDictionary<Type, IReadOnlyDictionary<Type, Delegate>> _scalarConverterDictionary; public ScalarTypeConverter(Dictionary<Type, Dictionary<Type, Delegate>> scalarConverterDictionary) { var dictionary = new Dictionary<Type, IReadOnlyDictionary<Type, Delegate>>(); foreach (var pair in scalarConverterDictionary) { dictionary.Add(pair.Key, pair.Value); } _scalarConverterDictionary = dictionary; } public TTarget Convert<TSource, TTarget>(TSource source) { var sourceType = typeof(TSource); var targetType = typeof(TTarget); if (!_scalarConverterDictionary.TryGetValue(sourceType, out var innerDictionary) || !innerDictionary.TryGetValue(targetType, out var converter)) { throw new ScalarConverterMissingException(sourceType, targetType); } return ((Func<TSource, TTarget>)converter)(source); } public object? Convert(object? value, Type targetType) { if (value != default) { var sourceType = value.GetType(); if (sourceType != targetType) { if (!_scalarConverterDictionary.TryGetValue(sourceType, out var innerDictionary) || !innerDictionary.TryGetValue(targetType, out var converter)) { throw new ScalarConverterMissingException(sourceType, targetType); } return converter.DynamicInvoke(new[] { value }); } } return value; } }
33.576923
160
0.655785
[ "MIT" ]
keeper013/Oasis
EntityFramework/Oasis.EntityFramework.Mapper/InternalLogic/ScalarTypeConverter.cs
1,748
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.Runtime.CompilerServices; static class ModConst { // I4 [MethodImpl(MethodImplOptions.NoInlining)] public static int I4_Mod_0(int i4) { return i4 % 0; } [MethodImpl(MethodImplOptions.NoInlining)] public static int I4_Mod_1(int i4) { return i4 % 1; } [MethodImpl(MethodImplOptions.NoInlining)] public static int I4_Mod_Minus1(int i4) { return i4 % -1; } [MethodImpl(MethodImplOptions.NoInlining)] public static int I4_Mod_3(int i4) { return i4 % 3; } [MethodImpl(MethodImplOptions.NoInlining)] public static int I4_ModRef_5(ref int i4) { return i4 % 5; } [MethodImpl(MethodImplOptions.NoInlining)] public static int I4_Mod_7(int i4) { return i4 % 7; } [MethodImpl(MethodImplOptions.NoInlining)] public static int I4_Mod_Minus3(int i4) { return i4 % -3; } [MethodImpl(MethodImplOptions.NoInlining)] public static int I4_ModPow2_2(int i4) { return i4 % 2; } [MethodImpl(MethodImplOptions.NoInlining)] public static int I4_ModPow2_Minus2(int i4) { return i4 % -2; } [MethodImpl(MethodImplOptions.NoInlining)] public static int I4_ModPow2_8(ref int i4) { return i4 % 8; } [MethodImpl(MethodImplOptions.NoInlining)] public static int I4_ModPow2_Minus4(int i4) { return i4 % -4; } [MethodImpl(MethodImplOptions.NoInlining)] public static int I4_ModPow2_I4Min(ref int i4) { return i4 % int.MinValue; } [MethodImpl(MethodImplOptions.NoInlining)] public static int I4_ModPow2Embedded_4(int x, int y) { return y * 2 + (x + 2) % 4 + (x * y >> 31); } [MethodImpl(MethodImplOptions.NoInlining)] public static int I4_ModPow2Call_8(int i4) { return I4_ModPow2_2(i4 % 8) + I4_ModRef_5(ref i4) % 8; } // I8 [MethodImpl(MethodImplOptions.NoInlining)] public static long I8_Mod_0(long i8) { return i8 % 0; } [MethodImpl(MethodImplOptions.NoInlining)] public static long I8_Mod_1(long i8) { return i8 % 1; } [MethodImpl(MethodImplOptions.NoInlining)] public static long I8_Mod_Minus1(long i8) { return i8 % -1; } [MethodImpl(MethodImplOptions.NoInlining)] public static long I8_Mod_3(long i8) { return i8 % 3; } [MethodImpl(MethodImplOptions.NoInlining)] public static long I8_Mod_5(long i8) { return i8 % 5; } [MethodImpl(MethodImplOptions.NoInlining)] public static long I8_Mod_7(long i8) { return i8 % 7; } [MethodImpl(MethodImplOptions.NoInlining)] public static long I8_Mod_Minus3(long i8) { return i8 % -3; } [MethodImpl(MethodImplOptions.NoInlining)] public static long I8_ModPow2_4(long i8) { return i8 % 4; } [MethodImpl(MethodImplOptions.NoInlining)] public static long I8_ModPow2_Minus8(long i8) { return i8 % -8; } [MethodImpl(MethodImplOptions.NoInlining)] public static long I8_ModUncontainedPow2_1Shl32(long i8) { return i8 % (1L << 32); } [MethodImpl(MethodImplOptions.NoInlining)] public static long I8_ModUncontainedPow2_I8Min(long i8) { return i8 % long.MinValue; } [MethodImpl(MethodImplOptions.NoInlining)] public static long I8_ModPow2Embedded_4(long x, long y) { return y * 2 + (x + 2) % 4 + (x * y >> 31); } [MethodImpl(MethodImplOptions.NoInlining)] public static long I8_ModPow2Call_8(long i8) { return I8_ModPow2_4(i8 % 8) + I8_Mod_5(i8) % 8; } } static class ModProgram { public static int Main() { const int Pass = 100; const int Fail = -1; // I4 try { ModConst.I4_Mod_0(42); return Fail; } catch (DivideByZeroException) { } catch (Exception) { return Fail; } if (ModConst.I4_Mod_1(42) != 0) { return Fail; } if (ModConst.I4_Mod_1(1) != 0) { return Fail; } if (ModConst.I4_Mod_Minus1(42) != 0) { return Fail; } try { ModConst.I4_Mod_Minus1(int.MinValue); return Fail; } catch (OverflowException) { } catch (Exception) { return Fail; } if (ModConst.I4_Mod_3(41) != 2) { return Fail; } { int dividend = 42; if (ModConst.I4_ModRef_5(ref dividend) != 2) { return Fail; } } if (ModConst.I4_Mod_7(42) != 0) { return Fail; } if (ModConst.I4_Mod_Minus3(41) != 2) { return Fail; } if (ModConst.I4_ModPow2_2(43) != 1) { return Fail; } if (ModConst.I4_ModPow2_2(42) != 0) { return Fail; } if (ModConst.I4_ModPow2_2(-43) != -1) { return Fail; } if (ModConst.I4_ModPow2_2(-42) != 0) { return Fail; } if (ModConst.I4_ModPow2_Minus2(43) != 1) { return Fail; } { int dividend = 42; if (ModConst.I4_ModPow2_8(ref dividend) != 2) { return Fail; } } { int dividend = -42; if (ModConst.I4_ModPow2_8(ref dividend) != -2) { return Fail; } } if (ModConst.I4_ModPow2_Minus4(42) != 2) { return Fail; } if (ModConst.I4_ModPow2_Minus4(-42) != -2) { return Fail; } { int dividend = -42; if (ModConst.I4_ModPow2_I4Min(ref dividend) != -42) { return Fail; } } { int dividend = int.MinValue; if (ModConst.I4_ModPow2_I4Min(ref dividend) != 0) { return Fail; } } if (ModConst.I4_ModPow2Embedded_4(420, 938) != 1878) { return Fail; } if (ModConst.I4_ModPow2Call_8(3674) != 4) { return Fail; } // I8 try { ModConst.I8_Mod_0(42); return Fail; } catch (DivideByZeroException) { } catch (Exception) { return Pass; } if (ModConst.I8_Mod_1(42) != 0) { return Fail; } if (ModConst.I8_Mod_Minus1(42) != 0) { return Fail; } try { ModConst.I8_Mod_Minus1(long.MinValue); return Fail; } catch (OverflowException) { } catch (Exception) { return Fail; } if (ModConst.I8_Mod_3(43) != 1) { return Fail; } if (ModConst.I8_Mod_5(42) != 2) { return Fail; } if (ModConst.I8_Mod_7(45) != 3) { return Fail; } if (ModConst.I8_Mod_Minus3(-43) != -1) { return Fail; } if (ModConst.I8_ModPow2_4(42) != 2) { return Fail; } if (ModConst.I8_ModPow2_Minus8(42) != 2) { return Fail; } if (ModConst.I8_ModPow2_Minus8(-42) != -2) { return Fail; } if (ModConst.I8_ModUncontainedPow2_1Shl32((1L << 33) + 42L) != 42) { return Fail; } if (ModConst.I8_ModUncontainedPow2_I8Min(42) != 42) { return Fail; } if (ModConst.I8_ModUncontainedPow2_I8Min(long.MinValue) != 0) { return Fail; } if (ModConst.I8_ModPow2Embedded_4(420, 938) != 1878) { return Fail; } if (ModConst.I8_ModPow2Call_8(3674) != 6) { return Fail; } return Pass; } }
19.886574
74
0.499942
[ "MIT" ]
2m0nd/runtime
src/tests/JIT/CodeGenBringUpTests/ModConst.cs
8,591
C#
using Ardalis.ListStartupServices; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc.ApplicationModels; using Microsoft.EntityFrameworkCore; using Microsoft.eShopWeb.ApplicationCore.Interfaces; using Microsoft.eShopWeb.Infrastructure.Data; using Microsoft.eShopWeb.Infrastructure.Identity; using Microsoft.eShopWeb.Web.Configuration; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Hosting; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Mime; namespace Microsoft.eShopWeb.Web { public class Startup { private IServiceCollection _services; public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureDevelopmentServices(IServiceCollection services) { // use in-memory database //ConfigureInMemoryDatabases(services); // use real database ConfigureProductionServices(services); } public void ConfigureDockerServices(IServiceCollection services) { services.AddDataProtection() .SetApplicationName("eshopwebmvc") .PersistKeysToFileSystem(new DirectoryInfo(@"./")); ConfigureDevelopmentServices(services); } private void ConfigureInMemoryDatabases(IServiceCollection services) { // use in-memory database services.AddDbContext<CatalogContext>(c => c.UseInMemoryDatabase("Catalog")); // Add Identity DbContext services.AddDbContext<AppIdentityDbContext>(options => options.UseInMemoryDatabase("Identity")); ConfigureServices(services); } public void ConfigureProductionServices(IServiceCollection services) { // use real database // Requires LocalDB which can be installed with SQL Server Express 2016 // https://www.microsoft.com/en-us/download/details.aspx?id=54284 services.AddDbContext<CatalogContext>(c => c.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); // Add Identity DbContext services.AddDbContext<AppIdentityDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); ConfigureServices(services); } public void ConfigureTestingServices(IServiceCollection services) { ConfigureInMemoryDatabases(services); } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddCookieSettings(); services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.Cookie.HttpOnly = true; options.Cookie.SecurePolicy = CookieSecurePolicy.Always; options.Cookie.SameSite = SameSiteMode.Lax; }); services.AddIdentity<ApplicationUser, IdentityRole>() .AddDefaultUI() .AddEntityFrameworkStores<AppIdentityDbContext>() .AddDefaultTokenProviders(); services.AddScoped<ITokenClaimsService, IdentityTokenClaimService>(); services.AddCoreServices(Configuration); services.AddWebServices(Configuration); // Add memory cache services services.AddMemoryCache(); services.AddRouting(options => { // Replace the type and the name used to refer to it with your own // IOutboundParameterTransformer implementation options.ConstraintMap["slugify"] = typeof(SlugifyParameterTransformer); }); services.AddMvc(options => { options.Conventions.Add(new RouteTokenTransformerConvention( new SlugifyParameterTransformer())); }); services.AddControllersWithViews(); services.AddRazorPages(options => { options.Conventions.AuthorizePage("/Basket/Checkout"); }); services.AddHttpContextAccessor(); services.AddHealthChecks(); services.Configure<ServiceConfig>(config => { config.Services = new List<ServiceDescriptor>(services); config.Path = "/allservices"; }); services.AddDatabaseDeveloperPageExceptionFilter(); _services = services; // used to debug registered services } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { var catalogBaseUrl = Configuration.GetValue(typeof(string), "CatalogBaseUrl") as string; if (!string.IsNullOrEmpty(catalogBaseUrl)) { app.Use((context, next) => { context.Request.PathBase = new PathString(catalogBaseUrl); return next(); }); } app.UseHealthChecks("/health", new HealthCheckOptions { ResponseWriter = async (context, report) => { var result = new { status = report.Status.ToString(), errors = report.Entries.Select(e => new { key = e.Key, value = Enum.GetName(typeof(HealthStatus), e.Value.Status) }) }.ToJson(); context.Response.ContentType = MediaTypeNames.Application.Json; await context.Response.WriteAsync(result); } }); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseShowAllServicesMiddleware(); app.UseMigrationsEndPoint(); app.UseWebAssemblyDebugging(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseCookiePolicy(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute("default", "{controller:slugify=Home}/{action:slugify=Index}/{id?}"); endpoints.MapRazorPages(); endpoints.MapHealthChecks("home_page_health_check"); endpoints.MapHealthChecks("api_health_check"); endpoints.MapFallbackToFile("index.html"); }); } } }
36.887324
143
0.590683
[ "MIT" ]
minhdo501/eShopWeb
src/Web/Startup.cs
7,859
C#
using DevPodcasts.DataLayer.Models; using DevPodcasts.ViewModels.Podcast; using System.Collections.Generic; using System.Linq; using DevPodcasts.ViewModels.Tags; namespace DevPodcasts.ServiceLayer.Tag { public class TagService { private readonly ApplicationDbContext _context; public TagService() { _context = new ApplicationDbContext(); } public IEnumerable<TagItemViewModel> GetTags() { return _context .Tags .OrderBy(i => i.Name) .Select(i => new TagItemViewModel { Name = i.Name, Slug = i.Slug, NumberOfPodcasts = i.Podcasts.Count }); } public TagResultViewModel GetTaggedPodcasts(string tagSlug) { var tagName = _context .Tags .Where(t => t.Slug == tagSlug) .Select(i => i.Name) .FirstOrDefault(); var podcasts = _context .Podcasts .Where(p => p.Tags.Any(t => t.Slug == tagSlug)) .OrderBy(p => p.Title) .Select(i => new PodcastSearchResultViewModel { Id = i.Id, Title = i.Title, ImageUrl = i.ResizedImageUrl ?? i.ImageUrl, Description = i.Description, NumberOfEpisodes = i.Episodes.Count, Tags = i.Tags .OrderBy(tag => tag.Name) .Select(tag => new TagViewModel { Name = tag.Name, Slug = tag.Slug }) }); return new TagResultViewModel { TagName = tagName, SearchResults = podcasts }; } } public class TagItemViewModel { public string Name { get; set; } public string Slug { get; set; } public int NumberOfPodcasts { get; set; } } }
28.625
89
0.481805
[ "MIT" ]
NRKirby/DevPodcasts
src/DevPodcasts.ServiceLayer/Tag/TagService.cs
2,063
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using VisualStudioDiscordRPC.Shared.Localization; using VisualStudioDiscordRPC.Shared.Localization.Models; using VisualStudioDiscordRPC.Shared.Services.Interfaces; using VisualStudioDiscordRPC.Shared.Services.Models; namespace VisualStudioDiscordRPC.Shared.ViewModels { public class SettingsViewModel : ViewModelBase { private RichPresenceWrapper _wrapper; public RichPresenceWrapper Wrapper { get => _wrapper; set => SetProperty(ref _wrapper, value, nameof(Wrapper)); } private ILocalizationService<LocalizationFile> _localizationManager; public ILocalizationService<LocalizationFile> LocalizationManager { get => _localizationManager; set => SetProperty(ref _localizationManager, value, nameof(LocalizationManager)); } public LocalizationFile SelectedLocalization { get => _localizationManager?.Current; set { _localizationManager?.SelectLanguage(value.LanguageName); Settings.Default.Language = value.LanguageName; IconEnum = new ObservableCollection<RichPresenceWrapper.Icon>(_iconEnum); TextEnum = new ObservableCollection<RichPresenceWrapper.Text>(_textEnum); WorkTimerModeEnum = new ObservableCollection<RichPresenceWrapper.TimerMode>(_workTimerModeEnum); } } private ObservableCollection<RichPresenceWrapper.Icon> _iconEnum; public ObservableCollection<RichPresenceWrapper.Icon> IconEnum { get => _iconEnum; set => SetProperty(ref _iconEnum, value, nameof(IconEnum)); } private ObservableCollection<RichPresenceWrapper.Text> _textEnum; public ObservableCollection<RichPresenceWrapper.Text> TextEnum { get => _textEnum; set => SetProperty(ref _textEnum, value, nameof(TextEnum)); } private ObservableCollection<RichPresenceWrapper.TimerMode> _workTimerModeEnum; public ObservableCollection<RichPresenceWrapper.TimerMode> WorkTimerModeEnum { get => _workTimerModeEnum; set => SetProperty(ref _workTimerModeEnum, value, nameof(WorkTimerModeEnum)); } public RichPresenceWrapper.Icon SelectedLargeIcon { get => _wrapper.LargeIcon; set { _wrapper.LargeIcon = value; Settings.Default.LargeIcon = SettingsHelper.Instance.IconEnumMap.GetString(value); } } public RichPresenceWrapper.Icon SelectedSmallIcon { get => _wrapper.SmallIcon; set { _wrapper.SmallIcon = value; Settings.Default.SmallIcon = SettingsHelper.Instance.IconEnumMap.GetString(value); } } public RichPresenceWrapper.Text SelectedTitleText { get => _wrapper.TitleText; set { _wrapper.TitleText = value; Settings.Default.TitleText = SettingsHelper.Instance.TextEnumMap.GetString(value); } } public RichPresenceWrapper.Text SelectedSubTitleText { get => _wrapper.SubTitleText; set { _wrapper.SubTitleText = value; Settings.Default.SubTitleText = SettingsHelper.Instance.TextEnumMap.GetString(value); } } public RichPresenceWrapper.TimerMode SelectedWorkTimerMode { get => _wrapper.WorkTimerMode; set { _wrapper.WorkTimerMode = value; Settings.Default.WorkTimerMode = SettingsHelper.Instance.TimerModeEnumMap.GetString(value); } } private ObservableCollection<T> ToObservableCollection<T>() where T : Enum { return new ObservableCollection<T>( Enum.GetValues(typeof(T)) as IEnumerable<T>); } public SettingsViewModel() { LocalizationManager = ServiceRepository.Default.GetService<LocalizationService<LocalizationFile>>(); IconEnum = ToObservableCollection<RichPresenceWrapper.Icon>(); TextEnum = ToObservableCollection<RichPresenceWrapper.Text>(); WorkTimerModeEnum = ToObservableCollection<RichPresenceWrapper.TimerMode>(); } } }
35.292308
112
0.631648
[ "MIT" ]
Ryavell/VisualStudioDiscordRPC
VisualStudioDiscordRPC.Shared/ViewModels/SettingsViewModel.cs
4,590
C#
namespace ClassLib026 { public class Class097 { public static string Property => "ClassLib026"; } }
15
55
0.633333
[ "MIT" ]
333fred/performance
src/scenarios/weblarge2.0/src/ClassLib026/Class097.cs
120
C#
using System; using Xamarin.Forms; namespace PlatformSpecifics { public partial class WindowsNavigationPage : NavigationPage { public WindowsNavigationPage() { InitializeComponent(); PushAsync(new ContentPageOneInNavigationPage()); } async void OnToolbarItemClicked(object sender, EventArgs e) { await DisplayAlert(WindowsPlatformSpecificsHelpers.Title, WindowsPlatformSpecificsHelpers.Message, WindowsPlatformSpecificsHelpers.Dismiss); } } }
27.1
152
0.691882
[ "Apache-2.0" ]
JhonP54/xamarin-forms-samples
UserInterface/PlatformSpecifics/PlatformSpecifics/UWP/XAML/NavigationPage/WindowsNavigationPage.xaml.cs
544
C#
using IdentityServer4; using IdentityServer4.Models; using IdentityServer4.Test; using System; using System.Collections.Generic; using System.Security.Claims; namespace IdentityServer.AuthServer { /// <summary> /// Identity server ayarları /// </summary> public static class Config { /// <summary> /// Api'leri tanıtıyorum /// </summary> /// <returns>List of api resource</returns> public static IEnumerable<ApiResource> GetApiResources() { List<ApiResource> apiResources = new() { new ApiResource { Name = "IdentityServer.API1", Scopes = //Identity Servera API1'in nelere yetkisi olduğunu belirtiyorum { "IdentityServer.API1.Read", "IdentityServer.API1.Create", "IdentityServer.API1.Update" }, ApiSecrets = new List<Secret> // connect/introspect basic Auth { new Secret { Value = "SecretAPI1".Sha256() } } }, new ApiResource { Name = "IdentityServer.API2", Scopes = //Identity Servera API2'in nelere yetkisi olduğunu belirtiyorum { "IdentityServer.API2.Read", "IdentityServer.API2.Create", "IdentityServer.API2.Update" }, ApiSecrets = new List<Secret> // connect/introspect basic Auth { new Secret { Value = "SecretAPI2".Sha256() } } } }; return apiResources; } /// <summary> /// Api Yetkileri /// </summary> /// <returns>List of api scope</returns> public static IEnumerable<ApiScope> GetApiScopes() { List<ApiScope> apiScopes = new() { new ApiScope { Name = "IdentityServer.API1.Read", DisplayName = "API 1 - Okuma İzni" }, new ApiScope { Name = "IdentityServer.API1.Create", DisplayName = "API 1 - Yazma İzni" }, new ApiScope { Name = "IdentityServer.API1.Update", DisplayName = "API 1 - Güncelleme İzni" }, new ApiScope { Name = "IdentityServer.API2.Read", DisplayName = "API 2 - Okuma İzni" }, new ApiScope { Name = "IdentityServer.API2.Create", DisplayName = "API 2 - Yazma İzni" }, new ApiScope { Name = "IdentityServer.API2.Update", DisplayName = "API 2 - Güncelleme İzni" }, }; return apiScopes; } /// <summary> /// Apileri hangi clientlar kullanacak? /// </summary> /// <returns>List of clients</returns> public static IEnumerable<Client> GetClients() { List<Client> clients = new() { new Client() { ClientName = "API - Sample Client 1", ClientId = "SampleClient1", ClientSecrets = new List<Secret> { new Secret("SampleClientSecret".Sha256()) }, AllowedGrantTypes = GrantTypes.ClientCredentials, //Kullanıcıyla ilgili işlemim yok, sadece client istek yaptıgı zaman akışa uygun token ver. AllowedScopes = new List<string> //Client1 hangi apilere ne izni var? { "IdentityServer.API1.Read" //Api1'de okuma izni } }, new Client() { ClientName = "API - Sample Client 2", ClientId = "SampleClient2", ClientSecrets = new List<Secret> { new Secret("SampleClientSecret".Sha256()) }, AllowedGrantTypes = GrantTypes.ClientCredentials, //Kullanıcıyla ilgili işlemim yok, sadece client istek yaptıgı zaman akışa uygun token ver. AllowedScopes = new List<string> //Client1 hangi apilere ne izni var? { "IdentityServer.API1.Read", //Api1'de okuma izni "IdentityServer.API2.Create", //Api2'de yazma izmi "IdentityServer.API2.Update", //Api2'de güncelleme izni } }, new Client() { ClientName = "Web - Sample Client 3", ClientId = "SampleClient3", ClientSecrets = new List<Secret> { new Secret("SampleClientSecret".Sha256()) }, AllowedGrantTypes = GrantTypes.Hybrid, //Serverdan response olarak hem token hemde id_token istediğimden dolayı akış hybrid olacaktır. RedirectUris = new List<string> //token alımını gerçekleştiren url ve bu urldende herhangi bir sayfaya yönlendirme işlemi gerçekleştirilecek. { "https://localhost:5001/signin-oidc" }, PostLogoutRedirectUris = new List<string> //Uygulamadan çıkış yaptıldığında { "https://localhost:5001/signout-callback-oidc" }, AllowedScopes = new List<string> //Bu web uygulaması hangi izinlere sahip olacak? { IdentityServerConstants.StandardScopes.OpenId, //OpenId bilgisine erişeyeceğim IdentityServerConstants.StandardScopes.Profile, //Kullanıcı bilgilerine erişeceğim IdentityServerConstants.StandardScopes.OfflineAccess, //Refresh token IdentityServerConstants.StandardScopes.Email, //Kullanıcı email bilgisi "IdentityServer.API1.Read", //Api1 için okuma izni "CountryAndCityCustomResource", //Custom claims "RolesCustomResource" }, RequirePkce = false, AccessTokenLifetime = 2 * 60 * 30, //Access token ömrünü 2 saat ayarladım AllowOfflineAccess = true, //Refresh token yayınlanması için AbsoluteRefreshTokenLifetime = (int)(DateTime.Now.AddDays(50) - DateTime.Now).TotalSeconds, //Refresh token ömrünü 50 gün ayarladım RefreshTokenUsage = TokenUsage.ReUse, //OneTimeOnly: Bu refresh token'ı bir kere kullanbilirsin. || ReUse: Tekrar tekrar kullanabilirsin. RequireConsent = true //login'de onay ekranı çıkmayacak. }, new Client() { ClientName = "Web - Sample Client 4", ClientId = "SampleClient4", ClientSecrets = new List<Secret> { new Secret("SampleClientSecret".Sha256()) }, AllowedGrantTypes = GrantTypes.Hybrid, //Serverdan response olarak hem token hemde id_token istediğimden dolayı akış hybrid olacaktır. RedirectUris = new List<string> //token alımını gerçekleştiren url ve bu urldende herhangi bir sayfaya yönlendirme işlemi gerçekleştirilecek. { "https://localhost:5002/signin-oidc" }, PostLogoutRedirectUris = new List<string> //Uygulamadan çıkış yaptıldığında { "https://localhost:5002/signout-callback-oidc" }, AllowedScopes = new List<string> //Bu web uygulaması hangi izinlere sahip olacak? { IdentityServerConstants.StandardScopes.OpenId, //OpenId bilgisine erişeyeceğim IdentityServerConstants.StandardScopes.Profile, //Kullanıcı bilgilerine erişeceğim IdentityServerConstants.StandardScopes.OfflineAccess, //Refresh token "IdentityServer.API1.Read", //Api1 için okuma izni "CountryAndCityCustomResource", //Custom claims "RolesCustomResource" }, RequirePkce = false, AccessTokenLifetime = 2 * 60 * 30, //Access token ömrünü 2 saat ayarladım AllowOfflineAccess = true, //Refresh token yayınlanması için AbsoluteRefreshTokenLifetime = (int)(DateTime.Now.AddDays(50) - DateTime.Now).TotalSeconds, //Refresh token ömrünü 50 gün ayarladım RefreshTokenUsage = TokenUsage.ReUse, //OneTimeOnly: Bu refresh token'ı bir kere kullanbilirsin. || ReUse: Tekrar tekrar kullanabilirsin. RequireConsent = false //login'de onay ekranı çıkmayacak. }, new Client() { ClientName = "Angular Identity Server", ClientId = "angular-js-client", RequireClientSecret = false, //Js uygulamalarında secret tutmak güvensiz olduğu için client-secret devre dışı bırakıyoruz. AllowedGrantTypes = GrantTypes.Code, AllowedScopes = new List<string> { IdentityServerConstants.StandardScopes.OpenId, //Kullanıcının id'sine erişeyeceğim (zorunlu) IdentityServerConstants.StandardScopes.Profile, //Kullanıcı bilgilerine erişeceğim (given_name, family name) IdentityServerConstants.StandardScopes.OfflineAccess, //Refresh token IdentityServerConstants.StandardScopes.Email, //Kullanıcı email bilgisi "IdentityServer.API1.Read", //Api1 için okuma izni "CountryAndCityCustomResource", //Custom claims "RolesCustomResource" }, RedirectUris = new List<string> { "http://localhost:4200/callback" //kullanıcı bilgilerini girdikten sonra bu sayfaya yönlenecek }, PostLogoutRedirectUris = new List<string> //Uygulamadan çıkış yaptıldığında { "http://localhost:4200" }, AllowedCorsOrigins = new List<string> { "http://localhost:4200" } }, new Client() { ClientName = "Web - Sample Client 5 - ResourceOwner", ClientId = "SampleClient5", ClientSecrets = new List<Secret> { new Secret("SampleClientSecret".Sha256()) }, AllowedGrantTypes = GrantTypes.ResourceOwnerPassword, AllowedScopes = new List<string> //Bu web uygulaması hangi izinlere sahip olacak? { IdentityServerConstants.StandardScopes.OpenId, //OpenId bilgisine erişeyeceğim IdentityServerConstants.StandardScopes.Profile, //Kullanıcı bilgilerine erişeceğim IdentityServerConstants.StandardScopes.OfflineAccess, //Refresh token IdentityServerConstants.StandardScopes.Email, //Kullanıcı email bilgisi "IdentityServer.API1.Read", //Api1 için okuma izni "CountryAndCityCustomResource", //Custom claims "RolesCustomResource" }, RequirePkce = false, AccessTokenLifetime = 2 * 60 * 30, //Access token ömrünü 2 saat ayarladım AllowOfflineAccess = true, //Refresh token yayınlanması için AbsoluteRefreshTokenLifetime = (int)(DateTime.Now.AddDays(50) - DateTime.Now).TotalSeconds, //Refresh token ömrünü 50 gün ayarladım RefreshTokenUsage = TokenUsage.ReUse, //OneTimeOnly: Bu refresh token'ı bir kere kullanbilirsin. || ReUse: Tekrar tekrar kullanabilirsin. }, }; return clients; } public static IEnumerable<IdentityResource> GetIdentityResources() { List<IdentityResource> identityResources = new() { new IdentityResources.OpenId(), //SubId new IdentityResources.Profile(), //Kullanıcı ile ilgili claimler new IdentityResource() { Name = "CountryAndCityCustomResource", DisplayName = "Ülke ve Şehir Bilgisi", Description = "Kullanıcının ülke ve şehir bilgisi.", UserClaims = new List<string> { "Country", "City" } }, new IdentityResource { Name = "RolesCustomResource", DisplayName = "Roller", Description = "Kullanıcıya ait rol bilgisi", UserClaims = new List<string> { "Role" } }, new IdentityResources.Email() //Client tarafından email alabilmek }; return identityResources; } /// <summary> /// Kullanıcı dataları /// TestUser -> namespace IdentityServer4.Test /// </summary> public static List<TestUser> GetTestUsers() { List<TestUser> testUsers = new() { new TestUser { SubjectId = "1", //Kullanıcı id'si Username = "cihatsolak", //İhtiyaca göre username'i e-posta olarak kullanabiliriz. Password = "123456", Claims = new List<Claim> //Claim: Token içerisinde bulunacak datalar. { new Claim("given_name", "Cihat"), new Claim("family_name", "Solak"), new Claim("Country", "Türkiye"), new Claim("City","İstanbul"), new Claim("Role","Admin") } }, new TestUser { SubjectId = "2", //Kullanıcı id'si Username = "mesutsolak", //İhtiyaca göre username'i e-posta olarak kullanabiliriz. Password = "123456", Claims = new List<Claim> //Claim: Token içerisinde bulunacak datalar. { new Claim("given_name", "Mesut"), new Claim("family_name","Solak"), new Claim("Country", "Türkiye"), new Claim("City","Ankara"), new Claim("Role","Customer") } } }; return testUsers; } } }
46.547826
161
0.486954
[ "MIT" ]
cihatsolak/netcore-identityserver4
NetCoreIdentityServer/IdentityServer.AuthServer/Config.cs
16,266
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Database_Layer.Exceptions { public class SQLInjectionException : Exception { public SQLInjectionException(string ex) : base(ex) {} } }
20.214286
61
0.742049
[ "MIT" ]
chaoskie/Ict4Participation
Ict4Participation/Database_Layer/Exceptions/SQLInjectionException.cs
285
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization; namespace SageFrame.Scheduler { [DataContract] [Serializable] public class ScheduleHistory :Schedule { [DataMember(Name = "_RowTotal", Order = 1)] private System.Nullable<int> _RowTotal; [DataMember(Name = "_ScheduleHistoryID", Order = 2)] public int? ScheduleHistoryID { get; set; } [DataMember(Name = "_HistoryStartDate", Order = 3)] public DateTime? HistoryStartDate { get; set; } [DataMember(Name = "_HistoryEndDate", Order = 4)] public DateTime? HistoryEndDate { get; set; } [DataMember(Name = "_Status", Order = 5)] public bool? Status{ get; set; } [DataMember(Name = "_ReturnText", Order = 6)] public String ReturnText{ get; set; } [DataMember(Name = "_RowTotal", Order = 7)] public string Server { get; set; } public ScheduleHistory() { } public ScheduleHistory(Schedule objSchedule) { this.AttachToEvent = objSchedule.AttachToEvent; this.CatchUpEnabled = objSchedule.CatchUpEnabled; this.EveryMin = objSchedule.EveryMin; this.EveryHours = objSchedule.EveryHours; this.RunningMode = objSchedule.RunningMode; this.NextStart = objSchedule.NextStart; this.ObjectDependencies = objSchedule.ObjectDependencies; this.ProcessGroup = objSchedule.ProcessGroup; //this.RetainHistoryNum = objSchedule.RetainHistoryNum; this.RetryTimeLapse = objSchedule.RetryTimeLapse; this.RetryFrequencyUnit = objSchedule.RetryFrequencyUnit; this.ScheduleID = objSchedule.ScheduleID; //this.ScheduleSource = objSchedule.ScheduleSource; this.ThreadID = objSchedule.ThreadID; //this.TimeLapse = objSchedule.TimeLapse; //this.TimeLapseMeasurement = objSchedule.TimeLapseMeasurement; this.RepeatDays = objSchedule.RepeatDays; this.StartDate = objSchedule.StartDate; this.StartHour = objSchedule.StartHour; this.StartMin = objSchedule.StartMin; this.EndDate = objSchedule.EndDate; this.IsEnable = objSchedule.IsEnable; this.FullNamespace = objSchedule.FullNamespace; this.Servers = objSchedule.Servers; this.ScheduleName= objSchedule.ScheduleName; this.ScheduleHistoryID = null; this.HistoryStartDate = null; this.HistoryEndDate = null; this.Status = null; this.ReturnText = string.Empty; this.Server = string.Empty; } } }
37.472973
75
0.635413
[ "MIT" ]
SageFrame/SageFrame
SageFrame.Scheduler/ScheduleHistory.cs
2,775
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 ssm-2014-11-06.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.SimpleSystemsManagement.Model { /// <summary> /// One or more association documents on the instance. /// </summary> public partial class InstanceAssociation { private string _associationId; private string _associationVersion; private string _content; private string _instanceId; /// <summary> /// Gets and sets the property AssociationId. /// <para> /// The association ID. /// </para> /// </summary> public string AssociationId { get { return this._associationId; } set { this._associationId = value; } } // Check to see if AssociationId property is set internal bool IsSetAssociationId() { return this._associationId != null; } /// <summary> /// Gets and sets the property AssociationVersion. /// <para> /// Version information for the association on the instance. /// </para> /// </summary> public string AssociationVersion { get { return this._associationVersion; } set { this._associationVersion = value; } } // Check to see if AssociationVersion property is set internal bool IsSetAssociationVersion() { return this._associationVersion != null; } /// <summary> /// Gets and sets the property Content. /// <para> /// The content of the association document for the instance(s). /// </para> /// </summary> [AWSProperty(Min=1)] public string Content { get { return this._content; } set { this._content = value; } } // Check to see if Content property is set internal bool IsSetContent() { return this._content != null; } /// <summary> /// Gets and sets the property InstanceId. /// <para> /// The instance ID. /// </para> /// </summary> public string InstanceId { get { return this._instanceId; } set { this._instanceId = value; } } // Check to see if InstanceId property is set internal bool IsSetInstanceId() { return this._instanceId != null; } } }
29.556522
102
0.56752
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/SimpleSystemsManagement/Generated/Model/InstanceAssociation.cs
3,399
C#
// 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. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by google-apis-code-generator 1.5.1 // C# generator version: 1.32.2 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ /** * \brief * Cloud Container Builder API Version v1 * * \section ApiInfo API Version Information * <table> * <tr><th>API * <td><a href='https://cloud.google.com/container-builder/docs/'>Cloud Container Builder API</a> * <tr><th>API Version<td>v1 * <tr><th>API Rev<td>20180221 (1147) * <tr><th>API Docs * <td><a href='https://cloud.google.com/container-builder/docs/'> * https://cloud.google.com/container-builder/docs/</a> * <tr><th>Discovery Name<td>cloudbuild * </table> * * \section ForMoreInfo For More Information * * The complete API documentation for using Cloud Container Builder API can be found at * <a href='https://cloud.google.com/container-builder/docs/'>https://cloud.google.com/container-builder/docs/</a>. * * For more information about the Google APIs Client Library for .NET, see * <a href='https://developers.google.com/api-client-library/dotnet/get_started'> * https://developers.google.com/api-client-library/dotnet/get_started</a> */ namespace Google.Apis.CloudBuild.v1 { /// <summary>The CloudBuild Service.</summary> public class CloudBuildService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public CloudBuildService() : this(new Google.Apis.Services.BaseClientService.Initializer()) {} /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public CloudBuildService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { operations = new OperationsResource(this); projects = new ProjectsResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features { get { return new string[0]; } } /// <summary>Gets the service name.</summary> public override string Name { get { return "cloudbuild"; } } /// <summary>Gets the service base URI.</summary> public override string BaseUri { get { return "https://cloudbuild.googleapis.com/"; } } /// <summary>Gets the service base path.</summary> public override string BasePath { get { return ""; } } #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri { get { return "https://cloudbuild.googleapis.com/batch"; } } /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath { get { return "batch"; } } #endif /// <summary>Available OAuth 2.0 scopes for use with the Cloud Container Builder API.</summary> public class Scope { /// <summary>View and manage your data across Google Cloud Platform services</summary> public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; } private readonly OperationsResource operations; /// <summary>Gets the Operations resource.</summary> public virtual OperationsResource Operations { get { return operations; } } private readonly ProjectsResource projects; /// <summary>Gets the Projects resource.</summary> public virtual ProjectsResource Projects { get { return projects; } } } ///<summary>A base abstract class for CloudBuild requests.</summary> public abstract class CloudBuildBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { ///<summary>Constructs a new CloudBuildBaseServiceRequest instance.</summary> protected CloudBuildBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>V1 error format.</summary> [Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<XgafvEnum> Xgafv { get; set; } /// <summary>V1 error format.</summary> public enum XgafvEnum { /// <summary>v1 error format</summary> [Google.Apis.Util.StringValueAttribute("1")] Value1, /// <summary>v2 error format</summary> [Google.Apis.Util.StringValueAttribute("2")] Value2, } /// <summary>OAuth access token.</summary> [Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string AccessToken { get; set; } /// <summary>Data format for response.</summary> /// [default: json] [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json, /// <summary>Media download with context-dependent Content-Type</summary> [Google.Apis.Util.StringValueAttribute("media")] Media, /// <summary>Responses with Content-Type of application/x-protobuf</summary> [Google.Apis.Util.StringValueAttribute("proto")] Proto, } /// <summary>OAuth bearer token.</summary> [Google.Apis.Util.RequestParameterAttribute("bearer_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string BearerToken { get; set; } /// <summary>JSONP</summary> [Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)] public virtual string Callback { get; set; } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports. /// Required unless you provide an OAuth 2.0 token.</summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Pretty-print response.</summary> /// [default: true] [Google.Apis.Util.RequestParameterAttribute("pp", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> Pp { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> /// [default: true] [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string /// assigned to a user, but should not exceed 40 characters.</summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadType { get; set; } /// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadProtocol { get; set; } /// <summary>Initializes CloudBuild parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "$.xgafv", new Google.Apis.Discovery.Parameter { Name = "$.xgafv", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "access_token", new Google.Apis.Discovery.Parameter { Name = "access_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add( "bearer_token", new Google.Apis.Discovery.Parameter { Name = "bearer_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "callback", new Google.Apis.Discovery.Parameter { Name = "callback", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "pp", new Google.Apis.Discovery.Parameter { Name = "pp", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add( "prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add( "quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "uploadType", new Google.Apis.Discovery.Parameter { Name = "uploadType", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "upload_protocol", new Google.Apis.Discovery.Parameter { Name = "upload_protocol", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "operations" collection of methods.</summary> public class OperationsResource { private const string Resource = "operations"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public OperationsResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Starts asynchronous cancellation on a long-running operation. The server makes a best effort to /// cancel the operation, but success is not guaranteed. If the server doesn't support this method, it returns /// `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to check whether /// the cancellation succeeded or whether the operation completed despite cancellation. On successful /// cancellation, the operation is not deleted; instead, it becomes an operation with an Operation.error value /// with a google.rpc.Status.code of 1, corresponding to `Code.CANCELLED`.</summary> /// <param name="body">The body of the request.</param> /// <param name="name">The name of the operation resource to be cancelled.</param> public virtual CancelRequest Cancel(Google.Apis.CloudBuild.v1.Data.CancelOperationRequest body, string name) { return new CancelRequest(service, body, name); } /// <summary>Starts asynchronous cancellation on a long-running operation. The server makes a best effort to /// cancel the operation, but success is not guaranteed. If the server doesn't support this method, it returns /// `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to check whether /// the cancellation succeeded or whether the operation completed despite cancellation. On successful /// cancellation, the operation is not deleted; instead, it becomes an operation with an Operation.error value /// with a google.rpc.Status.code of 1, corresponding to `Code.CANCELLED`.</summary> public class CancelRequest : CloudBuildBaseServiceRequest<Google.Apis.CloudBuild.v1.Data.Empty> { /// <summary>Constructs a new Cancel request.</summary> public CancelRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudBuild.v1.Data.CancelOperationRequest body, string name) : base(service) { Name = name; Body = body; InitParameters(); } /// <summary>The name of the operation resource to be cancelled.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudBuild.v1.Data.CancelOperationRequest Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "cancel"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/{+name}:cancel"; } } /// <summary>Initializes Cancel parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^operations/.+$", }); } } /// <summary>Gets the latest state of a long-running operation. Clients can use this method to poll the /// operation result at intervals as recommended by the API service.</summary> /// <param name="name">The name of the operation resource.</param> public virtual GetRequest Get(string name) { return new GetRequest(service, name); } /// <summary>Gets the latest state of a long-running operation. Clients can use this method to poll the /// operation result at intervals as recommended by the API service.</summary> public class GetRequest : CloudBuildBaseServiceRequest<Google.Apis.CloudBuild.v1.Data.Operation> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary>The name of the operation resource.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "get"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/{+name}"; } } /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^operations/.+$", }); } } /// <summary>Lists operations that match the specified filter in the request. If the server doesn't support this /// method, it returns `UNIMPLEMENTED`. /// /// NOTE: the `name` binding allows API services to override the binding to use different resource name schemes, /// such as `users/operations`. To override the binding, API services can add a binding such as /// `"/v1/{name=users}/operations"` to their service configuration. For backwards compatibility, the default /// name includes the operations collection id, however overriding users must ensure the name binding is the /// parent resource, without the operations collection id.</summary> /// <param name="name">The name of the operation's parent resource.</param> public virtual ListRequest List(string name) { return new ListRequest(service, name); } /// <summary>Lists operations that match the specified filter in the request. If the server doesn't support this /// method, it returns `UNIMPLEMENTED`. /// /// NOTE: the `name` binding allows API services to override the binding to use different resource name schemes, /// such as `users/operations`. To override the binding, API services can add a binding such as /// `"/v1/{name=users}/operations"` to their service configuration. For backwards compatibility, the default /// name includes the operations collection id, however overriding users must ensure the name binding is the /// parent resource, without the operations collection id.</summary> public class ListRequest : CloudBuildBaseServiceRequest<Google.Apis.CloudBuild.v1.Data.ListOperationsResponse> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary>The name of the operation's parent resource.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>The standard list filter.</summary> [Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)] public virtual string Filter { get; set; } /// <summary>The standard list page token.</summary> [Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)] public virtual string PageToken { get; set; } /// <summary>The standard list page size.</summary> [Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> PageSize { get; set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "list"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/{+name}"; } } /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^operations$", }); RequestParameters.Add( "filter", new Google.Apis.Discovery.Parameter { Name = "filter", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "pageToken", new Google.Apis.Discovery.Parameter { Name = "pageToken", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "pageSize", new Google.Apis.Discovery.Parameter { Name = "pageSize", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } /// <summary>The "projects" collection of methods.</summary> public class ProjectsResource { private const string Resource = "projects"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public ProjectsResource(Google.Apis.Services.IClientService service) { this.service = service; builds = new BuildsResource(service); triggers = new TriggersResource(service); } private readonly BuildsResource builds; /// <summary>Gets the Builds resource.</summary> public virtual BuildsResource Builds { get { return builds; } } /// <summary>The "builds" collection of methods.</summary> public class BuildsResource { private const string Resource = "builds"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public BuildsResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Cancels a requested build in progress.</summary> /// <param name="body">The body of the request.</param> /// <param name="projectId">ID of the project.</param> /// <param name="id">ID of the build.</param> public virtual CancelRequest Cancel(Google.Apis.CloudBuild.v1.Data.CancelBuildRequest body, string projectId, string id) { return new CancelRequest(service, body, projectId, id); } /// <summary>Cancels a requested build in progress.</summary> public class CancelRequest : CloudBuildBaseServiceRequest<Google.Apis.CloudBuild.v1.Data.Build> { /// <summary>Constructs a new Cancel request.</summary> public CancelRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudBuild.v1.Data.CancelBuildRequest body, string projectId, string id) : base(service) { ProjectId = projectId; Id = id; Body = body; InitParameters(); } /// <summary>ID of the project.</summary> [Google.Apis.Util.RequestParameterAttribute("projectId", Google.Apis.Util.RequestParameterType.Path)] public virtual string ProjectId { get; private set; } /// <summary>ID of the build.</summary> [Google.Apis.Util.RequestParameterAttribute("id", Google.Apis.Util.RequestParameterType.Path)] public virtual string Id { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudBuild.v1.Data.CancelBuildRequest Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "cancel"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/projects/{projectId}/builds/{id}:cancel"; } } /// <summary>Initializes Cancel parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "projectId", new Google.Apis.Discovery.Parameter { Name = "projectId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "id", new Google.Apis.Discovery.Parameter { Name = "id", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Starts a build with the specified configuration. /// /// The long-running Operation returned by this method will include the ID of the build, which can be passed /// to GetBuild to determine its status (e.g., success or failure).</summary> /// <param name="body">The body of the request.</param> /// <param name="projectId">ID of the project.</param> public virtual CreateRequest Create(Google.Apis.CloudBuild.v1.Data.Build body, string projectId) { return new CreateRequest(service, body, projectId); } /// <summary>Starts a build with the specified configuration. /// /// The long-running Operation returned by this method will include the ID of the build, which can be passed /// to GetBuild to determine its status (e.g., success or failure).</summary> public class CreateRequest : CloudBuildBaseServiceRequest<Google.Apis.CloudBuild.v1.Data.Operation> { /// <summary>Constructs a new Create request.</summary> public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudBuild.v1.Data.Build body, string projectId) : base(service) { ProjectId = projectId; Body = body; InitParameters(); } /// <summary>ID of the project.</summary> [Google.Apis.Util.RequestParameterAttribute("projectId", Google.Apis.Util.RequestParameterType.Path)] public virtual string ProjectId { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudBuild.v1.Data.Build Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "create"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/projects/{projectId}/builds"; } } /// <summary>Initializes Create parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "projectId", new Google.Apis.Discovery.Parameter { Name = "projectId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Returns information about a previously requested build. /// /// The Build that is returned includes its status (e.g., success or failure, or in-progress), and timing /// information.</summary> /// <param name="projectId">ID of the project.</param> /// <param name="id">ID of the build.</param> public virtual GetRequest Get(string projectId, string id) { return new GetRequest(service, projectId, id); } /// <summary>Returns information about a previously requested build. /// /// The Build that is returned includes its status (e.g., success or failure, or in-progress), and timing /// information.</summary> public class GetRequest : CloudBuildBaseServiceRequest<Google.Apis.CloudBuild.v1.Data.Build> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string projectId, string id) : base(service) { ProjectId = projectId; Id = id; InitParameters(); } /// <summary>ID of the project.</summary> [Google.Apis.Util.RequestParameterAttribute("projectId", Google.Apis.Util.RequestParameterType.Path)] public virtual string ProjectId { get; private set; } /// <summary>ID of the build.</summary> [Google.Apis.Util.RequestParameterAttribute("id", Google.Apis.Util.RequestParameterType.Path)] public virtual string Id { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "get"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/projects/{projectId}/builds/{id}"; } } /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "projectId", new Google.Apis.Discovery.Parameter { Name = "projectId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "id", new Google.Apis.Discovery.Parameter { Name = "id", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Lists previously requested builds. /// /// Previously requested builds may still be in-progress, or may have finished successfully or /// unsuccessfully.</summary> /// <param name="projectId">ID of the project.</param> public virtual ListRequest List(string projectId) { return new ListRequest(service, projectId); } /// <summary>Lists previously requested builds. /// /// Previously requested builds may still be in-progress, or may have finished successfully or /// unsuccessfully.</summary> public class ListRequest : CloudBuildBaseServiceRequest<Google.Apis.CloudBuild.v1.Data.ListBuildsResponse> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service, string projectId) : base(service) { ProjectId = projectId; InitParameters(); } /// <summary>ID of the project.</summary> [Google.Apis.Util.RequestParameterAttribute("projectId", Google.Apis.Util.RequestParameterType.Path)] public virtual string ProjectId { get; private set; } /// <summary>Number of results to return in the list.</summary> [Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> PageSize { get; set; } /// <summary>The raw filter text to constrain the results.</summary> [Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)] public virtual string Filter { get; set; } /// <summary>Token to provide to skip to a particular spot in the list.</summary> [Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)] public virtual string PageToken { get; set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "list"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/projects/{projectId}/builds"; } } /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "projectId", new Google.Apis.Discovery.Parameter { Name = "projectId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "pageSize", new Google.Apis.Discovery.Parameter { Name = "pageSize", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "filter", new Google.Apis.Discovery.Parameter { Name = "filter", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "pageToken", new Google.Apis.Discovery.Parameter { Name = "pageToken", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>Creates a new build based on the given build. /// /// This API creates a new build using the original build request, which may or may not result in an /// identical build. /// /// For triggered builds: /// /// * Triggered builds resolve to a precise revision, so a retry of a triggered build will result in a build /// that uses the same revision. /// /// For non-triggered builds that specify RepoSource: /// /// * If the original build built from the tip of a branch, the retried build will build from the tip of /// that branch, which may not be the same revision as the original build. * If the original build specified /// a commit sha or revision ID, the retried build will use the identical source. /// /// For builds that specify StorageSource: /// /// * If the original build pulled source from Cloud Storage without specifying the generation of the /// object, the new build will use the current object, which may be different from the original build /// source. * If the original build pulled source from Cloud Storage and specified the generation of the /// object, the new build will attempt to use the same object, which may or may not be available depending /// on the bucket's lifecycle management settings.</summary> /// <param name="body">The body of the request.</param> /// <param name="projectId">ID of the project.</param> /// <param name="id">Build ID of the original /// build.</param> public virtual RetryRequest Retry(Google.Apis.CloudBuild.v1.Data.RetryBuildRequest body, string projectId, string id) { return new RetryRequest(service, body, projectId, id); } /// <summary>Creates a new build based on the given build. /// /// This API creates a new build using the original build request, which may or may not result in an /// identical build. /// /// For triggered builds: /// /// * Triggered builds resolve to a precise revision, so a retry of a triggered build will result in a build /// that uses the same revision. /// /// For non-triggered builds that specify RepoSource: /// /// * If the original build built from the tip of a branch, the retried build will build from the tip of /// that branch, which may not be the same revision as the original build. * If the original build specified /// a commit sha or revision ID, the retried build will use the identical source. /// /// For builds that specify StorageSource: /// /// * If the original build pulled source from Cloud Storage without specifying the generation of the /// object, the new build will use the current object, which may be different from the original build /// source. * If the original build pulled source from Cloud Storage and specified the generation of the /// object, the new build will attempt to use the same object, which may or may not be available depending /// on the bucket's lifecycle management settings.</summary> public class RetryRequest : CloudBuildBaseServiceRequest<Google.Apis.CloudBuild.v1.Data.Operation> { /// <summary>Constructs a new Retry request.</summary> public RetryRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudBuild.v1.Data.RetryBuildRequest body, string projectId, string id) : base(service) { ProjectId = projectId; Id = id; Body = body; InitParameters(); } /// <summary>ID of the project.</summary> [Google.Apis.Util.RequestParameterAttribute("projectId", Google.Apis.Util.RequestParameterType.Path)] public virtual string ProjectId { get; private set; } /// <summary>Build ID of the original build.</summary> [Google.Apis.Util.RequestParameterAttribute("id", Google.Apis.Util.RequestParameterType.Path)] public virtual string Id { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudBuild.v1.Data.RetryBuildRequest Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "retry"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/projects/{projectId}/builds/{id}:retry"; } } /// <summary>Initializes Retry parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "projectId", new Google.Apis.Discovery.Parameter { Name = "projectId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "id", new Google.Apis.Discovery.Parameter { Name = "id", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } } private readonly TriggersResource triggers; /// <summary>Gets the Triggers resource.</summary> public virtual TriggersResource Triggers { get { return triggers; } } /// <summary>The "triggers" collection of methods.</summary> public class TriggersResource { private const string Resource = "triggers"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public TriggersResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Creates a new BuildTrigger. /// /// This API is experimental.</summary> /// <param name="body">The body of the request.</param> /// <param name="projectId">ID of the project for which to configure automatic builds.</param> public virtual CreateRequest Create(Google.Apis.CloudBuild.v1.Data.BuildTrigger body, string projectId) { return new CreateRequest(service, body, projectId); } /// <summary>Creates a new BuildTrigger. /// /// This API is experimental.</summary> public class CreateRequest : CloudBuildBaseServiceRequest<Google.Apis.CloudBuild.v1.Data.BuildTrigger> { /// <summary>Constructs a new Create request.</summary> public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudBuild.v1.Data.BuildTrigger body, string projectId) : base(service) { ProjectId = projectId; Body = body; InitParameters(); } /// <summary>ID of the project for which to configure automatic builds.</summary> [Google.Apis.Util.RequestParameterAttribute("projectId", Google.Apis.Util.RequestParameterType.Path)] public virtual string ProjectId { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudBuild.v1.Data.BuildTrigger Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "create"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/projects/{projectId}/triggers"; } } /// <summary>Initializes Create parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "projectId", new Google.Apis.Discovery.Parameter { Name = "projectId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Deletes an BuildTrigger by its project ID and trigger ID. /// /// This API is experimental.</summary> /// <param name="projectId">ID of the project that owns the trigger.</param> /// <param name="triggerId">ID of the /// BuildTrigger to delete.</param> public virtual DeleteRequest Delete(string projectId, string triggerId) { return new DeleteRequest(service, projectId, triggerId); } /// <summary>Deletes an BuildTrigger by its project ID and trigger ID. /// /// This API is experimental.</summary> public class DeleteRequest : CloudBuildBaseServiceRequest<Google.Apis.CloudBuild.v1.Data.Empty> { /// <summary>Constructs a new Delete request.</summary> public DeleteRequest(Google.Apis.Services.IClientService service, string projectId, string triggerId) : base(service) { ProjectId = projectId; TriggerId = triggerId; InitParameters(); } /// <summary>ID of the project that owns the trigger.</summary> [Google.Apis.Util.RequestParameterAttribute("projectId", Google.Apis.Util.RequestParameterType.Path)] public virtual string ProjectId { get; private set; } /// <summary>ID of the BuildTrigger to delete.</summary> [Google.Apis.Util.RequestParameterAttribute("triggerId", Google.Apis.Util.RequestParameterType.Path)] public virtual string TriggerId { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "delete"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "DELETE"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/projects/{projectId}/triggers/{triggerId}"; } } /// <summary>Initializes Delete parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "projectId", new Google.Apis.Discovery.Parameter { Name = "projectId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "triggerId", new Google.Apis.Discovery.Parameter { Name = "triggerId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Gets information about a BuildTrigger. /// /// This API is experimental.</summary> /// <param name="projectId">ID of the project that owns the trigger.</param> /// <param name="triggerId">ID of the /// BuildTrigger to get.</param> public virtual GetRequest Get(string projectId, string triggerId) { return new GetRequest(service, projectId, triggerId); } /// <summary>Gets information about a BuildTrigger. /// /// This API is experimental.</summary> public class GetRequest : CloudBuildBaseServiceRequest<Google.Apis.CloudBuild.v1.Data.BuildTrigger> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string projectId, string triggerId) : base(service) { ProjectId = projectId; TriggerId = triggerId; InitParameters(); } /// <summary>ID of the project that owns the trigger.</summary> [Google.Apis.Util.RequestParameterAttribute("projectId", Google.Apis.Util.RequestParameterType.Path)] public virtual string ProjectId { get; private set; } /// <summary>ID of the BuildTrigger to get.</summary> [Google.Apis.Util.RequestParameterAttribute("triggerId", Google.Apis.Util.RequestParameterType.Path)] public virtual string TriggerId { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "get"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/projects/{projectId}/triggers/{triggerId}"; } } /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "projectId", new Google.Apis.Discovery.Parameter { Name = "projectId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "triggerId", new Google.Apis.Discovery.Parameter { Name = "triggerId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Lists existing BuildTrigger. /// /// This API is experimental.</summary> /// <param name="projectId">ID of the project for which to list BuildTriggers.</param> public virtual ListRequest List(string projectId) { return new ListRequest(service, projectId); } /// <summary>Lists existing BuildTrigger. /// /// This API is experimental.</summary> public class ListRequest : CloudBuildBaseServiceRequest<Google.Apis.CloudBuild.v1.Data.ListBuildTriggersResponse> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service, string projectId) : base(service) { ProjectId = projectId; InitParameters(); } /// <summary>ID of the project for which to list BuildTriggers.</summary> [Google.Apis.Util.RequestParameterAttribute("projectId", Google.Apis.Util.RequestParameterType.Path)] public virtual string ProjectId { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "list"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/projects/{projectId}/triggers"; } } /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "projectId", new Google.Apis.Discovery.Parameter { Name = "projectId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Updates an BuildTrigger by its project ID and trigger ID. /// /// This API is experimental.</summary> /// <param name="body">The body of the request.</param> /// <param name="projectId">ID of the project that owns the trigger.</param> /// <param name="triggerId">ID of the /// BuildTrigger to update.</param> public virtual PatchRequest Patch(Google.Apis.CloudBuild.v1.Data.BuildTrigger body, string projectId, string triggerId) { return new PatchRequest(service, body, projectId, triggerId); } /// <summary>Updates an BuildTrigger by its project ID and trigger ID. /// /// This API is experimental.</summary> public class PatchRequest : CloudBuildBaseServiceRequest<Google.Apis.CloudBuild.v1.Data.BuildTrigger> { /// <summary>Constructs a new Patch request.</summary> public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudBuild.v1.Data.BuildTrigger body, string projectId, string triggerId) : base(service) { ProjectId = projectId; TriggerId = triggerId; Body = body; InitParameters(); } /// <summary>ID of the project that owns the trigger.</summary> [Google.Apis.Util.RequestParameterAttribute("projectId", Google.Apis.Util.RequestParameterType.Path)] public virtual string ProjectId { get; private set; } /// <summary>ID of the BuildTrigger to update.</summary> [Google.Apis.Util.RequestParameterAttribute("triggerId", Google.Apis.Util.RequestParameterType.Path)] public virtual string TriggerId { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudBuild.v1.Data.BuildTrigger Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "patch"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "PATCH"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/projects/{projectId}/triggers/{triggerId}"; } } /// <summary>Initializes Patch parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "projectId", new Google.Apis.Discovery.Parameter { Name = "projectId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "triggerId", new Google.Apis.Discovery.Parameter { Name = "triggerId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Runs a BuildTrigger at a particular source revision.</summary> /// <param name="body">The body of the request.</param> /// <param name="projectId">ID of the project.</param> /// <param name="triggerId">ID of the trigger.</param> public virtual RunRequest Run(Google.Apis.CloudBuild.v1.Data.RepoSource body, string projectId, string triggerId) { return new RunRequest(service, body, projectId, triggerId); } /// <summary>Runs a BuildTrigger at a particular source revision.</summary> public class RunRequest : CloudBuildBaseServiceRequest<Google.Apis.CloudBuild.v1.Data.Operation> { /// <summary>Constructs a new Run request.</summary> public RunRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudBuild.v1.Data.RepoSource body, string projectId, string triggerId) : base(service) { ProjectId = projectId; TriggerId = triggerId; Body = body; InitParameters(); } /// <summary>ID of the project.</summary> [Google.Apis.Util.RequestParameterAttribute("projectId", Google.Apis.Util.RequestParameterType.Path)] public virtual string ProjectId { get; private set; } /// <summary>ID of the trigger.</summary> [Google.Apis.Util.RequestParameterAttribute("triggerId", Google.Apis.Util.RequestParameterType.Path)] public virtual string TriggerId { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudBuild.v1.Data.RepoSource Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "run"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/projects/{projectId}/triggers/{triggerId}:run"; } } /// <summary>Initializes Run parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "projectId", new Google.Apis.Discovery.Parameter { Name = "projectId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "triggerId", new Google.Apis.Discovery.Parameter { Name = "triggerId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } } } } namespace Google.Apis.CloudBuild.v1.Data { /// <summary>A build resource in the Container Builder API. /// /// At a high level, a Build describes where to find source code, how to build it (for example, the builder image to /// run on the source), and what tag to apply to the built image when it is pushed to Google Container Registry. /// /// Fields can include the following variables which will be expanded when the build is created: /// /// - $PROJECT_ID: the project ID of the build. - $BUILD_ID: the autogenerated ID of the build. - $REPO_NAME: the /// source repository name specified by RepoSource. - $BRANCH_NAME: the branch name specified by RepoSource. - /// $TAG_NAME: the tag name specified by RepoSource. - $REVISION_ID or $COMMIT_SHA: the commit SHA specified by /// RepoSource or resolved from the specified branch or tag. - $SHORT_SHA: first 7 characters of $REVISION_ID or /// $COMMIT_SHA.</summary> public class Build : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The ID of the BuildTrigger that triggered this build, if it was triggered automatically. /// @OutputOnly</summary> [Newtonsoft.Json.JsonPropertyAttribute("buildTriggerId")] public virtual string BuildTriggerId { get; set; } /// <summary>Time at which the request to create the build was received. @OutputOnly</summary> [Newtonsoft.Json.JsonPropertyAttribute("createTime")] public virtual object CreateTime { get; set; } /// <summary>Time at which execution of the build was finished. /// /// The difference between finish_time and start_time is the duration of the build's execution. /// @OutputOnly</summary> [Newtonsoft.Json.JsonPropertyAttribute("finishTime")] public virtual object FinishTime { get; set; } /// <summary>Unique identifier of the build. @OutputOnly</summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual string Id { get; set; } /// <summary>A list of images to be pushed upon the successful completion of all build steps. /// /// The images will be pushed using the builder service account's credentials. /// /// The digests of the pushed images will be stored in the Build resource's results field. /// /// If any of the images fail to be pushed, the build is marked FAILURE.</summary> [Newtonsoft.Json.JsonPropertyAttribute("images")] public virtual System.Collections.Generic.IList<string> Images { get; set; } /// <summary>URL to logs for this build in Google Cloud Console. @OutputOnly</summary> [Newtonsoft.Json.JsonPropertyAttribute("logUrl")] public virtual string LogUrl { get; set; } /// <summary>Google Cloud Storage bucket where logs should be written (see [Bucket Name /// Requirements](https://cloud.google.com/storage/docs/bucket-naming#requirements)). Logs file names will be of /// the format `${logs_bucket}/log-${build_id}.txt`.</summary> [Newtonsoft.Json.JsonPropertyAttribute("logsBucket")] public virtual string LogsBucket { get; set; } /// <summary>Special options for this build.</summary> [Newtonsoft.Json.JsonPropertyAttribute("options")] public virtual BuildOptions Options { get; set; } /// <summary>ID of the project. @OutputOnly.</summary> [Newtonsoft.Json.JsonPropertyAttribute("projectId")] public virtual string ProjectId { get; set; } /// <summary>Results of the build. @OutputOnly</summary> [Newtonsoft.Json.JsonPropertyAttribute("results")] public virtual Results Results { get; set; } /// <summary>Secrets to decrypt using Cloud KMS.</summary> [Newtonsoft.Json.JsonPropertyAttribute("secrets")] public virtual System.Collections.Generic.IList<Secret> Secrets { get; set; } /// <summary>Describes where to find the source files to build.</summary> [Newtonsoft.Json.JsonPropertyAttribute("source")] public virtual Source Source { get; set; } /// <summary>A permanent fixed identifier for source. @OutputOnly</summary> [Newtonsoft.Json.JsonPropertyAttribute("sourceProvenance")] public virtual SourceProvenance SourceProvenance { get; set; } /// <summary>Time at which execution of the build was started. @OutputOnly</summary> [Newtonsoft.Json.JsonPropertyAttribute("startTime")] public virtual object StartTime { get; set; } /// <summary>Status of the build. @OutputOnly</summary> [Newtonsoft.Json.JsonPropertyAttribute("status")] public virtual string Status { get; set; } /// <summary>Customer-readable message about the current status. @OutputOnly</summary> [Newtonsoft.Json.JsonPropertyAttribute("statusDetail")] public virtual string StatusDetail { get; set; } /// <summary>Describes the operations to be performed on the workspace.</summary> [Newtonsoft.Json.JsonPropertyAttribute("steps")] public virtual System.Collections.Generic.IList<BuildStep> Steps { get; set; } /// <summary>Substitutions data for Build resource.</summary> [Newtonsoft.Json.JsonPropertyAttribute("substitutions")] public virtual System.Collections.Generic.IDictionary<string,string> Substitutions { get; set; } /// <summary>Tags for annotation of a Build. These are not docker tags.</summary> [Newtonsoft.Json.JsonPropertyAttribute("tags")] public virtual System.Collections.Generic.IList<string> Tags { get; set; } /// <summary>Amount of time that this build should be allowed to run, to second granularity. If this amount of /// time elapses, work on the build will cease and the build status will be TIMEOUT. /// /// Default time is ten minutes.</summary> [Newtonsoft.Json.JsonPropertyAttribute("timeout")] public virtual object Timeout { get; set; } /// <summary>Stores timing information for phases of the build. Valid keys are: /// /// * BUILD: time to execute all build steps * PUSH: time to push all specified images. * FETCHSOURCE: time to /// fetch source. /// /// If the build does not specify source, or does not specify images, these keys will not be included. /// @OutputOnly</summary> [Newtonsoft.Json.JsonPropertyAttribute("timing")] public virtual System.Collections.Generic.IDictionary<string,TimeSpan> Timing { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Metadata for build operations.</summary> public class BuildOperationMetadata : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The build that the operation is tracking.</summary> [Newtonsoft.Json.JsonPropertyAttribute("build")] public virtual Build Build { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Optional arguments to enable specific features of builds.</summary> public class BuildOptions : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Requested disk size for the VM that runs the build. Note that this is *NOT* "disk free"; some of /// the space will be used by the operating system and build utilities. Also note that this is the minimum disk /// size that will be allocated for the build -- the build may run with a larger disk than requested. At /// present, the maximum disk size is 1000GB; builds that request more than the maximum are rejected with an /// error.</summary> [Newtonsoft.Json.JsonPropertyAttribute("diskSizeGb")] public virtual System.Nullable<long> DiskSizeGb { get; set; } /// <summary>LogStreamingOption to define build log streaming behavior to Google Cloud Storage.</summary> [Newtonsoft.Json.JsonPropertyAttribute("logStreamingOption")] public virtual string LogStreamingOption { get; set; } /// <summary>Compute Engine machine type on which to run the build.</summary> [Newtonsoft.Json.JsonPropertyAttribute("machineType")] public virtual string MachineType { get; set; } /// <summary>Requested verifiability options.</summary> [Newtonsoft.Json.JsonPropertyAttribute("requestedVerifyOption")] public virtual string RequestedVerifyOption { get; set; } /// <summary>Requested hash for SourceProvenance.</summary> [Newtonsoft.Json.JsonPropertyAttribute("sourceProvenanceHash")] public virtual System.Collections.Generic.IList<string> SourceProvenanceHash { get; set; } /// <summary>SubstitutionOption to allow unmatch substitutions.</summary> [Newtonsoft.Json.JsonPropertyAttribute("substitutionOption")] public virtual string SubstitutionOption { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>BuildStep describes a step to perform in the build pipeline.</summary> public class BuildStep : Google.Apis.Requests.IDirectResponseSchema { /// <summary>A list of arguments that will be presented to the step when it is started. /// /// If the image used to run the step's container has an entrypoint, these args will be used as arguments to /// that entrypoint. If the image does not define an entrypoint, the first element in args will be used as the /// entrypoint, and the remainder will be used as arguments.</summary> [Newtonsoft.Json.JsonPropertyAttribute("args")] public virtual System.Collections.Generic.IList<string> Args { get; set; } /// <summary>Working directory to use when running this step's container. /// /// If this value is a relative path, it is relative to the build's working directory. If this value is /// absolute, it may be outside the build's working directory, in which case the contents of the path may not be /// persisted across build step executions, unless a volume for that path is specified. /// /// If the build specifies a RepoSource with dir and a step with a dir which specifies an absolute path, the /// RepoSource dir is ignored for the step's execution.</summary> [Newtonsoft.Json.JsonPropertyAttribute("dir")] public virtual string Dir { get; set; } /// <summary>Optional entrypoint to be used instead of the build step image's default If unset, the image's /// default will be used.</summary> [Newtonsoft.Json.JsonPropertyAttribute("entrypoint")] public virtual string Entrypoint { get; set; } /// <summary>A list of environment variable definitions to be used when running a step. /// /// The elements are of the form "KEY=VALUE" for the environment variable "KEY" being given the value /// "VALUE".</summary> [Newtonsoft.Json.JsonPropertyAttribute("env")] public virtual System.Collections.Generic.IList<string> Env { get; set; } /// <summary>Optional unique identifier for this build step, used in wait_for to reference this build step as a /// dependency.</summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual string Id { get; set; } /// <summary>The name of the container image that will run this particular build step. /// /// If the image is already available in the host's Docker daemon's cache, it will be run directly. If not, the /// host will attempt to pull the image first, using the builder service account's credentials if necessary. /// /// The Docker daemon's cache will already have the latest versions of all of the officially supported build /// steps ([https://github.com/GoogleCloudPlatform/cloud-builders](https://github.com/GoogleCloudPlatform/cloud- /// builders)). The Docker daemon will also have cached many of the layers for some popular images, like /// "ubuntu", "debian", but they will be refreshed at the time you attempt to use them. /// /// If you built an image in a previous build step, it will be stored in the host's Docker daemon's cache and is /// available to use as the name for a later build step.</summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary>A list of environment variables which are encrypted using a Cloud KMS crypto key. These values must /// be specified in the build's secrets.</summary> [Newtonsoft.Json.JsonPropertyAttribute("secretEnv")] public virtual System.Collections.Generic.IList<string> SecretEnv { get; set; } /// <summary>Status of the build step. At this time, build step status is only updated on build completion; step /// status is not updated in real-time as the build progresses. @OutputOnly</summary> [Newtonsoft.Json.JsonPropertyAttribute("status")] public virtual string Status { get; set; } /// <summary>Time limit for executing this build step. If not defined, the step has no time limit and will be /// allowed to continue to run until either it completes or the build itself times out.</summary> [Newtonsoft.Json.JsonPropertyAttribute("timeout")] public virtual object Timeout { get; set; } /// <summary>Stores timing information for executing this build step. @OutputOnly</summary> [Newtonsoft.Json.JsonPropertyAttribute("timing")] public virtual TimeSpan Timing { get; set; } /// <summary>List of volumes to mount into the build step. /// /// Each volume will be created as an empty volume prior to execution of the build step. Upon completion of the /// build, volumes and their contents will be discarded. /// /// Using a named volume in only one step is not valid as it is indicative of a mis-configured build /// request.</summary> [Newtonsoft.Json.JsonPropertyAttribute("volumes")] public virtual System.Collections.Generic.IList<Volume> Volumes { get; set; } /// <summary>The ID(s) of the step(s) that this build step depends on. This build step will not start until all /// the build steps in wait_for have completed successfully. If wait_for is empty, this build step will start /// when all previous build steps in the Build.Steps list have completed successfully.</summary> [Newtonsoft.Json.JsonPropertyAttribute("waitFor")] public virtual System.Collections.Generic.IList<string> WaitFor { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Configuration for an automated build in response to source repository changes.</summary> public class BuildTrigger : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Contents of the build template.</summary> [Newtonsoft.Json.JsonPropertyAttribute("build")] public virtual Build Build { get; set; } /// <summary>Time when the trigger was created. /// /// @OutputOnly</summary> [Newtonsoft.Json.JsonPropertyAttribute("createTime")] public virtual object CreateTime { get; set; } /// <summary>Human-readable description of this trigger.</summary> [Newtonsoft.Json.JsonPropertyAttribute("description")] public virtual string Description { get; set; } /// <summary>If true, the trigger will never result in a build.</summary> [Newtonsoft.Json.JsonPropertyAttribute("disabled")] public virtual System.Nullable<bool> Disabled { get; set; } /// <summary>Path, from the source root, to a file whose contents is used for the template.</summary> [Newtonsoft.Json.JsonPropertyAttribute("filename")] public virtual string Filename { get; set; } /// <summary>Unique identifier of the trigger. /// /// @OutputOnly</summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual string Id { get; set; } /// <summary>Substitutions data for Build resource.</summary> [Newtonsoft.Json.JsonPropertyAttribute("substitutions")] public virtual System.Collections.Generic.IDictionary<string,string> Substitutions { get; set; } /// <summary>Template describing the types of source changes to trigger a build. /// /// Branch and tag names in trigger templates are interpreted as regular expressions. Any branch or tag change /// that matches that regular expression will trigger a build.</summary> [Newtonsoft.Json.JsonPropertyAttribute("triggerTemplate")] public virtual RepoSource TriggerTemplate { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>BuiltImage describes an image built by the pipeline.</summary> public class BuiltImage : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Docker Registry 2.0 digest.</summary> [Newtonsoft.Json.JsonPropertyAttribute("digest")] public virtual string Digest { get; set; } /// <summary>Name used to push the container image to Google Container Registry, as presented to `docker /// push`.</summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary>Stores timing information for pushing the specified image. @OutputOnly</summary> [Newtonsoft.Json.JsonPropertyAttribute("pushTiming")] public virtual TimeSpan PushTiming { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Request to cancel an ongoing build.</summary> public class CancelBuildRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The request message for Operations.CancelOperation.</summary> public class CancelOperationRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A /// typical example is to use it as the request or the response type of an API method. For instance: /// /// service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } /// /// The JSON representation for `Empty` is empty JSON object `{}`.</summary> public class Empty : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Container message for hashes of byte content of files, used in SourceProvenance messages to verify /// integrity of source input to the build.</summary> public class FileHashes : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Collection of file hashes.</summary> [Newtonsoft.Json.JsonPropertyAttribute("fileHash")] public virtual System.Collections.Generic.IList<Hash> FileHash { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Container message for hash values.</summary> public class Hash : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The type of hash that was performed.</summary> [Newtonsoft.Json.JsonPropertyAttribute("type")] public virtual string Type { get; set; } /// <summary>The hash value.</summary> [Newtonsoft.Json.JsonPropertyAttribute("value")] public virtual string Value { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Response containing existing BuildTriggers.</summary> public class ListBuildTriggersResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>BuildTriggers for the project, sorted by create_time descending.</summary> [Newtonsoft.Json.JsonPropertyAttribute("triggers")] public virtual System.Collections.Generic.IList<BuildTrigger> Triggers { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Response including listed builds.</summary> public class ListBuildsResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Builds will be sorted by create_time, descending.</summary> [Newtonsoft.Json.JsonPropertyAttribute("builds")] public virtual System.Collections.Generic.IList<Build> Builds { get; set; } /// <summary>Token to receive the next page of results.</summary> [Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")] public virtual string NextPageToken { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The response message for Operations.ListOperations.</summary> public class ListOperationsResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The standard List next-page token.</summary> [Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")] public virtual string NextPageToken { get; set; } /// <summary>A list of operations that matches the specified filter in the request.</summary> [Newtonsoft.Json.JsonPropertyAttribute("operations")] public virtual System.Collections.Generic.IList<Operation> Operations { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>This resource represents a long-running operation that is the result of a network API call.</summary> public class Operation : Google.Apis.Requests.IDirectResponseSchema { /// <summary>If the value is `false`, it means the operation is still in progress. If `true`, the operation is /// completed, and either `error` or `response` is available.</summary> [Newtonsoft.Json.JsonPropertyAttribute("done")] public virtual System.Nullable<bool> Done { get; set; } /// <summary>The error result of the operation in case of failure or cancellation.</summary> [Newtonsoft.Json.JsonPropertyAttribute("error")] public virtual Status Error { get; set; } /// <summary>Service-specific metadata associated with the operation. It typically contains progress /// information and common metadata such as create time. Some services might not provide such metadata. Any /// method that returns a long-running operation should document the metadata type, if any.</summary> [Newtonsoft.Json.JsonPropertyAttribute("metadata")] public virtual System.Collections.Generic.IDictionary<string,object> Metadata { get; set; } /// <summary>The server-assigned name, which is only unique within the same service that originally returns it. /// If you use the default HTTP mapping, the `name` should have the format of /// `operations/some/unique/name`.</summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary>The normal response of the operation in case of success. If the original method returns no data on /// success, such as `Delete`, the response is `google.protobuf.Empty`. If the original method is standard /// `Get`/`Create`/`Update`, the response should be the resource. For other methods, the response should have /// the type `XxxResponse`, where `Xxx` is the original method name. For example, if the original method name /// is `TakeSnapshot()`, the inferred response type is `TakeSnapshotResponse`.</summary> [Newtonsoft.Json.JsonPropertyAttribute("response")] public virtual System.Collections.Generic.IDictionary<string,object> Response { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>RepoSource describes the location of the source in a Google Cloud Source Repository.</summary> public class RepoSource : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Name of the branch to build.</summary> [Newtonsoft.Json.JsonPropertyAttribute("branchName")] public virtual string BranchName { get; set; } /// <summary>Explicit commit SHA to build.</summary> [Newtonsoft.Json.JsonPropertyAttribute("commitSha")] public virtual string CommitSha { get; set; } /// <summary>Directory, relative to the source root, in which to run the build. /// /// This must be a relative path. If a step's dir is specified and is an absolute path, this value is ignored /// for that step's execution.</summary> [Newtonsoft.Json.JsonPropertyAttribute("dir")] public virtual string Dir { get; set; } /// <summary>ID of the project that owns the repo. If omitted, the project ID requesting the build is /// assumed.</summary> [Newtonsoft.Json.JsonPropertyAttribute("projectId")] public virtual string ProjectId { get; set; } /// <summary>Name of the repo. If omitted, the name "default" is assumed.</summary> [Newtonsoft.Json.JsonPropertyAttribute("repoName")] public virtual string RepoName { get; set; } /// <summary>Name of the tag to build.</summary> [Newtonsoft.Json.JsonPropertyAttribute("tagName")] public virtual string TagName { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Results describes the artifacts created by the build pipeline.</summary> public class Results : Google.Apis.Requests.IDirectResponseSchema { /// <summary>List of build step digests, in order corresponding to build step indices.</summary> [Newtonsoft.Json.JsonPropertyAttribute("buildStepImages")] public virtual System.Collections.Generic.IList<string> BuildStepImages { get; set; } /// <summary>Images that were built as a part of the build.</summary> [Newtonsoft.Json.JsonPropertyAttribute("images")] public virtual System.Collections.Generic.IList<BuiltImage> Images { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>RetryBuildRequest specifies a build to retry.</summary> public class RetryBuildRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Secret pairs a set of secret environment variables containing encrypted values with the Cloud KMS key /// to use to decrypt the value.</summary> public class Secret : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Cloud KMS key name to use to decrypt these envs.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kmsKeyName")] public virtual string KmsKeyName { get; set; } /// <summary>Map of environment variable name to its encrypted value. /// /// Secret environment variables must be unique across all of a build's secrets, and must be used by at least /// one build step. Values can be at most 1 KB in size. There can be at most ten secret values across all of a /// build's secrets.</summary> [Newtonsoft.Json.JsonPropertyAttribute("secretEnv")] public virtual System.Collections.Generic.IDictionary<string,string> SecretEnv { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Source describes the location of the source in a supported storage service.</summary> public class Source : Google.Apis.Requests.IDirectResponseSchema { /// <summary>If provided, get source from this location in a Cloud Repo.</summary> [Newtonsoft.Json.JsonPropertyAttribute("repoSource")] public virtual RepoSource RepoSource { get; set; } /// <summary>If provided, get the source from this location in Google Cloud Storage.</summary> [Newtonsoft.Json.JsonPropertyAttribute("storageSource")] public virtual StorageSource StorageSource { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Provenance of the source. Ways to find the original source, or verify that some source was used for /// this build.</summary> public class SourceProvenance : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Hash(es) of the build source, which can be used to verify that the original source integrity was /// maintained in the build. Note that FileHashes will only be populated if BuildOptions has requested a /// SourceProvenanceHash. /// /// The keys to this map are file paths used as build source and the values contain the hash values for those /// files. /// /// If the build source came in a single package such as a gzipped tarfile (.tar.gz), the FileHash will be for /// the single path to that file. @OutputOnly</summary> [Newtonsoft.Json.JsonPropertyAttribute("fileHashes")] public virtual System.Collections.Generic.IDictionary<string,FileHashes> FileHashes { get; set; } /// <summary>A copy of the build's source.repo_source, if exists, with any revisions resolved.</summary> [Newtonsoft.Json.JsonPropertyAttribute("resolvedRepoSource")] public virtual RepoSource ResolvedRepoSource { get; set; } /// <summary>A copy of the build's source.storage_source, if exists, with any generations resolved.</summary> [Newtonsoft.Json.JsonPropertyAttribute("resolvedStorageSource")] public virtual StorageSource ResolvedStorageSource { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The `Status` type defines a logical error model that is suitable for different programming /// environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). The error model /// is designed to be: /// /// - Simple to use and understand for most users - Flexible enough to meet unexpected needs /// /// # Overview /// /// The `Status` message contains three pieces of data: error code, error message, and error details. The error code /// should be an enum value of google.rpc.Code, but it may accept additional error codes if needed. The error /// message should be a developer-facing English message that helps developers *understand* and *resolve* the error. /// If a localized user-facing error message is needed, put the localized message in the error details or localize /// it in the client. The optional error details may contain arbitrary information about the error. There is a /// predefined set of error detail types in the package `google.rpc` that can be used for common error conditions. /// /// # Language mapping /// /// The `Status` message is the logical representation of the error model, but it is not necessarily the actual wire /// format. When the `Status` message is exposed in different client libraries and different wire protocols, it can /// be mapped differently. For example, it will likely be mapped to some exceptions in Java, but more likely mapped /// to some error codes in C. /// /// # Other uses /// /// The error model and the `Status` message can be used in a variety of environments, either with or without APIs, /// to provide a consistent developer experience across different environments. /// /// Example uses of this error model include: /// /// - Partial errors. If a service needs to return partial errors to the client, it may embed the `Status` in the /// normal response to indicate the partial errors. /// /// - Workflow errors. A typical workflow has multiple steps. Each step may have a `Status` message for error /// reporting. /// /// - Batch operations. If a client uses batch request and batch response, the `Status` message should be used /// directly inside batch response, one for each error sub-response. /// /// - Asynchronous operations. If an API call embeds asynchronous operation results in its response, the status of /// those operations should be represented directly using the `Status` message. /// /// - Logging. If some API errors are stored in logs, the message `Status` could be used directly after any /// stripping needed for security/privacy reasons.</summary> public class Status : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The status code, which should be an enum value of google.rpc.Code.</summary> [Newtonsoft.Json.JsonPropertyAttribute("code")] public virtual System.Nullable<int> Code { get; set; } /// <summary>A list of messages that carry the error details. There is a common set of message types for APIs /// to use.</summary> [Newtonsoft.Json.JsonPropertyAttribute("details")] public virtual System.Collections.Generic.IList<System.Collections.Generic.IDictionary<string,object>> Details { get; set; } /// <summary>A developer-facing error message, which should be in English. Any user-facing error message should /// be localized and sent in the google.rpc.Status.details field, or localized by the client.</summary> [Newtonsoft.Json.JsonPropertyAttribute("message")] public virtual string Message { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>StorageSource describes the location of the source in an archive file in Google Cloud /// Storage.</summary> public class StorageSource : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Google Cloud Storage bucket containing source (see [Bucket Name /// Requirements](https://cloud.google.com/storage/docs/bucket-naming#requirements)).</summary> [Newtonsoft.Json.JsonPropertyAttribute("bucket")] public virtual string Bucket { get; set; } /// <summary>Google Cloud Storage generation for the object. If the generation is omitted, the latest generation /// will be used.</summary> [Newtonsoft.Json.JsonPropertyAttribute("generation")] public virtual System.Nullable<long> Generation { get; set; } /// <summary>Google Cloud Storage object containing source. /// /// This object must be a gzipped archive file (.tar.gz) containing source to build.</summary> [Newtonsoft.Json.JsonPropertyAttribute("object")] public virtual string Object__ { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Stores start and end times for a build execution phase.</summary> public class TimeSpan : Google.Apis.Requests.IDirectResponseSchema { /// <summary>End of time span.</summary> [Newtonsoft.Json.JsonPropertyAttribute("endTime")] public virtual object EndTime { get; set; } /// <summary>Start of time span.</summary> [Newtonsoft.Json.JsonPropertyAttribute("startTime")] public virtual object StartTime { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Volume describes a Docker container volume which is mounted into build steps in order to persist files /// across build step execution.</summary> public class Volume : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Name of the volume to mount. /// /// Volume names must be unique per build step and must be valid names for Docker volumes. Each named volume /// must be used by at least two build steps.</summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary>Path at which to mount the volume. /// /// Paths must be absolute and cannot conflict with other volume paths on the same build step or with certain /// reserved volume paths.</summary> [Newtonsoft.Json.JsonPropertyAttribute("path")] public virtual string Path { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
45.964852
166
0.574723
[ "Apache-2.0" ]
Ramkarthik/google-api-dotnet-client
Src/Generated/Google.Apis.CloudBuild.v1/Google.Apis.CloudBuild.v1.cs
107,236
C#
using System; using System.Threading.Tasks; using Newtonsoft.Json; namespace TdLib { /// <summary> /// Autogenerated TDLib APIs /// </summary> public static partial class TdApi { /// <summary> /// Returns all user contacts /// </summary> public class GetContacts : Function<Users> { /// <summary> /// Data type for serialization /// </summary> [JsonProperty("@type")] public override string DataType { get; set; } = "getContacts"; /// <summary> /// Extra data attached to the function /// </summary> [JsonProperty("@extra")] public override string Extra { get; set; } } /// <summary> /// Returns all user contacts /// </summary> public static Task<Users> GetContactsAsync( this Client client) { return client.ExecuteAsync(new GetContacts { }); } } }
25.365854
74
0.502885
[ "MIT" ]
0x25CBFC4F/tdsharp
TDLib.Api/Functions/GetContacts.cs
1,040
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 iot-2015-05-28.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.IoT.Model { /// <summary> /// A target to which an alert is sent when a security profile behavior is violated. /// </summary> public partial class SecurityProfileTarget { private string _arn; /// <summary> /// Gets and sets the property Arn. /// <para> /// The ARN of the security profile. /// </para> /// </summary> [AWSProperty(Required=true)] public string Arn { get { return this._arn; } set { this._arn = value; } } // Check to see if Arn property is set internal bool IsSetArn() { return this._arn != null; } } }
27.517241
101
0.639098
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/IoT/Generated/Model/SecurityProfileTarget.cs
1,596
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using WACines.Infraestructura; namespace WACines.Controller { public interface ISalaController { public Task<ActionResult<Sala>> FindById(int id); public Task<IEnumerable<Sala>> Find(); public Task<ActionResult<Sala>> Desactivar(int id); } }
27
59
0.738272
[ "Apache-2.0" ]
Weenhallo/ejercicio015
WACines/Controller/ISalaController.cs
407
C#
using System.Threading; using System.Threading.Tasks; using API.Client; using DLCS.HydraModel; using Hydra.Collections; using MediatR; namespace Portal.Features.Users.Requests { /// <summary> /// Get all PortalUsers for current customer /// </summary> public class GetPortalUsers : IRequest<HydraCollection<PortalUser>?> { } public class GetPortalUsersHandler : IRequestHandler<GetPortalUsers, HydraCollection<PortalUser>?> { private readonly IDlcsClient dlcsClient; public GetPortalUsersHandler(IDlcsClient dlcsClient) { this.dlcsClient = dlcsClient; } public Task<HydraCollection<PortalUser>?> Handle(GetPortalUsers request, CancellationToken cancellationToken) { var portalUsers = dlcsClient.GetPortalUsers(); return portalUsers; } } }
28.5625
118
0.655361
[ "MIT" ]
dlcs/protagonist
Portal/Features/Users/Requests/GetPortalUsers.cs
916
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210 { using Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.PowerShell; /// <summary> /// A PowerShell PSTypeConverter to support converting to an instance of <see cref="ResumeJobParams" /> /// </summary> public partial class ResumeJobParamsTypeConverter : global::System.Management.Automation.PSTypeConverter { /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c>. /// </returns> public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="ResumeJobParams" /// /> type.</param> /// <returns> /// <c>true</c> if the instance could be converted to a <see cref="ResumeJobParams" /> type, otherwise <c>false</c> /// </returns> public static bool CanConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return true; } global::System.Type type = sourceValue.GetType(); if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { // we say yest to PSObjects return true; } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { // we say yest to Hashtables/dictionaries return true; } try { if (null != sourceValue.ToJsonString()) { return true; } } catch { // Not one of our objects } try { string text = sourceValue.ToString()?.Trim(); return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonType.Object; } catch { // Doesn't look like it can be treated as JSON } return false; } /// <summary> /// Determines if the <see cref="sourceValue" /> parameter can be converted to the <see cref="destinationType" /> parameter /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c> /// </returns> public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; /// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns> /// an instance of <see cref="ResumeJobParams" />, or <c>null</c> if there is no suitable conversion. /// </returns> public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); /// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the value to convert into an instance of <see cref="ResumeJobParams" />.</param> /// <returns> /// an instance of <see cref="ResumeJobParams" />, or <c>null</c> if there is no suitable conversion. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IResumeJobParams ConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return null; } global::System.Type type = sourceValue.GetType(); if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IResumeJobParams).IsAssignableFrom(type)) { return sourceValue; } try { return ResumeJobParams.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; } catch { // Unable to use JSON pattern } if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { return ResumeJobParams.DeserializeFromPSObject(sourceValue); } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { return ResumeJobParams.DeserializeFromDictionary(sourceValue); } return null; } /// <summary>NotImplemented -- this will return <c>null</c></summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns>will always return <c>null</c>.</returns> public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; } }
51.239437
245
0.580951
[ "MIT" ]
AverageDesigner/azure-powershell
src/Migrate/generated/api/Models/Api20210210/ResumeJobParams.TypeConverter.cs
7,135
C#
using System; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using HuaweiCloud.SDK.Core; namespace HuaweiCloud.SDK.As.V1.Model { /// <summary> /// 伸缩策略 /// </summary> public class ScalingV1PolicyDetail { /// <summary> /// 伸缩策略类型:ALARM:告警策略,此时alarm_id有返回,scheduled_policy不会返回。SCHEDULED:定时策略,此时alarm_id不会返回,scheduled_policy有返回,并且recurrence_type、recurrence_value、start_time和end_time不会返回。RECURRENCE:周期策略,此时alarm_id不会返回,scheduled_policy有返回,并且recurrence_type、recurrence_value、start_time和end_time有返回。 /// </summary> /// <value>伸缩策略类型:ALARM:告警策略,此时alarm_id有返回,scheduled_policy不会返回。SCHEDULED:定时策略,此时alarm_id不会返回,scheduled_policy有返回,并且recurrence_type、recurrence_value、start_time和end_time不会返回。RECURRENCE:周期策略,此时alarm_id不会返回,scheduled_policy有返回,并且recurrence_type、recurrence_value、start_time和end_time有返回。</value> [JsonConverter(typeof(EnumClassConverter<ScalingPolicyTypeEnum>))] public class ScalingPolicyTypeEnum { /// <summary> /// Enum ALARM for value: ALARM /// </summary> public static readonly ScalingPolicyTypeEnum ALARM = new ScalingPolicyTypeEnum("ALARM"); /// <summary> /// Enum SCHEDULED for value: SCHEDULED /// </summary> public static readonly ScalingPolicyTypeEnum SCHEDULED = new ScalingPolicyTypeEnum("SCHEDULED"); /// <summary> /// Enum RECURRENCE for value: RECURRENCE /// </summary> public static readonly ScalingPolicyTypeEnum RECURRENCE = new ScalingPolicyTypeEnum("RECURRENCE"); private static readonly Dictionary<string, ScalingPolicyTypeEnum> StaticFields = new Dictionary<string, ScalingPolicyTypeEnum>() { { "ALARM", ALARM }, { "SCHEDULED", SCHEDULED }, { "RECURRENCE", RECURRENCE }, }; private string Value; public ScalingPolicyTypeEnum(string value) { Value = value; } public static ScalingPolicyTypeEnum FromValue(string value) { if(value == null){ return null; } if (StaticFields.ContainsKey(value)) { return StaticFields[value]; } return null; } public string GetValue() { return Value; } public override string ToString() { return $"{Value}"; } public override int GetHashCode() { return this.Value.GetHashCode(); } public override bool Equals(object obj) { if (obj == null) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (this.Equals(obj as ScalingPolicyTypeEnum)) { return true; } return false; } public bool Equals(ScalingPolicyTypeEnum obj) { if ((object)obj == null) { return false; } return StringComparer.OrdinalIgnoreCase.Equals(this.Value, obj.Value); } public static bool operator ==(ScalingPolicyTypeEnum a, ScalingPolicyTypeEnum b) { if (System.Object.ReferenceEquals(a, b)) { return true; } if ((object)a == null) { return false; } return a.Equals(b); } public static bool operator !=(ScalingPolicyTypeEnum a, ScalingPolicyTypeEnum b) { return !(a == b); } } /// <summary> /// 伸缩组ID。 /// </summary> [JsonProperty("scaling_group_id", NullValueHandling = NullValueHandling.Ignore)] public string ScalingGroupId { get; set; } /// <summary> /// 伸缩策略名称。 /// </summary> [JsonProperty("scaling_policy_name", NullValueHandling = NullValueHandling.Ignore)] public string ScalingPolicyName { get; set; } /// <summary> /// 伸缩策略ID。 /// </summary> [JsonProperty("scaling_policy_id", NullValueHandling = NullValueHandling.Ignore)] public string ScalingPolicyId { get; set; } /// <summary> /// 伸缩策略状态 INSERVICE:已启用 PAUSED:已停用 EXECUTING:执行中 /// </summary> [JsonProperty("policy_status", NullValueHandling = NullValueHandling.Ignore)] public string PolicyStatus { get; set; } /// <summary> /// 伸缩策略类型:ALARM:告警策略,此时alarm_id有返回,scheduled_policy不会返回。SCHEDULED:定时策略,此时alarm_id不会返回,scheduled_policy有返回,并且recurrence_type、recurrence_value、start_time和end_time不会返回。RECURRENCE:周期策略,此时alarm_id不会返回,scheduled_policy有返回,并且recurrence_type、recurrence_value、start_time和end_time有返回。 /// </summary> [JsonProperty("scaling_policy_type", NullValueHandling = NullValueHandling.Ignore)] public ScalingPolicyTypeEnum ScalingPolicyType { get; set; } /// <summary> /// 告警ID,即告警规则的ID,当scaling_policy_type为ALARM时该项必选,此时scheduled_policy不生效。创建告警策略成功后,会自动为该告警ID对应的告警规则的alarm_actions字段增加类型为autoscaling的告警触发动作。告警ID通过查询云监控告警规则列表获取,详见《云监控API参考》的“查询告警规则列表”。 /// </summary> [JsonProperty("alarm_id", NullValueHandling = NullValueHandling.Ignore)] public string AlarmId { get; set; } /// <summary> /// /// </summary> [JsonProperty("scheduled_policy", NullValueHandling = NullValueHandling.Ignore)] public ScheduledPolicy ScheduledPolicy { get; set; } /// <summary> /// /// </summary> [JsonProperty("scaling_policy_action", NullValueHandling = NullValueHandling.Ignore)] public ScalingPolicyActionV1 ScalingPolicyAction { get; set; } /// <summary> /// 冷却时间,取值范围0-86400,默认为300,单位是秒。 /// </summary> [JsonProperty("cool_down_time", NullValueHandling = NullValueHandling.Ignore)] public int? CoolDownTime { get; set; } /// <summary> /// 创建伸缩策略时间,遵循UTC时间。 /// </summary> [JsonProperty("create_time", NullValueHandling = NullValueHandling.Ignore)] public string CreateTime { get; set; } /// <summary> /// Get the string /// </summary> public override string ToString() { var sb = new StringBuilder(); sb.Append("class ScalingV1PolicyDetail {\n"); sb.Append(" scalingGroupId: ").Append(ScalingGroupId).Append("\n"); sb.Append(" scalingPolicyName: ").Append(ScalingPolicyName).Append("\n"); sb.Append(" scalingPolicyId: ").Append(ScalingPolicyId).Append("\n"); sb.Append(" policyStatus: ").Append(PolicyStatus).Append("\n"); sb.Append(" scalingPolicyType: ").Append(ScalingPolicyType).Append("\n"); sb.Append(" alarmId: ").Append(AlarmId).Append("\n"); sb.Append(" scheduledPolicy: ").Append(ScheduledPolicy).Append("\n"); sb.Append(" scalingPolicyAction: ").Append(ScalingPolicyAction).Append("\n"); sb.Append(" coolDownTime: ").Append(CoolDownTime).Append("\n"); sb.Append(" createTime: ").Append(CreateTime).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns true if objects are equal /// </summary> public override bool Equals(object input) { return this.Equals(input as ScalingV1PolicyDetail); } /// <summary> /// Returns true if objects are equal /// </summary> public bool Equals(ScalingV1PolicyDetail input) { if (input == null) return false; return ( this.ScalingGroupId == input.ScalingGroupId || (this.ScalingGroupId != null && this.ScalingGroupId.Equals(input.ScalingGroupId)) ) && ( this.ScalingPolicyName == input.ScalingPolicyName || (this.ScalingPolicyName != null && this.ScalingPolicyName.Equals(input.ScalingPolicyName)) ) && ( this.ScalingPolicyId == input.ScalingPolicyId || (this.ScalingPolicyId != null && this.ScalingPolicyId.Equals(input.ScalingPolicyId)) ) && ( this.PolicyStatus == input.PolicyStatus || (this.PolicyStatus != null && this.PolicyStatus.Equals(input.PolicyStatus)) ) && ( this.ScalingPolicyType == input.ScalingPolicyType || (this.ScalingPolicyType != null && this.ScalingPolicyType.Equals(input.ScalingPolicyType)) ) && ( this.AlarmId == input.AlarmId || (this.AlarmId != null && this.AlarmId.Equals(input.AlarmId)) ) && ( this.ScheduledPolicy == input.ScheduledPolicy || (this.ScheduledPolicy != null && this.ScheduledPolicy.Equals(input.ScheduledPolicy)) ) && ( this.ScalingPolicyAction == input.ScalingPolicyAction || (this.ScalingPolicyAction != null && this.ScalingPolicyAction.Equals(input.ScalingPolicyAction)) ) && ( this.CoolDownTime == input.CoolDownTime || (this.CoolDownTime != null && this.CoolDownTime.Equals(input.CoolDownTime)) ) && ( this.CreateTime == input.CreateTime || (this.CreateTime != null && this.CreateTime.Equals(input.CreateTime)) ); } /// <summary> /// Get hash code /// </summary> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.ScalingGroupId != null) hashCode = hashCode * 59 + this.ScalingGroupId.GetHashCode(); if (this.ScalingPolicyName != null) hashCode = hashCode * 59 + this.ScalingPolicyName.GetHashCode(); if (this.ScalingPolicyId != null) hashCode = hashCode * 59 + this.ScalingPolicyId.GetHashCode(); if (this.PolicyStatus != null) hashCode = hashCode * 59 + this.PolicyStatus.GetHashCode(); if (this.ScalingPolicyType != null) hashCode = hashCode * 59 + this.ScalingPolicyType.GetHashCode(); if (this.AlarmId != null) hashCode = hashCode * 59 + this.AlarmId.GetHashCode(); if (this.ScheduledPolicy != null) hashCode = hashCode * 59 + this.ScheduledPolicy.GetHashCode(); if (this.ScalingPolicyAction != null) hashCode = hashCode * 59 + this.ScalingPolicyAction.GetHashCode(); if (this.CoolDownTime != null) hashCode = hashCode * 59 + this.CoolDownTime.GetHashCode(); if (this.CreateTime != null) hashCode = hashCode * 59 + this.CreateTime.GetHashCode(); return hashCode; } } } }
38.561514
298
0.538531
[ "Apache-2.0" ]
cnblogs/huaweicloud-sdk-net-v3
Services/As/V1/Model/ScalingV1PolicyDetail.cs
13,034
C#
using Mahjong.Properties; using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace Mahjong { public partial class MainForm : AForm { #region Members private MainFormModel _model; private MainFormControler _controler; private Dictionary<RadioButton, EnumTileFamily> _tileFamilyByRadioButtons; private Dictionary<EnumTileFamily, RadioButton> _radioButtonByTileFamilys; private Dictionary<EnumTileFamily, GroupBox> _groupBoxByTileFamilys; private Dictionary<RadioButton, EnumTileSubNumber> _tileSubNumberByRadioButtons; private Dictionary<EnumTileSubNumber, List<RadioButton>> _radionButtonsByTileSubNumbers; #endregion Members #region Init private MainForm() { InitializeComponent(); } public MainForm(MainFormModel model) : this(model, new MainFormControler(model)) { } public MainForm(MainFormModel model, MainFormControler controler) : this() { if (model == null) throw new ArgumentNullException(); _model = model; _controler = controler; } protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (_model == null) return; // Tile Family radionButtons const int constOffsetX = 6; const int constOffsetY = 19; const int constStepY = 42 - constOffsetY; int x = constOffsetX; int y = constOffsetY; _tileFamilyByRadioButtons = new Dictionary<RadioButton, EnumTileFamily> { }; _radioButtonByTileFamilys = new Dictionary<EnumTileFamily, RadioButton> { }; foreach (EnumTileFamily tileFamily in Enum.GetValues(typeof(EnumTileFamily))) { if (tileFamily == EnumTileFamily.Base) continue; RadioButton radioButton = new RadioButton() { Name = tileFamily.ToString(), Location = new Point(x, y), Text = tileFamily.ToString(), }; radioButton.CheckedChanged += TileFamilyRadioButton_CheckedChanged; _groupBoxTileFamily.Controls.Add(radioButton); _tileFamilyByRadioButtons[radioButton] = tileFamily; _radioButtonByTileFamilys[tileFamily] = radioButton; y += constStepY; } _groupBoxTileFamily.Height = y + constOffsetY; // Tile sub familly Point point = new Point(_groupBoxTileFamily.Right + 5, _groupBoxTileFamily.Top); Size size = _groupBoxTileFamily.Size; _groupBoxByTileFamilys = new Dictionary<EnumTileFamily, GroupBox> { }; _tileSubNumberByRadioButtons = new Dictionary<RadioButton, EnumTileSubNumber> { }; _radionButtonsByTileSubNumbers = new Dictionary<EnumTileSubNumber, List<RadioButton>> { }; foreach (EnumTileFamily tileFamily in Enum.GetValues(typeof(EnumTileFamily))) { if (tileFamily == EnumTileFamily.None || tileFamily == EnumTileFamily.Base) continue; GroupBox groupBox = new GroupBox() { Text = String.Empty, Location = point, Size = size, Visible = false, }; this.Controls.Add(groupBox); _groupBoxByTileFamilys[tileFamily] = groupBox; x = constOffsetX; y = constOffsetY; List<EnumTileSubNumber> tileSubNumbers = TileSetFactory.TileSet.TileByTileSubTypeByTileFamilies[tileFamily].Keys .ToList(); if (!tileSubNumbers.Any(tsn => tsn == EnumTileSubNumber.None)) tileSubNumbers.Insert(0, EnumTileSubNumber.None); foreach (EnumTileSubNumber tileSubNumber in tileSubNumbers) { RadioButton radioButton = new RadioButton() { Name = tileFamily.ToString(), Location = new Point(x, y), Text = tileSubNumber.ToString(), }; radioButton.CheckedChanged += TileSubNumberRadioButton_CheckedChanged; groupBox.Controls.Add(radioButton); _tileSubNumberByRadioButtons[radioButton] = tileSubNumber; List<RadioButton> radioButtons; if (!_radionButtonsByTileSubNumbers.TryGetValue(tileSubNumber, out radioButtons)) { radioButtons = new List<RadioButton> { }; _radionButtonsByTileSubNumbers[tileSubNumber] = radioButtons; } radioButtons.Add(radioButton); y += constStepY; } groupBox.Height = y + constOffsetY; } // connect model MainFormModel model = _model; _model = null; Model = model; } #endregion Init #region Refresh private void RefreshUIState() { BeginUpdate(); EnumTileType tileType = EnumTileType.None; if (_model != null) tileType = _model.CurrentTile; _buttonStartOrNext.Text = tileType == EnumTileType.None ? "Sart" : "Next"; bool isGBEnable = tileType != EnumTileType.None; _groupBoxTileFamily.Enabled = isGBEnable; _groupBoxByTileFamilys.Values.Foreach(gb => gb.Enabled = isGBEnable); EndUpdate(); } private void RefreshPictureBox() { BeginUpdate(); EnumTileType tileType = EnumTileType.None; if (_model != null) tileType = _model.CurrentTile; Image image = null; Tile tile; if (TileSetFactory.TileSet.TileByTileTypes.TryGetValue(tileType, out tile)) image = tile.Image; _pictureBox.Image = image; EndUpdate(); } private void RefreshGroupBoxTileFamily() { BeginUpdate(); EnumTileFamily tileFamily = EnumTileFamily.None; if (_model != null) tileFamily = _model.SelectedTileFamily; RadioButton radioButton; if (_radioButtonByTileFamilys.TryGetValue(tileFamily, out radioButton)) radioButton.Checked = true; EndUpdate(); } private void RefreshGroupBoxSubFamily() { BeginUpdate(); EnumTileFamily tileFamily = EnumTileFamily.None; if (_model != null) tileFamily = _model.SelectedTileFamily; foreach (var gb in _groupBoxByTileFamilys.Values) { gb.Visible = false; } GroupBox groupBox; if (_groupBoxByTileFamilys.TryGetValue(tileFamily, out groupBox)) groupBox.Visible = true; EndUpdate(); } private void RefreshRadioButtonTileSubNumber() { BeginUpdate(); EnumTileSubNumber tileSubNumber = EnumTileSubNumber.None; if (_model != null) tileSubNumber = _model.SelectedTileSubNumber; List<RadioButton> radioButtons; if (_radionButtonsByTileSubNumbers.TryGetValue(tileSubNumber, out radioButtons)) { foreach (var radioButton in radioButtons) { radioButton.Checked = true; } } EndUpdate(); } private void RefresPictureBoxResult() { bool? result = null; if (_model != null) result = _model.Result; Image image = result == null ? null : result.Value ? Resources.ok : Resources.no; _pictureBoxResult.Image = image; } #endregion Refresh #region Model public MainFormModel Model { get { return _model; } set { if (_model != null) _model.PropertyChanged -= _model_PropertyChanged; _model = value; if (_model != null) _model.PropertyChanged += _model_PropertyChanged; UpdateModel(); } } private void _model_PropertyChanged(object sender, PropertyChangedEventArgs e) { EnsureSync(() => { switch (e.PropertyName) { case MainFormModel.ConstPropertyNameCurrentTile: UpdateCurrentTile(); break; case MainFormModel.ConstPropertyNameSelectedTileFamily: UpdateSelectedTileFamily(); break; case MainFormModel.ConstPropertyNameSelectedTileSubNumber: UpdateSelectedTileSubNumber(); break; case MainFormModel.ConstPropertyNameResult: UpdateResult(); break; } }); } private void UpdateModel() { BeginUpdate(); UpdateCurrentTile(); UpdateSelectedTileFamily(); UpdateSelectedTileSubNumber(); UpdateResult(); EndUpdate(); } private void UpdateCurrentTile() { RefreshUIState(); RefreshPictureBox(); } private void UpdateSelectedTileFamily() { BeginUpdate(); RefreshGroupBoxTileFamily(); RefreshGroupBoxSubFamily(); EndUpdate(); } private void UpdateSelectedTileSubNumber() { RefreshRadioButtonTileSubNumber(); } private void UpdateResult() { RefreshUIState(); RefresPictureBoxResult(); } #endregion Model #region User input private void TileFamilyRadioButton_CheckedChanged(object sender, EventArgs e) { if (IsUpdating) return; EnumTileFamily tileFamily; RadioButton radioButton = sender as RadioButton; if (!radioButton.Checked) return; if (!_tileFamilyByRadioButtons.TryGetValue(radioButton, out tileFamily)) tileFamily = EnumTileFamily.None; _controler.SetSelectedTileFamily(tileFamily); } private void TileSubNumberRadioButton_CheckedChanged(object sender, EventArgs e) { if (IsUpdating) return; EnumTileSubNumber tileSubNumber; RadioButton radioButton = sender as RadioButton; if (!radioButton.Checked) return; if (!_tileSubNumberByRadioButtons.TryGetValue(radioButton, out tileSubNumber)) tileSubNumber = EnumTileSubNumber.None; _controler.SetSelectedTileSubNumberAndCheck(tileSubNumber); } private void _buttonStartOrNext_Click(object sender, EventArgs e) { _controler.Next(); } #endregion User input } }
32.097561
128
0.542215
[ "Unlicense" ]
blueneosky/Bag
Mahjong/Mahjong/MainForm.cs
11,846
C#
namespace BE_CustomerStore.Data { public class MemoryStore<T> : IStore<T> where T : class, IEntity { private readonly Dictionary<Guid, T> _data; public MemoryStore() { _data = new Dictionary<Guid, T>(); } public Task<Guid> Add(T newItem) { newItem.Id = Guid.NewGuid(); _data.Add(newItem.Id, newItem); return Task.FromResult(newItem.Id); } public Task<IEnumerable<T>> Get() { return Task.FromResult(_data.Values.AsEnumerable()); } public Task<IEnumerable<T>> Get(IQuery<T> query) { return Task.FromResult(query.Specify(_data.Values.AsQueryable()).AsEnumerable()); } } }
24.83871
93
0.546753
[ "Apache-2.0" ]
GuitaristJake3/SupermarketE2E
BE-CustomerStore/Data/MemoryStore.cs
772
C#
using NSuperTest; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Threading.Tasks; using FluentAssertions; using Moq; using Newtonsoft.Json; using NSuperTest.Tests.Models; using Xunit; using NSuperTest.Assertions; using NSuperTest.Models; namespace NSuperTest.Tests.Assertions { public class AssertionTests { HttpResponseMessage message; HttpRequestMessage request; //ITestBuilder builder; Mock<IHttpRequestClient> clientMock; IHttpRequestClient client; User user; public AssertionTests() { request = new HttpRequestMessage(); message = new HttpResponseMessage(); message.StatusCode = HttpStatusCode.OK; message.Content = new StringContent("Hello World"); message.Headers.Add("TestHeader", "Test"); user = new User { Name = "Peter", Age = 32, Id = 1 }; clientMock = new Mock<IHttpRequestClient>(); clientMock.Setup(c => c.AsyncMakeRequest(It.IsAny<HttpRequestMessage>())).ReturnsAsync(() => message); client = clientMock.Object; } [Fact] public async Task ShouldAssertStatusCodes() { var req = new HttpRequestMessage(); await client.AsyncMakeRequest(req).ExpectStatus(200); message.AssertStatusCode(200); } [Fact] public async Task ShouldAssertEnumStatusCode() { message.StatusCode = HttpStatusCode.PartialContent; await client.AsyncMakeRequest(request).ExpectStatus(HttpStatusCode.PartialContent); message.AssertStatusCode((int)HttpStatusCode.PartialContent); } // TODO : Do we want these back... //[Fact] //public void ShouldAssertOk() //{ // builder // .ExpectOk() // .End(); //} //[Fact] //public void ShouldAssertCreated() //{ // message.StatusCode = HttpStatusCode.Created; // builder // .ExpectCreated() // .End(); //} //[Fact] //public void ShouldAssertNotFound() //{ // message.StatusCode = HttpStatusCode.NotFound; // builder // .ExpectNotFound() // .End(); //} //[Fact] //public void ShouldAssertBadRequest() //{ // message.StatusCode = HttpStatusCode.BadRequest; // builder // .ExpectBadRequest() // .End(); //} //[Fact] //public void ShouldAssertUnauthorized() //{ // message.StatusCode = HttpStatusCode.Unauthorized; // builder // .ExpectUnauthorized() // .End(); //} //[Fact] //public void ShouldAssertForbidden() //{ // message.StatusCode = HttpStatusCode.Forbidden; // builder // .ExpectForbidden() // .End(); //} //[Fact] //public void ShouldAssertRedirect() //{ // message.StatusCode = HttpStatusCode.Redirect; // builder // .ExpectRedirect() // .End(); //} [Fact] public void ShouldThrowAssertStatusCodesUnauthorized() { Func<Task> action = async () => await client.AsyncMakeRequest(request).ExpectStatus(401); action.Should().Throw<Exception>() .WithMessage("Expected status code Unauthorized (401) but got Ok (200)"); } [Fact] public void ShouldThrowAssertStatusCodesForbidden() { Func<Task> action = async () => await client.AsyncMakeRequest(request).ExpectStatus(403); action.Should().Throw<Exception>() .WithMessage("Expected status code Forbidden (403) but got Ok (200)"); } [Fact] public async Task ShouldAssertStatusAndCallback() { await client.AsyncMakeRequest(request) .ExpectStatus(200) .ExpectResponse(resp => { resp.StatusCode.Should().BeEquivalentTo<HttpStatusCode>(HttpStatusCode.OK); }); } [Fact] public async Task ShouldAssertBody() { await client.AsyncMakeRequest(request) .ExpectStatus(200) .ExpectBody("Hello World"); } [Fact] public void ShouldThrowBadBody() { Func<Task> a = async () => await client.AsyncMakeRequest(request) .ExpectBody("Goodbye World"); a.Should() .Throw<Exception>() .WithMessage("Expected body 'Goodbye World' but got 'Hello World'"); } [Fact] public async Task ShouldAssertBodyAndCallback() { await client.AsyncMakeRequest(request) .ExpectBody("Hello World") .ExpectResponse(resp => { resp.Content.ReadAsStringAsync().Result.Should().StartWith("H"); }); } [Fact] public async Task ShouldAssertHeaders() { await client.AsyncMakeRequest(request) .ExpectHeader("TestHeader", "Test"); } [Fact] public void ShouldThrowBadHeaderName() { Func<Task> a = async () => await client.AsyncMakeRequest(request).ExpectHeader("Content", "100"); a.Should() .Throw<Exception>().WithMessage("Header 'Content' not found on response message"); } [Fact] public void ShouldThrowBadHeaderValue() { Func<Task> a = async () => await client.AsyncMakeRequest(request).ExpectHeader("TestHeader", "100"); a.Should() .Throw<Exception>().WithMessage("Header 'TestHeader' not found with value '100' on response message"); } [Fact] public async Task ShouldAssertHeaderWithCallback() { await client.AsyncMakeRequest(request) .ExpectHeader("TestHeader", "Test") .ExpectResponse(resp => { resp.Headers.GetValues("TestHeader").First().Should().BeSameAs("Test"); resp.Headers.GetValues("TestHeader").Should().HaveCount(1); }); } [Fact] public async Task ShouldAssertCallback() { await client.AsyncMakeRequest(request) .ExpectResponse(resp => { resp.Content.ReadAsStringAsync().Result.Should().Contain("Hello World"); resp.StatusCode.Should() .BeEquivalentTo<HttpStatusCode>(HttpStatusCode.OK); }); } [Fact] public async Task ShouldAssertAnObjectBody() { message.Content = new StringContent(JsonConvert.SerializeObject(user)); clientMock.Setup(c => c.AsyncMakeRequest(It.IsAny<HttpRequestMessage>())).ReturnsAsync(message); await client.AsyncMakeRequest(request) .ExpectBody(user, false); } [Fact] public async Task ShouldAssertBadRequest() { var messageBody = new BadRequestResponse { Errors = new ErrorList { { "Age", new List<string> { "Test" } } } }; message.StatusCode = HttpStatusCode.BadRequest; message.Content = new StringContent(JsonConvert.SerializeObject(messageBody)); clientMock.Setup(c => c.AsyncMakeRequest(It.IsAny<HttpRequestMessage>())).ReturnsAsync(message); await client.AsyncMakeRequest(request) .ExpectBadRequest(err => { err.Count().Should().Be(1); err["Age"].Should().BeEquivalentTo(new string[] { "Test" }); }); } [Fact] public void ShouldThrowBadObjectBody() { message.Content = new StringContent(JsonConvert.SerializeObject(user)); clientMock.Setup(c => c.AsyncMakeRequest(It.IsAny<HttpRequestMessage>())).ReturnsAsync(message); Func<Task> a = async () => await client.AsyncMakeRequest(request) .ExpectBody(new User { Name = "Tom", Age = 11, Id = 1 }); a.Should() .Throw<Exception>(); } [Fact] public async Task ShouldAssertAnObjectBodyAndCallback() { message.Content = new StringContent(JsonConvert.SerializeObject(user)); clientMock.Setup(c => c.AsyncMakeRequest(It.IsAny<HttpRequestMessage>())).ReturnsAsync(message); await client.AsyncMakeRequest(request) .ExpectBody(user, false) .ExpectResponse(resp => { resp.StatusCode.Should() .BeEquivalentTo<HttpStatusCode>(HttpStatusCode.OK); }); } } }
32.220736
119
0.520241
[ "MIT" ]
pshort/nsupertest
NSuperTest.Tests/Assertions/AssertionTests.cs
9,636
C#
#region Apache License // // 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. // #endregion using System; using System.Collections; using System.IO; using log4net.Core; using log4net.Layout.Pattern; using log4net.Util; using log4net.Util.PatternStringConverters; using AppDomainPatternConverter=log4net.Layout.Pattern.AppDomainPatternConverter; using DatePatternConverter=log4net.Layout.Pattern.DatePatternConverter; using IdentityPatternConverter=log4net.Layout.Pattern.IdentityPatternConverter; using PropertyPatternConverter=log4net.Layout.Pattern.PropertyPatternConverter; using UserNamePatternConverter=log4net.Layout.Pattern.UserNamePatternConverter; using UtcDatePatternConverter=log4net.Layout.Pattern.UtcDatePatternConverter; namespace log4net.Layout { /// <summary> /// A flexible layout configurable with pattern string. /// </summary> /// <remarks> /// <para> /// The goal of this class is to <see cref="M:PatternLayout.Format(TextWriter,LoggingEvent)"/> a /// <see cref="LoggingEvent"/> as a string. The results /// depend on the <i>conversion pattern</i>. /// </para> /// <para> /// The conversion pattern is closely related to the conversion /// pattern of the printf function in C. A conversion pattern is /// composed of literal text and format control expressions called /// <i>conversion specifiers</i>. /// </para> /// <para> /// <i>You are free to insert any literal text within the conversion /// pattern.</i> /// </para> /// <para> /// Each conversion specifier starts with a percent sign (%) and is /// followed by optional <i>format modifiers</i> and a <i>conversion /// pattern name</i>. The conversion pattern name specifies the type of /// data, e.g. logger, level, date, thread name. The format /// modifiers control such things as field width, padding, left and /// right justification. The following is a simple example. /// </para> /// <para> /// Let the conversion pattern be <b>"%-5level [%thread]: %message%newline"</b> and assume /// that the log4net environment was set to use a PatternLayout. Then the /// statements /// </para> /// <code lang="C#"> /// ILog log = LogManager.GetLogger(typeof(TestApp)); /// log.Debug("Message 1"); /// log.Warn("Message 2"); /// </code> /// <para>would yield the output</para> /// <code> /// DEBUG [main]: Message 1 /// WARN [main]: Message 2 /// </code> /// <para> /// Note that there is no explicit separator between text and /// conversion specifiers. The pattern parser knows when it has reached /// the end of a conversion specifier when it reads a conversion /// character. In the example above the conversion specifier /// <b>%-5level</b> means the level of the logging event should be left /// justified to a width of five characters. /// </para> /// <para> /// The recognized conversion pattern names are: /// </para> /// <list type="table"> /// <listheader> /// <term>Conversion Pattern Name</term> /// <description>Effect</description> /// </listheader> /// <item> /// <term>a</term> /// <description>Equivalent to <b>appdomain</b></description> /// </item> /// <item> /// <term>appdomain</term> /// <description> /// Used to output the friendly name of the AppDomain where the /// logging event was generated. /// </description> /// </item> /// <item> /// <term>aspnet-cache</term> /// <description> /// <para> /// Used to output all cache items in the case of <b>%aspnet-cache</b> or just one named item if used as <b>%aspnet-cache{key}</b> /// </para> /// <para> /// This pattern is not available for Compact Framework or Client Profile assemblies. /// </para> /// </description> /// </item> /// <item> /// <term>aspnet-context</term> /// <description> /// <para> /// Used to output all context items in the case of <b>%aspnet-context</b> or just one named item if used as <b>%aspnet-context{key}</b> /// </para> /// <para> /// This pattern is not available for Compact Framework or Client Profile assemblies. /// </para> /// </description> /// </item> /// <item> /// <term>aspnet-request</term> /// <description> /// <para> /// Used to output all request parameters in the case of <b>%aspnet-request</b> or just one named param if used as <b>%aspnet-request{key}</b> /// </para> /// <para> /// This pattern is not available for Compact Framework or Client Profile assemblies. /// </para> /// </description> /// </item> /// <item> /// <term>aspnet-session</term> /// <description> /// <para> /// Used to output all session items in the case of <b>%aspnet-session</b> or just one named item if used as <b>%aspnet-session{key}</b> /// </para> /// <para> /// This pattern is not available for Compact Framework or Client Profile assemblies. /// </para> /// </description> /// </item> /// <item> /// <term>c</term> /// <description>Equivalent to <b>logger</b></description> /// </item> /// <item> /// <term>C</term> /// <description>Equivalent to <b>type</b></description> /// </item> /// <item> /// <term>class</term> /// <description>Equivalent to <b>type</b></description> /// </item> /// <item> /// <term>d</term> /// <description>Equivalent to <b>date</b></description> /// </item> /// <item> /// <term>date</term> /// <description> /// <para> /// Used to output the date of the logging event in the local time zone. /// To output the date in universal time use the <c>%utcdate</c> pattern. /// The date conversion /// specifier may be followed by a <i>date format specifier</i> enclosed /// between braces. For example, <b>%date{HH:mm:ss,fff}</b> or /// <b>%date{dd MMM yyyy HH:mm:ss,fff}</b>. If no date format specifier is /// given then ISO8601 format is /// assumed (<see cref="log4net.DateFormatter.Iso8601DateFormatter"/>). /// </para> /// <para> /// The date format specifier admits the same syntax as the /// time pattern string of the <see cref="M:DateTime.ToString(string)"/>. /// </para> /// <para> /// For better results it is recommended to use the log4net date /// formatters. These can be specified using one of the strings /// "ABSOLUTE", "DATE" and "ISO8601" for specifying /// <see cref="log4net.DateFormatter.AbsoluteTimeDateFormatter"/>, /// <see cref="log4net.DateFormatter.DateTimeDateFormatter"/> and respectively /// <see cref="log4net.DateFormatter.Iso8601DateFormatter"/>. For example, /// <b>%date{ISO8601}</b> or <b>%date{ABSOLUTE}</b>. /// </para> /// <para> /// These dedicated date formatters perform significantly /// better than <see cref="M:DateTime.ToString(string)"/>. /// </para> /// </description> /// </item> /// <item> /// <term>exception</term> /// <description> /// <para> /// Used to output the exception passed in with the log message. /// </para> /// <para> /// If an exception object is stored in the logging event /// it will be rendered into the pattern output with a /// trailing newline. /// If there is no exception then nothing will be output /// and no trailing newline will be appended. /// It is typical to put a newline before the exception /// and to have the exception as the last data in the pattern. /// </para> /// </description> /// </item> /// <item> /// <term>F</term> /// <description>Equivalent to <b>file</b></description> /// </item> /// <item> /// <term>file</term> /// <description> /// <para> /// Used to output the file name where the logging request was /// issued. /// </para> /// <para> /// <b>WARNING</b> Generating caller location information is /// extremely slow. Its use should be avoided unless execution speed /// is not an issue. /// </para> /// <para> /// See the note below on the availability of caller location information. /// </para> /// </description> /// </item> /// <item> /// <term>identity</term> /// <description> /// <para> /// Used to output the user name for the currently active user /// (Principal.Identity.Name). /// </para> /// <para> /// <b>WARNING</b> Generating caller information is /// extremely slow. Its use should be avoided unless execution speed /// is not an issue. /// </para> /// </description> /// </item> /// <item> /// <term>l</term> /// <description>Equivalent to <b>location</b></description> /// </item> /// <item> /// <term>L</term> /// <description>Equivalent to <b>line</b></description> /// </item> /// <item> /// <term>location</term> /// <description> /// <para> /// Used to output location information of the caller which generated /// the logging event. /// </para> /// <para> /// The location information depends on the CLI implementation but /// usually consists of the fully qualified name of the calling /// method followed by the callers source the file name and line /// number between parentheses. /// </para> /// <para> /// The location information can be very useful. However, its /// generation is <b>extremely</b> slow. Its use should be avoided /// unless execution speed is not an issue. /// </para> /// <para> /// See the note below on the availability of caller location information. /// </para> /// </description> /// </item> /// <item> /// <term>level</term> /// <description> /// <para> /// Used to output the level of the logging event. /// </para> /// </description> /// </item> /// <item> /// <term>line</term> /// <description> /// <para> /// Used to output the line number from where the logging request /// was issued. /// </para> /// <para> /// <b>WARNING</b> Generating caller location information is /// extremely slow. Its use should be avoided unless execution speed /// is not an issue. /// </para> /// <para> /// See the note below on the availability of caller location information. /// </para> /// </description> /// </item> /// <item> /// <term>logger</term> /// <description> /// <para> /// Used to output the logger of the logging event. The /// logger conversion specifier can be optionally followed by /// <i>precision specifier</i>, that is a decimal constant in /// brackets. /// </para> /// <para> /// If a precision specifier is given, then only the corresponding /// number of right most components of the logger name will be /// printed. By default the logger name is printed in full. /// </para> /// <para> /// For example, for the logger name "a.b.c" the pattern /// <b>%logger{2}</b> will output "b.c". /// </para> /// </description> /// </item> /// <item> /// <term>m</term> /// <description>Equivalent to <b>message</b></description> /// </item> /// <item> /// <term>M</term> /// <description>Equivalent to <b>method</b></description> /// </item> /// <item> /// <term>message</term> /// <description> /// <para> /// Used to output the application supplied message associated with /// the logging event. /// </para> /// </description> /// </item> /// <item> /// <term>mdc</term> /// <description> /// <para> /// The MDC (old name for the ThreadContext.Properties) is now part of the /// combined event properties. This pattern is supported for compatibility /// but is equivalent to <b>property</b>. /// </para> /// </description> /// </item> /// <item> /// <term>method</term> /// <description> /// <para> /// Used to output the method name where the logging request was /// issued. /// </para> /// <para> /// <b>WARNING</b> Generating caller location information is /// extremely slow. Its use should be avoided unless execution speed /// is not an issue. /// </para> /// <para> /// See the note below on the availability of caller location information. /// </para> /// </description> /// </item> /// <item> /// <term>n</term> /// <description>Equivalent to <b>newline</b></description> /// </item> /// <item> /// <term>newline</term> /// <description> /// <para> /// Outputs the platform dependent line separator character or /// characters. /// </para> /// <para> /// This conversion pattern offers the same performance as using /// non-portable line separator strings such as "\n", or "\r\n". /// Thus, it is the preferred way of specifying a line separator. /// </para> /// </description> /// </item> /// <item> /// <term>ndc</term> /// <description> /// <para> /// Used to output the NDC (nested diagnostic context) associated /// with the thread that generated the logging event. /// </para> /// </description> /// </item> /// <item> /// <term>p</term> /// <description>Equivalent to <b>level</b></description> /// </item> /// <item> /// <term>P</term> /// <description>Equivalent to <b>property</b></description> /// </item> /// <item> /// <term>properties</term> /// <description>Equivalent to <b>property</b></description> /// </item> /// <item> /// <term>property</term> /// <description> /// <para> /// Used to output the an event specific property. The key to /// lookup must be specified within braces and directly following the /// pattern specifier, e.g. <b>%property{user}</b> would include the value /// from the property that is keyed by the string 'user'. Each property value /// that is to be included in the log must be specified separately. /// Properties are added to events by loggers or appenders. By default /// the <c>log4net:HostName</c> property is set to the name of machine on /// which the event was originally logged. /// </para> /// <para> /// If no key is specified, e.g. <b>%property</b> then all the keys and their /// values are printed in a comma separated list. /// </para> /// <para> /// The properties of an event are combined from a number of different /// contexts. These are listed below in the order in which they are searched. /// </para> /// <list type="definition"> /// <item> /// <term>the event properties</term> /// <description> /// The event has <see cref="LoggingEvent.Properties"/> that can be set. These /// properties are specific to this event only. /// </description> /// </item> /// <item> /// <term>the thread properties</term> /// <description> /// The <see cref="ThreadContext.Properties"/> that are set on the current /// thread. These properties are shared by all events logged on this thread. /// </description> /// </item> /// <item> /// <term>the global properties</term> /// <description> /// The <see cref="GlobalContext.Properties"/> that are set globally. These /// properties are shared by all the threads in the AppDomain. /// </description> /// </item> /// </list> /// /// </description> /// </item> /// <item> /// <term>r</term> /// <description>Equivalent to <b>timestamp</b></description> /// </item> /// <item> /// <term>stacktrace</term> /// <description> /// <para> /// Used to output the stack trace of the logging event /// The stack trace level specifier may be enclosed /// between braces. For example, <b>%stacktrace{level}</b>. /// If no stack trace level specifier is given then 1 is assumed /// </para> /// <para> /// Output uses the format: /// type3.MethodCall3 > type2.MethodCall2 > type1.MethodCall1 /// </para> /// <para> /// This pattern is not available for Compact Framework assemblies. /// </para> /// </description> /// </item> /// <item> /// <term>stacktracedetail</term> /// <description> /// <para> /// Used to output the stack trace of the logging event /// The stack trace level specifier may be enclosed /// between braces. For example, <b>%stacktracedetail{level}</b>. /// If no stack trace level specifier is given then 1 is assumed /// </para> /// <para> /// Output uses the format: /// type3.MethodCall3(type param,...) > type2.MethodCall2(type param,...) > type1.MethodCall1(type param,...) /// </para> /// <para> /// This pattern is not available for Compact Framework assemblies. /// </para> /// </description> /// </item> /// <item> /// <term>t</term> /// <description>Equivalent to <b>thread</b></description> /// </item> /// <item> /// <term>timestamp</term> /// <description> /// <para> /// Used to output the number of milliseconds elapsed since the start /// of the application until the creation of the logging event. /// </para> /// </description> /// </item> /// <item> /// <term>thread</term> /// <description> /// <para> /// Used to output the name of the thread that generated the /// logging event. Uses the thread number if no name is available. /// </para> /// </description> /// </item> /// <item> /// <term>type</term> /// <description> /// <para> /// Used to output the fully qualified type name of the caller /// issuing the logging request. This conversion specifier /// can be optionally followed by <i>precision specifier</i>, that /// is a decimal constant in brackets. /// </para> /// <para> /// If a precision specifier is given, then only the corresponding /// number of right most components of the class name will be /// printed. By default the class name is output in fully qualified form. /// </para> /// <para> /// For example, for the class name "log4net.Layout.PatternLayout", the /// pattern <b>%type{1}</b> will output "PatternLayout". /// </para> /// <para> /// <b>WARNING</b> Generating the caller class information is /// slow. Thus, its use should be avoided unless execution speed is /// not an issue. /// </para> /// <para> /// See the note below on the availability of caller location information. /// </para> /// </description> /// </item> /// <item> /// <term>u</term> /// <description>Equivalent to <b>identity</b></description> /// </item> /// <item> /// <term>username</term> /// <description> /// <para> /// Used to output the WindowsIdentity for the currently /// active user. /// </para> /// <para> /// <b>WARNING</b> Generating caller WindowsIdentity information is /// extremely slow. Its use should be avoided unless execution speed /// is not an issue. /// </para> /// </description> /// </item> /// <item> /// <term>utcdate</term> /// <description> /// <para> /// Used to output the date of the logging event in universal time. /// The date conversion /// specifier may be followed by a <i>date format specifier</i> enclosed /// between braces. For example, <b>%utcdate{HH:mm:ss,fff}</b> or /// <b>%utcdate{dd MMM yyyy HH:mm:ss,fff}</b>. If no date format specifier is /// given then ISO8601 format is /// assumed (<see cref="log4net.DateFormatter.Iso8601DateFormatter"/>). /// </para> /// <para> /// The date format specifier admits the same syntax as the /// time pattern string of the <see cref="M:DateTime.ToString(string)"/>. /// </para> /// <para> /// For better results it is recommended to use the log4net date /// formatters. These can be specified using one of the strings /// "ABSOLUTE", "DATE" and "ISO8601" for specifying /// <see cref="log4net.DateFormatter.AbsoluteTimeDateFormatter"/>, /// <see cref="log4net.DateFormatter.DateTimeDateFormatter"/> and respectively /// <see cref="log4net.DateFormatter.Iso8601DateFormatter"/>. For example, /// <b>%utcdate{ISO8601}</b> or <b>%utcdate{ABSOLUTE}</b>. /// </para> /// <para> /// These dedicated date formatters perform significantly /// better than <see cref="M:DateTime.ToString(string)"/>. /// </para> /// </description> /// </item> /// <item> /// <term>w</term> /// <description>Equivalent to <b>username</b></description> /// </item> /// <item> /// <term>x</term> /// <description>Equivalent to <b>ndc</b></description> /// </item> /// <item> /// <term>X</term> /// <description>Equivalent to <b>mdc</b></description> /// </item> /// <item> /// <term>%</term> /// <description> /// <para> /// The sequence %% outputs a single percent sign. /// </para> /// </description> /// </item> /// </list> /// <para> /// The single letter patterns are deprecated in favor of the /// longer more descriptive pattern names. /// </para> /// <para> /// By default the relevant information is output as is. However, /// with the aid of format modifiers it is possible to change the /// minimum field width, the maximum field width and justification. /// </para> /// <para> /// The optional format modifier is placed between the percent sign /// and the conversion pattern name. /// </para> /// <para> /// The first optional format modifier is the <i>left justification /// flag</i> which is just the minus (-) character. Then comes the /// optional <i>minimum field width</i> modifier. This is a decimal /// constant that represents the minimum number of characters to /// output. If the data item requires fewer characters, it is padded on /// either the left or the right until the minimum width is /// reached. The default is to pad on the left (right justify) but you /// can specify right padding with the left justification flag. The /// padding character is space. If the data item is larger than the /// minimum field width, the field is expanded to accommodate the /// data. The value is never truncated. /// </para> /// <para> /// This behavior can be changed using the <i>maximum field /// width</i> modifier which is designated by a period followed by a /// decimal constant. If the data item is longer than the maximum /// field, then the extra characters are removed from the /// <i>beginning</i> of the data item and not from the end. For /// example, it the maximum field width is eight and the data item is /// ten characters long, then the first two characters of the data item /// are dropped. This behavior deviates from the printf function in C /// where truncation is done from the end. /// </para> /// <para> /// Below are various format modifier examples for the logger /// conversion specifier. /// </para> /// <div class="tablediv"> /// <table class="dtTABLE" cellspacing="0"> /// <tr> /// <th>Format modifier</th> /// <th>left justify</th> /// <th>minimum width</th> /// <th>maximum width</th> /// <th>comment</th> /// </tr> /// <tr> /// <td align="center">%20logger</td> /// <td align="center">false</td> /// <td align="center">20</td> /// <td align="center">none</td> /// <td> /// <para> /// Left pad with spaces if the logger name is less than 20 /// characters long. /// </para> /// </td> /// </tr> /// <tr> /// <td align="center">%-20logger</td> /// <td align="center">true</td> /// <td align="center">20</td> /// <td align="center">none</td> /// <td> /// <para> /// Right pad with spaces if the logger /// name is less than 20 characters long. /// </para> /// </td> /// </tr> /// <tr> /// <td align="center">%.30logger</td> /// <td align="center">NA</td> /// <td align="center">none</td> /// <td align="center">30</td> /// <td> /// <para> /// Truncate from the beginning if the logger /// name is longer than 30 characters. /// </para> /// </td> /// </tr> /// <tr> /// <td align="center"><nobr>%20.30logger</nobr></td> /// <td align="center">false</td> /// <td align="center">20</td> /// <td align="center">30</td> /// <td> /// <para> /// Left pad with spaces if the logger name is shorter than 20 /// characters. However, if logger name is longer than 30 characters, /// then truncate from the beginning. /// </para> /// </td> /// </tr> /// <tr> /// <td align="center">%-20.30logger</td> /// <td align="center">true</td> /// <td align="center">20</td> /// <td align="center">30</td> /// <td> /// <para> /// Right pad with spaces if the logger name is shorter than 20 /// characters. However, if logger name is longer than 30 characters, /// then truncate from the beginning. /// </para> /// </td> /// </tr> /// </table> /// </div> /// <para> /// <b>Note about caller location information.</b><br /> /// The following patterns <c>%type %file %line %method %location %class %C %F %L %l %M</c> /// all generate caller location information. /// Location information uses the <c>System.Diagnostics.StackTrace</c> class to generate /// a call stack. The caller's information is then extracted from this stack. /// </para> /// <note type="caution"> /// <para> /// The <c>System.Diagnostics.StackTrace</c> class is not supported on the /// .NET Compact Framework 1.0 therefore caller location information is not /// available on that framework. /// </para> /// </note> /// <note type="caution"> /// <para> /// The <c>System.Diagnostics.StackTrace</c> class has this to say about Release builds: /// </para> /// <para> /// "StackTrace information will be most informative with Debug build configurations. /// By default, Debug builds include debug symbols, while Release builds do not. The /// debug symbols contain most of the file, method name, line number, and column /// information used in constructing StackFrame and StackTrace objects. StackTrace /// might not report as many method calls as expected, due to code transformations /// that occur during optimization." /// </para> /// <para> /// This means that in a Release build the caller information may be incomplete or may /// not exist at all! Therefore caller location information cannot be relied upon in a Release build. /// </para> /// </note> /// <para> /// Additional pattern converters may be registered with a specific <see cref="PatternLayout"/> /// instance using the <see cref="M:AddConverter(string, Type)"/> method. /// </para> /// </remarks> /// <example> /// This is a more detailed pattern. /// <code><b>%timestamp [%thread] %level %logger %ndc - %message%newline</b></code> /// </example> /// <example> /// A similar pattern except that the relative time is /// right padded if less than 6 digits, thread name is right padded if /// less than 15 characters and truncated if longer and the logger /// name is left padded if shorter than 30 characters and truncated if /// longer. /// <code><b>%-6timestamp [%15.15thread] %-5level %30.30logger %ndc - %message%newline</b></code> /// </example> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> /// <author>Douglas de la Torre</author> /// <author>Daniel Cazzulino</author> public class PatternLayout : LayoutSkeleton { #region Constants /// <summary> /// Default pattern string for log output. /// </summary> /// <remarks> /// <para> /// Default pattern string for log output. /// Currently set to the string <b>"%message%newline"</b> /// which just prints the application supplied message. /// </para> /// </remarks> public const string DefaultConversionPattern ="%message%newline"; /// <summary> /// A detailed conversion pattern /// </summary> /// <remarks> /// <para> /// A conversion pattern which includes Time, Thread, Logger, and Nested Context. /// Current value is <b>%timestamp [%thread] %level %logger %ndc - %message%newline</b>. /// </para> /// </remarks> public const string DetailConversionPattern = "%timestamp [%thread] %level %logger %ndc - %message%newline"; #endregion #region Static Fields /// <summary> /// Internal map of converter identifiers to converter types. /// </summary> /// <remarks> /// <para> /// This static map is overridden by the m_converterRegistry instance map /// </para> /// </remarks> private static Hashtable s_globalRulesRegistry; #endregion Static Fields #region Member Variables /// <summary> /// the pattern /// </summary> private string m_pattern; /// <summary> /// the head of the pattern converter chain /// </summary> private PatternConverter m_head; /// <summary> /// patterns defined on this PatternLayout only /// </summary> private Hashtable m_instanceRulesRegistry = new Hashtable(); #endregion #region Static Constructor /// <summary> /// Initialize the global registry /// </summary> /// <remarks> /// <para> /// Defines the builtin global rules. /// </para> /// </remarks> static PatternLayout() { s_globalRulesRegistry = new Hashtable(45); s_globalRulesRegistry.Add("literal", typeof(LiteralPatternConverter)); s_globalRulesRegistry.Add("newline", typeof(NewLinePatternConverter)); s_globalRulesRegistry.Add("n", typeof(NewLinePatternConverter)); // .NET Compact Framework 1.0 has no support for ASP.NET // SSCLI 1.0 has no support for ASP.NET #if !NETCF && !SSCLI && !CLIENT_PROFILE && !NETSTANDARD s_globalRulesRegistry.Add("aspnet-cache", typeof(AspNetCachePatternConverter)); s_globalRulesRegistry.Add("aspnet-context", typeof(AspNetContextPatternConverter)); s_globalRulesRegistry.Add("aspnet-request", typeof(AspNetRequestPatternConverter)); s_globalRulesRegistry.Add("aspnet-session", typeof(AspNetSessionPatternConverter)); #endif s_globalRulesRegistry.Add("c", typeof(LoggerPatternConverter)); s_globalRulesRegistry.Add("logger", typeof(LoggerPatternConverter)); s_globalRulesRegistry.Add("C", typeof(TypeNamePatternConverter)); s_globalRulesRegistry.Add("class", typeof(TypeNamePatternConverter)); s_globalRulesRegistry.Add("type", typeof(TypeNamePatternConverter)); s_globalRulesRegistry.Add("d", typeof(DatePatternConverter)); s_globalRulesRegistry.Add("date", typeof(DatePatternConverter)); s_globalRulesRegistry.Add("exception", typeof(ExceptionPatternConverter)); s_globalRulesRegistry.Add("F", typeof(FileLocationPatternConverter)); s_globalRulesRegistry.Add("file", typeof(FileLocationPatternConverter)); s_globalRulesRegistry.Add("l", typeof(FullLocationPatternConverter)); s_globalRulesRegistry.Add("location", typeof(FullLocationPatternConverter)); s_globalRulesRegistry.Add("L", typeof(LineLocationPatternConverter)); s_globalRulesRegistry.Add("line", typeof(LineLocationPatternConverter)); s_globalRulesRegistry.Add("m", typeof(MessagePatternConverter)); s_globalRulesRegistry.Add("message", typeof(MessagePatternConverter)); s_globalRulesRegistry.Add("M", typeof(MethodLocationPatternConverter)); s_globalRulesRegistry.Add("method", typeof(MethodLocationPatternConverter)); s_globalRulesRegistry.Add("p", typeof(LevelPatternConverter)); s_globalRulesRegistry.Add("level", typeof(LevelPatternConverter)); s_globalRulesRegistry.Add("P", typeof(PropertyPatternConverter)); s_globalRulesRegistry.Add("property", typeof(PropertyPatternConverter)); s_globalRulesRegistry.Add("properties", typeof(PropertyPatternConverter)); s_globalRulesRegistry.Add("r", typeof(RelativeTimePatternConverter)); s_globalRulesRegistry.Add("timestamp", typeof(RelativeTimePatternConverter)); #if !NETCF && !NETSTANDARD1_3 s_globalRulesRegistry.Add("stacktrace", typeof(StackTracePatternConverter)); s_globalRulesRegistry.Add("stacktracedetail", typeof(StackTraceDetailPatternConverter)); #endif s_globalRulesRegistry.Add("t", typeof(ThreadPatternConverter)); s_globalRulesRegistry.Add("thread", typeof(ThreadPatternConverter)); // For backwards compatibility the NDC patterns s_globalRulesRegistry.Add("x", typeof(NdcPatternConverter)); s_globalRulesRegistry.Add("ndc", typeof(NdcPatternConverter)); // For backwards compatibility the MDC patterns just do a property lookup s_globalRulesRegistry.Add("X", typeof(PropertyPatternConverter)); s_globalRulesRegistry.Add("mdc", typeof(PropertyPatternConverter)); s_globalRulesRegistry.Add("a", typeof(AppDomainPatternConverter)); s_globalRulesRegistry.Add("appdomain", typeof(AppDomainPatternConverter)); s_globalRulesRegistry.Add("u", typeof(IdentityPatternConverter)); s_globalRulesRegistry.Add("identity", typeof(IdentityPatternConverter)); s_globalRulesRegistry.Add("utcdate", typeof(UtcDatePatternConverter)); s_globalRulesRegistry.Add("utcDate", typeof(UtcDatePatternConverter)); s_globalRulesRegistry.Add("UtcDate", typeof(UtcDatePatternConverter)); s_globalRulesRegistry.Add("w", typeof(UserNamePatternConverter)); s_globalRulesRegistry.Add("username", typeof(UserNamePatternConverter)); } #endregion Static Constructor #region Constructors /// <summary> /// Constructs a PatternLayout using the DefaultConversionPattern /// </summary> /// <remarks> /// <para> /// The default pattern just produces the application supplied message. /// </para> /// <para> /// Note to Inheritors: This constructor calls the virtual method /// <see cref="CreatePatternParser"/>. If you override this method be /// aware that it will be called before your is called constructor. /// </para> /// <para> /// As per the <see cref="IOptionHandler"/> contract the <see cref="ActivateOptions"/> /// method must be called after the properties on this object have been /// configured. /// </para> /// </remarks> public PatternLayout() : this(DefaultConversionPattern) { } /// <summary> /// Constructs a PatternLayout using the supplied conversion pattern /// </summary> /// <param name="pattern">the pattern to use</param> /// <remarks> /// <para> /// Note to Inheritors: This constructor calls the virtual method /// <see cref="CreatePatternParser"/>. If you override this method be /// aware that it will be called before your is called constructor. /// </para> /// <para> /// When using this constructor the <see cref="ActivateOptions"/> method /// need not be called. This may not be the case when using a subclass. /// </para> /// </remarks> public PatternLayout(string pattern) { // By default we do not process the exception IgnoresException = true; m_pattern = pattern; if (m_pattern == null) { m_pattern = DefaultConversionPattern; } ActivateOptions(); } #endregion /// <summary> /// The pattern formatting string /// </summary> /// <remarks> /// <para> /// The <b>ConversionPattern</b> option. This is the string which /// controls formatting and consists of a mix of literal content and /// conversion specifiers. /// </para> /// </remarks> public string ConversionPattern { get { return m_pattern; } set { m_pattern = value; } } /// <summary> /// Create the pattern parser instance /// </summary> /// <param name="pattern">the pattern to parse</param> /// <returns>The <see cref="PatternParser"/> that will format the event</returns> /// <remarks> /// <para> /// Creates the <see cref="PatternParser"/> used to parse the conversion string. Sets the /// global and instance rules on the <see cref="PatternParser"/>. /// </para> /// </remarks> protected virtual PatternParser CreatePatternParser(string pattern) { PatternParser patternParser = new PatternParser(pattern); // Add all the builtin patterns foreach(DictionaryEntry entry in s_globalRulesRegistry) { ConverterInfo converterInfo = new ConverterInfo(); converterInfo.Name = (string)entry.Key; converterInfo.Type = (Type)entry.Value; patternParser.PatternConverters[entry.Key] = converterInfo; } // Add the instance patterns foreach(DictionaryEntry entry in m_instanceRulesRegistry) { patternParser.PatternConverters[entry.Key] = entry.Value; } return patternParser; } #region Implementation of IOptionHandler /// <summary> /// Initialize layout options /// </summary> /// <remarks> /// <para> /// This is part of the <see cref="IOptionHandler"/> delayed object /// activation scheme. The <see cref="ActivateOptions"/> method must /// be called on this object after the configuration properties have /// been set. Until <see cref="ActivateOptions"/> is called this /// object is in an undefined state and must not be used. /// </para> /// <para> /// If any of the configuration properties are modified then /// <see cref="ActivateOptions"/> must be called again. /// </para> /// </remarks> public override void ActivateOptions() { m_head = CreatePatternParser(m_pattern).Parse(); PatternConverter curConverter = m_head; while(curConverter != null) { PatternLayoutConverter layoutConverter = curConverter as PatternLayoutConverter; if (layoutConverter != null) { if (!layoutConverter.IgnoresException) { // Found converter that handles the exception this.IgnoresException = false; break; } } curConverter = curConverter.Next; } } #endregion #region Override implementation of LayoutSkeleton /// <summary> /// Produces a formatted string as specified by the conversion pattern. /// </summary> /// <param name="loggingEvent">the event being logged</param> /// <param name="writer">The TextWriter to write the formatted event to</param> /// <remarks> /// <para> /// Parse the <see cref="LoggingEvent"/> using the patter format /// specified in the <see cref="ConversionPattern"/> property. /// </para> /// </remarks> public override void Format(TextWriter writer, LoggingEvent loggingEvent) { if (writer == null) { throw new ArgumentNullException("writer"); } if (loggingEvent == null) { throw new ArgumentNullException("loggingEvent"); } PatternConverter c = m_head; // loop through the chain of pattern converters while(c != null) { c.Format(writer, loggingEvent); c = c.Next; } } #endregion /// <summary> /// Add a converter to this PatternLayout /// </summary> /// <param name="converterInfo">the converter info</param> /// <remarks> /// <para> /// This version of the method is used by the configurator. /// Programmatic users should use the alternative <see cref="M:AddConverter(string,Type)"/> method. /// </para> /// </remarks> public void AddConverter(ConverterInfo converterInfo) { if (converterInfo == null) throw new ArgumentNullException("converterInfo"); if (!typeof(PatternConverter).IsAssignableFrom(converterInfo.Type)) { throw new ArgumentException("The converter type specified [" + converterInfo.Type + "] must be a subclass of log4net.Util.PatternConverter", "converterInfo"); } m_instanceRulesRegistry[converterInfo.Name] = converterInfo; } /// <summary> /// Add a converter to this PatternLayout /// </summary> /// <param name="name">the name of the conversion pattern for this converter</param> /// <param name="type">the type of the converter</param> /// <remarks> /// <para> /// Add a named pattern converter to this instance. This /// converter will be used in the formatting of the event. /// This method must be called before <see cref="ActivateOptions"/>. /// </para> /// <para> /// The <paramref name="type"/> specified must extend the /// <see cref="PatternConverter"/> type. /// </para> /// </remarks> public void AddConverter(string name, Type type) { if (name == null) throw new ArgumentNullException("name"); if (type == null) throw new ArgumentNullException("type"); ConverterInfo converterInfo = new ConverterInfo(); converterInfo.Name = name; converterInfo.Type = type; AddConverter(converterInfo); } } }
36.16567
174
0.62536
[ "Apache-2.0" ]
BipulRaman/logging-log4net
src/log4net/Layout/PatternLayout.cs
42,350
C#
namespace Love { public enum MouseButton: int { /// <summary> /// The mouse left button /// </summary> LeftButton = 0, /// <summary> /// The mouse right button /// </summary> RightButton, /// <summary> /// The mouse middle button /// </summary> MiddleButton, /// <summary> /// The first extended button /// </summary> ExtendedButton1, /// <summary> /// The second extended button /// </summary> ExtendedButton2, /// <summary> /// The third extended button /// </summary> ExtendedButton3, /// <summary> /// The Fourth extended button /// </summary> ExtendedButton4, /// <summary> /// The Fifth extended button /// </summary> ExtendedButton5, } public enum VertexDataType: int { UNORM8, UNORM16, FLOAT, } public enum VertexCullMode : int { None, Back, Front, MAX_ENUM }; public enum VertexWinding : int { CW, CCW, MAX_ENUM } /// <summary> /// The types of a Body. /// </summary> public enum BodyType { /// <summary> /// Static bodies do not move. /// </summary> Static = 1, /// <summary> /// Dynamic bodies collide with all bodies. /// </summary> Dynamic, /// <summary> /// Kinematic bodies only collide with dynamic bodies. /// </summary> Kinematic, } /// <summary> /// Different types of joints. /// </summary> public enum JointType { Distance = 1, Revolute, Prismatic, Mouse, Pulley, Gear, Friction, Weld, Wheel, Rope, Motor, } /// <summary> /// The different types of Shapes, as returned by Shape:getType. /// </summary> public enum ShapeType { Circle = 1, Polygon, Edge, Chain, } /// <summary> /// True Type hinting mode. See True Type official document for more information. /// </summary> public enum HintingMode { Normal, Light, Mono, None, }; /// <summary> /// Virtual gamepad buttons. /// </summary> public enum GamepadButton { A = 1, B, X, Y, Back, Guide, Start, /// <summary> /// Left stick click button. /// </summary> LeftStick, /// <summary> /// Right stick click button. /// </summary> RightStick, /// <summary> /// Left bumper. /// </summary> LeftShoulder, /// <summary> /// Right bumper. /// </summary> RightShoulder, /// <summary> /// D-pad up. /// </summary> DPadUp, /// <summary> /// D-pad down. /// </summary> DPadDown, /// <summary> /// D-pad left. /// </summary> DPadLeft, /// <summary> /// D-pad right. /// </summary> DPadRight, }; /// <summary> /// Virtual gamepad axes. /// </summary> public enum GamepadAxis { LeftX = 1, LeftY, RightX, RightY, TriggerLeft, TriggerRight, }; // Joystick hat values. public enum JoystickHat { Centered = 1, Up, Right, Down, Left, /// <summary> /// Right+Up /// </summary> RightUp, /// <summary> /// Right+Down /// </summary> RightDown, /// <summary> /// Left+Up /// </summary> LeftUp, /// <summary> /// Left+Down /// </summary> LeftDown, }; /// <summary> /// How newly created particles are added to the ParticleSystem. /// </summary> public enum ParticleInsertMode { /// <summary> /// Particles are inserted at the top of the ParticleSystem's list of particles. /// </summary> Top, /// <summary> /// Particles are inserted at the bottom of the ParticleSystem's list of particles. /// </summary> Bottom, /// <summary> /// Particles are inserted at random positions in the ParticleSystem's list of particles. /// </summary> Random, }; /// <summary> /// How the image wraps inside a Quad with a larger quad size than image size. This also affects how Meshes with texture coordinates which are outside the range of [0, 1] are drawn, and the color returned by the Texel Shader function when using it to sample from texture coordinates outside of the range of [0, 1]. /// <para>https://love2d.org/wiki/WrapMode</para> /// </summary> public enum WrapMode { /// <summary> /// Clamp the texture. Appears only once. The area outside the texture's normal range is colored based on the edge pixels of the texture. /// </summary> Clamp, /// <summary> /// Clamp the texture. Fills the area outside the texture's normal range with transparent black (or opaque black for textures with no alpha channel.) /// </summary> ClampZero, /// <summary> /// Repeat the texture. Fills the whole available extent. /// </summary> Repeat, /// <summary> /// Repeat the texture, flipping it each time it repeats. May produce better visual results than the <see cref="Repeat"/> mode when the texture doesn't seamlessly tile. /// </summary> MirroredRepeat, }; /// <summary> /// How the image is filtered when scaling. /// </summary> public enum FilterMode { None, /// <summary> /// Scale image with linear interpolation. (default) /// </summary> Linear, /// <summary> /// Scale image with nearest neighbor interpolation. /// </summary> Nearest, }; /// <summary> /// Text alignment. /// </summary> public enum AlignMode { /// <summary> /// Align text left. /// </summary> Left, /// <summary> /// Align text center. /// </summary> Center, /// <summary> /// Align text right. /// </summary> Right, /// <summary> /// Align text both left and right. /// </summary> Justify, }; /// <summary> /// Provide for custom image data, not all Pixel format support to create new custom imageData; /// </summary> public enum ImageDataPixelFormat : int { RGBA8 = PixelFormat.RGBA8, RGBA16 = PixelFormat.RGBA16, RGBA16F = PixelFormat.RGBA16F, RGBA32F = PixelFormat.RGBA32F, } /// <summary> /// Encoded image formats. /// </summary> public enum ImageFormat { /// <summary> /// Targa image format. /// </summary> TGA, /// <summary> /// PNG image format. /// </summary> PNG, }; /// <summary> /// The different modes you can open a File in. /// </summary> public enum FileMode : int { /// <summary> /// Do not open a file (represents a closed file.) /// </summary> Closed, /// <summary> /// Open a file for read. /// </summary> Read, /// <summary> /// Open a file for write. /// </summary> Write, /// <summary> /// Open a file for append. /// </summary> Append, }; /// <summary> /// Buffer modes for File objects. /// </summary> public enum BufferMode : int { /// <summary> /// No buffering. The result of write and append operations appears immediately. /// </summary> None, /// <summary> /// Line buffering. Write and append operations are buffered until a newline is output or the buffer size limit is reached. /// </summary> Line, /// <summary> /// Full buffering. Write and append operations are always buffered until the buffer size limit is reached. /// </summary> Full, }; /// <summary> /// The type of a file. /// </summary> public enum FileType : int { /// <summary> /// Regular file. /// </summary> File, /// <summary> /// Directory. /// </summary> Directory, /// <summary> /// Symbolic link. /// </summary> SymLink, /// <summary> /// Something completely different like a device. /// </summary> Other, }; /// <summary> /// The different distance models. /// <para>Extended information can be found in the chapter "3.4. Attenuation By Distance" of the OpenAL 1.1 specification.( https://www.openal.org/documentation/openal-1.1-specification.pdf )</para> /// </summary> public enum DistanceModel { /// <summary> /// Sources do not get attenuated. /// </summary> None, /// <summary> /// Inverse distance attenuation. /// </summary> Inverse, /// <summary> /// Inverse distance attenuation. Gain is clamped. In version 0.9.2 and older this is named inverse clamped. /// </summary> InverseClamped, /// <summary> /// Linear attenuation. /// </summary> Linear, /// <summary> /// Linear attenuation. Gain is clamped. In version 0.9.2 and older this is named linear clamped. /// </summary> LinearClamped, /// <summary> /// Exponential attenuation. /// </summary> Exponent, /// <summary> /// Exponential attenuation. Gain is clamped. In version 0.9.2 and older this is named exponent clamped. /// </summary> ExponentClamped, }; /// <summary> /// Types of cursors. /// </summary> public enum SystemCursor : int { /// <summary> /// An arrow pointer. /// </summary> Arrow, /// <summary> /// An I-beam, normally used when mousing over editable or selectable text. /// </summary> Ibeam, /// <summary> /// Wait graphic. /// </summary> Wait, /// <summary> /// Crosshair symbol. /// </summary> Crosshair, /// <summary> /// Small wait cursor with an arrow pointer. /// </summary> WaitArrow, /// <summary> /// Double arrow pointing to the top-left and bottom-right. /// </summary> SizeNWSE, /// <summary> /// Double arrow pointing to the top-right and bottom-left. /// </summary> SizeNESW, /// <summary> /// Double arrow pointing left and right. /// </summary> SizeWE, /// <summary> /// Double arrow pointing up and down. /// </summary> SizeNS, /// <summary> /// Four-pointed arrow pointing up, down, left, and right. /// </summary> SizeAll, /// <summary> /// Slashed circle or crossbones. /// </summary> No, /// <summary> /// Hand symbol. /// </summary> Hand, } public enum CursorType: int { /// <summary> /// 自定义的光标类型 /// </summary> Custom, /// <summary> /// 系统的光标 /// </summary> System, } /// <summary> /// Units that represent time. /// </summary> public enum TimeUnit : int { /// <summary> /// Regular seconds. /// </summary> Seconds = 0, /// <summary> /// Audio samples. /// </summary> Samples, }; /// <summary> /// All the keys you can press. Note that some keys may not be available on your keyboard or system. /// </summary> public enum KeyConstant : int { Unknown, Return, Enter = Return, Escape, Backspace, Tab, Space, Exclaim, Quotedbl, Hash, Percent, Dollar, Ampersand, Quote, LeftParen, RightParen, Asterisk, Plus, Comma, Minus, Period, Slash, Number0, Number1, Number2, Number3, Number4, Number5, Number6, Number7, Number8, Number9, Colon, SemiColon, Less, Equals, Greater, Question, At, LeftBracket, Backslash, RightBracket, Caret, Underscore, Backquote, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, CapsLock, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, PrintScreen, ScrollLock, Pause, Insert, Home, PageUp, Delete, End, PageDown, Right, Left, Down, Up, NumLockClear, KeypadDivide, KeypadMultiply, KeypadMinus, KeypadPlus, KeypadEnter, Keypad1, Keypad2, Keypad3, Keypad4, Keypad5, Keypad6, Keypad7, Keypad8, Keypad9, Keypad0, KeypadPeriod, KeypadComma, KeypadEquals, Application, Power, F13, F14, F15, F16, F17, F18, F19, F20, F21, F22, F23, F24, Execute, Help, Menu, Select, Stop, Again, Undo, Cut, Copy, Paste, Find, Mute, VolumeUp, VolumeDown, Alterase, Sysreq, Cancel, Clear, Prior, Return2, Separator, Out, Oper, ClearAgain, ThousandsSeparator, DecimalSeparator, CurrencyUnit, CurrencySubunit, LCtrl, LShift, LAlt, LGUI, RCtrl, RShift, RAlt, RGUI, Mode, AudioNext, AudioPrev, AudioStop, AudioPlay, AudioMute, MediaSelect, WWW, Mail, Calculator, Computer, AppSearch, AppHome, AppBack, AppForward, AppStop, AppRefresh, AppBookmarks, BrightnessDown, BrightnessUp, DisplaySwitch, KBDILLUMToggle, KBDILLUMDown, KBDILLUMUp, Eject, Sleep, }; /// <summary> /// <para>Scancodes are keyboard layout-independent, so the scancode "w" will be generated if the key in the same place as the "w" key on an American QWERTY keyboard ( https://en.wikipedia.org/wiki/Keyboard_layout#/media/File:ISO_keyboard_(105)_QWERTY_UK.svg ) is pressed, no matter what the key is labelled or what the user's operating system settings are.</para> /// <para>Using scancodes, rather than keycodes, is useful because keyboards with layouts differing from the US/UK layout(s) might have keys that generate 'unknown' keycodes, but the scancodes will still be detected. This however would necessitate having a list for each keyboard layout one would choose to support.</para> /// <para>One could use textinput or textedited instead, but those only give back the end result of keys used, i.e. you can't get modifiers on their own from it, only the final symbols that were generated.</para> /// </summary> public enum Scancode : int { Unknow, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, Number1, Number2, Number3, Number4, Number5, Number6, Number7, Number8, Number9, Number0, Return, Escape, Backspace, Tab, Space, Minus, Equals, LeftBracket, RightBracket, Backslash, Nonushash, Semicolon, Apostrophe, Grave, Comma, Period, Slash, Capslock, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, PrintScreen, ScrollLock, Pause, Insert, Home, PageUp, Delete, End, PageDown, Right, Left, Down, Up, NumLockClear, KeypadDivide, KeypadMultiply, KeypadMinus, KeypadPlus, KeypadEnter, Keypad1, Keypad2, Keypad3, Keypad4, Keypad5, Keypad6, Keypad7, Keypad8, Keypad9, Keypad0, KeypadPeriod, NonusBackslash, Application, Power, KeypadEquals, F13, F14, F15, F16, F17, F18, F19, F20, F21, F22, F23, F24, Execute, Help, Menu, Select, Stop, Again, Undo, Cut, Copy, Paste, Find, Mute, VolumeUp, VolumeDown, KeypadComma, KeypadEqualSAS400, International1, International2, International3, International4, International5, International6, International7, International8, International9, Lang1, Lang2, Lang3, Lang4, Lang5, Lang6, Lang7, Lang8, Lang9, Alterase, Sysreq, Cancel, Clear, Prior, Return2, Separator, Out, Oper, ClearaAain, Crsel, Exsel, Keypad00, Keypad000, ThousandsSeparator, DecimalSeparator, CurrencyUnit, CurrencySubunit, KeypadLeftParen, KeypadRightParen, KeypadLeftBrace, KeypadRightBrace, KeypadTab, KeypadBackspace, KeypadA, KeypadB, KeypadC, KeypadD, KeypadE, KeypadF, KeypadXOR, KeypadPower, KeypadPercent, KeypadLess, KeypadGreater, KeypadAmpersand, KeypadDblampersand, KeypadVerticalBar, KeypadDblverticalBar, KeypadColon, KeypadHash, KeypadSpace, KeypadAt, KeypadExclam, KeypadMemstore, KeypadMemrecall, KeypadMemclear, KeypadMemadd, KeypadMemsubtract, KeypadMemmultiply, KeypadMemdivide, KeypadPlusminus, KeypadClear, KeypadClearEntry, KeypadBinary, KeypadOctal, KeypadDecimal, KeypadHexaecimal, LCtrl, LShift, LAlt, LGUI, RCtrl, RShift, RAlt, RGUI, Mode, AudioNext, AudioPrev, AudioStop, AudioPlay, AudioMute, MediaSelect, WWW, Mail, Calculator, Computer, ACSearch, ACHome, ACBack, ACForward, ACStop, ACRefresh, ACBookmarks, BrightnessDown, BrightnessUp, DisplaySwitch, KBDILLUMToggle, KBDILLUMDown, KBDILLUMUp, Eject, Sleep, App1, App2, }; /// <summary> /// <para>Types of audio sources. </para> /// <para>A good rule of thumb is to use Stream for music files and Static for all short sound effects. Basically, you want to avoid loading large files into memory at once.</para> /// </summary> public enum SourceType : int { /// <summary> /// Decode the entire sound at once. /// </summary> Static = 0, /// <summary> /// Stream the sound; decode it gradually. /// </summary> Stream, }; public enum StackType : int { /// <summary> /// All Love.Graphics state, including transform state. /// </summary> All, /// <summary> /// The transformation stack (Love.Graphics.translate, Love.Graphics.rotate, etc.) /// </summary> Transform, }; /// <summary> /// <para>全屏模式的类型。</para> /// <para>Types of fullscreen modes.</para> /// </summary> public enum FullscreenType { /// <summary> /// Standard exclusive-fullscreen mode. Changes the display mode (actual resolution) of the monitor. /// </summary> Exclusive, /// <summary> /// Sometimes known as borderless fullscreen windowed mode. A borderless screen-sized window is created which sits on top of all desktop UI elements. The window is automatically resized to match the dimensions of the desktop, and its size cannot be changed. /// </summary> DeskTop, }; /// <summary> /// <para>消息框对话框的类型。</para> /// <para>Types of message box dialogs.</para> /// </summary> public enum MessageBoxType { /// <summary> /// Error dialog. /// </summary> Error, /// <summary> /// Warning dialog. /// </summary> Warning, /// <summary> /// Informational dialog. /// </summary> Info, }; /// <summary> /// Different types of arcs that can be drawn. /// </summary> public enum ArcType : int { /// <summary> /// The arc circle's two end-points are unconnected when the arc is drawn as a line. Behaves like the "closed" arc type when the arc is drawn in filled mode. /// </summary> Open, /// <summary> /// The arc circle's two end-points are connected to each other. /// </summary> Closed, /// <summary> /// The arc is drawn like a slice of pie, with the arc circle connected to the center at its end-points. /// </summary> Pie, }; /// <summary> /// Different ways to do color blending. See BlendAlphaMode and the BlendMode Formulas for additional notes. /// </summary> public enum BlendMode : int { /// <summary> /// Alpha blending (normal). The alpha of what's drawn determines its opacity. /// </summary> Alpha, /// <summary> /// The pixel colors of what's drawn are added to the pixel colors already on the screen. The alpha of the screen is not modified. /// </summary> Add, /// <summary> /// The pixel colors of what's drawn are subtracted from the pixel colors already on the screen. The alpha of the screen is not modified. /// </summary> Subtract, /// <summary> /// The pixel colors of what's drawn are multiplied with the pixel colors already on the screen (darkening them). The alpha of drawn objects is multiplied with the alpha of the screen rather than determining how much the colors on the screen are affected, even when the <see cref="BlendAlphaMode.PreMultiplied"/> BlendAlphaMode is used. /// </summary> Multiply, /// <summary> /// The pixel colors of what's drawn are compared to the existing pixel colors, and the larger of the two values for each color component is used. Only works when the "premultiplied" BlendAlphaMode is used in <see cref="Graphics.SetBlendMode"/> /// </summary> Lighten, /// <summary> /// The pixel colors of what's drawn are compared to the existing pixel colors, and the smaller of the two values for each color component is used. Only works when the "premultiplied" BlendAlphaMode is used in <see cref="Graphics.SetBlendMode"/> /// </summary> Darken, /// <summary> /// 'Screen' blending. /// </summary> Screen, /// <summary> /// The colors of what's drawn completely replace what was on the screen, with no additional blending. The BlendAlphaMode specified in love.graphics.setBlendMode still affects what happens. /// </summary> Replace, }; /// <summary> /// The "premultiplied" constant should generally be used when drawing a Canvas to the screen, because the RGB values of the Canvas' texture had previously been multiplied by its alpha values when drawing content to the Canvas itself. /// <para>The "alphamultiply" constant does not affect the "multiply" BlendMode.Similarly, the "screen" BlendMode's math is only correct if the "premultiplied" alpha mode is used and the alpha of drawn objects has already been multiplied with its RGB values previously (possibly inside a shader).</para> /// <para>https://love2d.org/wiki/BlendAlphaMode</para> /// </summary> public enum BlendAlphaMode : int { /// <summary> /// The RGB values of what's drawn are multiplied by the alpha values of those colors during blending. This is the default alpha mode. /// </summary> Multiply, /// <summary> /// The RGB values of what's drawn are not multiplied by the alpha values of those colors during blending. For most blend modes to work correctly with this alpha mode, the colors of a drawn object need to have had their RGB values multiplied by their alpha values at some point previously ("premultiplied alpha"). /// </summary> PreMultiplied, }; /// <summary> /// The styles in which lines are drawn. /// </summary> public enum LineStyle : int { /// <summary> /// Draw rough lines. /// </summary> Rough, /// <summary> /// Draw smooth lines. /// </summary> Smooth, }; /// <summary> /// https://love2d.org/wiki/LineJoin /// </summary> public enum LineJoin : int { /// <summary> /// No cap applied to the ends of the line segments. /// <para>https://love2d.org/wiki/LineJoin</para> /// </summary> None, /// <summary> /// The ends of the line segments beveled in an angle so that they join seamlessly. /// <para>https://love2d.org/wiki/LineJoin</para> /// </summary> Miter, /// <summary> /// Flattens the point where line segments join together. /// <para>https://love2d.org/wiki/LineJoin</para> /// </summary> Bevel, }; /// <summary> /// <para>How a stencil function modifies the stencil values of pixels it touches.</para> /// https://love2d.org/wiki/StencilAction /// </summary> public enum StencilAction : int { /// <summary> /// The stencil value of a pixel will be replaced by the value specified in love.graphics.stencil, if any object touches the pixel. /// </summary> Replace, /// <summary> /// The stencil value of a pixel will be incremented by 1 for each object that touches the pixel. If the stencil value reaches 255 it will stay at 255. /// </summary> Increment, /// <summary> /// The stencil value of a pixel will be decremented by 1 for each object that touches the pixel. If the stencil value reaches 0 it will stay at 0. /// </summary> Decrement, /// <summary> /// The stencil value of a pixel will be incremented by 1 for each object that touches the pixel. If a stencil value of 255 is incremented it will be set to 0. /// </summary> IncrementWrap, /// <summary> /// The stencil value of a pixel will be decremented by 1 for each object that touches the pixel. If the stencil value of 0 is decremented it will be set to 255. /// </summary> DecrementWrap, /// <summary> /// The stencil value of a pixel will be bitwise-inverted for each object that touches the pixel. If a stencil value of 0 is inverted it will become 255. /// </summary> Invert, }; /// <summary> /// Different types of per-pixel stencil test comparisons. The pixels of an object will be drawn if the comparison succeeds, for each pixel that the object touches. /// <para>https://love2d.org/wiki/CompareMode</para> /// </summary> public enum CompareMode : int { /// <summary> /// The stencil value of the pixel must be less than the supplied value. /// </summary> Less, /// <summary> /// The stencil value of the pixel must be less than or equal to the supplied value. /// </summary> LEqual, /// <summary> /// The stencil value of the pixel must be equal to the supplied value. /// </summary> Equal, /// <summary> /// The stencil value of the pixel must be greater than or equal to the supplied value. /// </summary> GEqual, /// <summary> /// The stencil value of the pixel must be greater than the supplied value. /// </summary> Greater, /// <summary> /// The stencil value of the pixel must not be equal to the supplied value. /// </summary> NotEqual, Always, }; /// <summary> /// https://love2d.org/wiki/GraphicsFeature /// <para>Graphics features that can be checked for with love.graphics.getSupported.</para> /// </summary> public enum Feature : int { /// <summary> /// Whether multiple Canvases with different formats can be used in the same love.graphics.setCanvas call. /// <para>multicanvasformats is supported on OpenGL 3-capable desktop systems, and OpenGL ES 3-capable mobile devices.</para> /// </summary> MultiCanvasFormats, /// <summary> /// Whether the "clampzero" WrapMode is supported. /// <para>clampzero is supported on all desktop systems, but only some mobile devices. If it's not supported and it's attempted to be set, the "clamp" wrap mode will automatically be used instead.</para> /// </summary> ClampZero, /// <summary> /// Whether the "lighten" and "darken" BlendModes are supported. /// <para>lighten is supported on all desktop systems, and OpenGL ES 3-capable mobile devices.</para> /// </summary> Lighten, /// <summary> /// Whether textures with non-power-of-two dimensions can use mipmapping and the 'repeat' WrapMode (Texture:setMipmapFilter). /// </summary> FullNPOT, /// <summary> /// Whether pixel shaders can use "highp" 32 bit floating point numbers (as opposed to just 16 bit or lower precision). /// </summary> PixelShaderHighp, /// <summary> /// /// </summary> ShaderDerivatives, /// <summary> /// Whether GLSL 3 Shaders can be used. /// </summary> GLSL3, /// <summary> /// Whether mesh instancing (love.graphics.drawInstanced) is supported. /// </summary> Instancing, }; /// <summary> /// Type of distribution new particles are drawn from: None, uniform, normal, ellipse, borderellipse, borderrectangle. /// <para>https://love2d.org/wiki/AreaSpreadDistribution</para> /// </summary> public enum AreaSpreadDistribution : int { None, /// <summary> /// Uniform distribution. /// </summary> Uniform, /// <summary> /// Normal (gaussian) distribution. /// </summary> Normal, /// <summary> /// Uniform distribution in an ellipse. /// </summary> Ellipse, /// <summary> /// Distribution in an ellipse with particles spawning at the edges of the ellipse. /// </summary> BorderEllipse, /// <summary> /// Distribution in a rectangle with particles spawning at the edges of the rectangle. /// </summary> BorderRectangle, }; /// <summary> /// Controls whether shapes are drawn as an outline, or filled. /// </summary> public enum DrawMode : int { /// <summary> /// Draw outlined shape. /// </summary> Line, /// <summary> /// Draw filled shape. /// </summary> Fill, }; // The expected usage pattern of the Mesh's vertex data. public enum SpriteBatchUsage : int { /// <summary> /// The object data will always change between draws. /// </summary> Stream, /// <summary> /// The object's data will change occasionally during its lifetime. /// </summary> Dynamic, /// <summary> /// The object will not be modified after initial sprites or vertices are added. /// </summary> Static, }; /// <summary> /// https://love2d.org/wiki/MeshDrawMode /// </summary> public enum MeshDrawMode : int { /// <summary> /// The vertices create a "fan" shape with the first vertex acting as the hub point. Can be easily used to draw simple convex polygons. /// </summary> Trangles, /// <summary> /// The vertices create a series of connected triangles using vertices 1, 2, 3, then 3, 2, 4 (note the order), then 3, 4, 5, and so on. /// </summary> Strip, /// <summary> /// The vertices create a "fan" shape with the first vertex acting as the hub point. Can be easily used to draw simple convex polygons. /// </summary> Fan, /// <summary> /// The vertices are drawn as unconnected points (see love.graphics.setPointSize.) /// </summary> Points, }; /// <summary> /// Pixel formats for Textures, ImageData, and CompressedImageData. /// https://love2d.org/wiki/PixelFormat /// </summary> public enum PixelFormat : int { UNKNOWN, // these are converted to an actual format by love NORMAL, HDR, // "regular" formats R8, RG8, RGBA8, sRGBA8, R16, RG16, RGBA16, R16F, RG16F, RGBA16F, R32F, RG32F, RGBA32F, LA8, // Same as RG8, but accessed as (L, L, L, A) // packed formats RGBA4, RGB5A1, RGB565, RGB10A2, RG11B10F, // depth/stencil formats STENCIL8, DEPTH16, DEPTH24, DEPTH32F, DEPTH24_STENCIL8, DEPTH32F_STENCIL8, // compressed formats DXT1, DXT3, DXT5, BC4, BC4s, BC5, BC5s, BC6H, BC6Hs, BC7, PVR1_RGB2, PVR1_RGB4, PVR1_RGBA2, PVR1_RGBA4, ETC1, ETC2_RGB, ETC2_RGBA, ETC2_RGBA1, EAC_R, EAC_Rs, EAC_RG, EAC_RGs, ASTC_4x4, ASTC_5x4, ASTC_5x5, ASTC_6x5, ASTC_6x6, ASTC_8x5, ASTC_8x6, ASTC_8x8, ASTC_10x5, ASTC_10x6, ASTC_10x8, ASTC_10x10, ASTC_12x10, ASTC_12x12, }; /// <summary> /// https://love2d.org/wiki/CanvasMipmapMode /// </summary> public enum CanvasMipmapMode : int { /// <summary> /// Do not enable mipmap. /// </summary> None, /// <summary> /// Let user manually generate mipmap. /// </summary> Manual, /// <summary> /// Automatically generate mipmap. /// </summary> Auto, } /// <summary> /// Types of textures (2D, cubemap, etc.) /// </summary> public enum TextureType : int { /// <summary> /// Regular 2D texture with width and height. /// </summary> TEXTURE_2D, /// <summary> /// 3D texture with width, height, and depth. Requires a custom shader to use. Volume textures can have texture filtering applied along the 3rd axis. /// </summary> TEXTURE_VOLUME, /// <summary> /// Several same-size 2D textures organized into a single object. Similar to a texture atlas / sprite sheet, but avoids sprite bleeding and other issues. /// </summary> TEXTURE_2D_ARRAY, /// <summary> /// Cubemap texture with 6 faces. Requires a custom shader (and Shader:send) to use. Sampling from a cube texture in a shader takes a 3D direction vector instead of a texture coordinate. /// </summary> TEXTURE_CUBE, } }
23.536089
369
0.516067
[ "MIT" ]
Ruin0x11/Love2dCS
csharp_src/Love2dEnum.cs
38,216
C#
namespace Files { /// <summary> /// Represents an element which is associated with an arbitrary file system. /// See remarks for details. /// </summary> /// <remarks> /// The <see cref="IFileSystemElement"/> interface is implemented by every member /// which can be created by the <see cref="Files.FileSystem"/> class. /// The interface gives you access to the file system with which the implementing element /// is associated. This enables you to easily create other elements of the same file system /// implementation without direct access to the <see cref="Files.FileSystem"/> instance: /// /// <code> /// StorageFile GetFileFromPath(StoragePath path) /// { /// FileSystem fs = path.FileSystem; /// return fs.GetFile(path); /// } /// </code> /// </remarks> public interface IFileSystemElement { /// <summary> /// Gets the file system with which this element is associated. /// </summary> FileSystem FileSystem { get; } } }
37.333333
99
0.589286
[ "MIT" ]
manuelroemer/Files
src/Files/IFileSystemElement.cs
1,122
C#
using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using ISAAR.MSolve.LinearAlgebra.Commons; using ISAAR.MSolve.LinearAlgebra.Exceptions; using ISAAR.MSolve.LinearAlgebra.Output.Formatting; using ISAAR.MSolve.LinearAlgebra.Vectors; //TODO: Add a create from dense method to facilitate testing. //TODO: Also provide a method GetSubmatrixWithout that would remove rows/cols. Actually that would be better as Remove(int[]) // in a DOK with a Dictionary<Dictionary<int, double>> as a backing storage to easily remove stuff. namespace ISAAR.MSolve.LinearAlgebra.Matrices.Builders { /// <summary> /// Use this class for building large symmetric sparse matrices not for operations. Convert to other matrix formats once /// finished and use them instead for matrix operations. The large matrices and their properties will be characterized as /// "global" in this namespace. This class is optimized for building symmetric global matrices, where only entries of the /// upper triangle are explicitly stored, the storage format is column major and there is at least 1 entry per column. /// Authors: Serafeim Bakalakos /// </summary> public class DokSymmetric: ISparseSymmetricMatrix, ISymmetricMatrixBuilder { /// <summary> /// An array of dictionaries is more efficent and perhaps easier to work with than a dictionary of dictionaries. There /// is usually at least 1 non zero entry in each column. Otherwise this data structure wastes space, but if there were /// many empty rows, perhaps another matrix format is more appropriate. /// To get the value: columns[colIdx][rowIdx] = value. /// To get the row-value subdictionary: columns[colIdx] = Dictionary[int, double] /// TODO: Things to benchmark (keys = row indices): /// 1) Dictionary + sort on converting: copy unordered keys and values to arrays and sort both arrays according to keys /// 2) Dictionary + sort on converting: Use LINQ to sort key-value pairs and then copy each one to the arrays /// 3) SortedDictionary: O(log(n)) insertion but already ordered. Some entries are inserted more than once though! /// However this is wasteful if the sparse matrix doesn't need to be ordered. Thus I should use IDictionary and provide /// static methods for Skyline (descending keys), CSC (ascending keys) or unordered (can use simple Dictionary) /// Perhaps a Dictionary should be used instead of SortedDictionary and only sort each column independently before /// converting. /// </summary> private Dictionary<int, double>[] columns; private readonly int order; private DokSymmetric(int order, Dictionary<int, double>[] columns) { this.columns = columns; this.order = order; } /// <summary> /// The number of columns of the matrix. /// </summary> public int NumColumns { get => order; } /// <summary> /// The number of rows of the matrix. /// </summary> public int NumRows { get => order; } /// <summary> /// See <see cref="IIndexable2D.this[int, int]"/>, <see cref="IMatrixBuilder.this[int, int]"/>. /// </summary> public double this[int rowIdx, int colIdx] { get { ProcessIndices(ref rowIdx, ref colIdx); if (columns[colIdx].TryGetValue(rowIdx, out double val)) return val; else return 0.0; } set //not thread safe { ProcessIndices(ref rowIdx, ref colIdx); columns[colIdx][rowIdx] = value; } } /// <summary> /// Initializes a new instance of <see cref="DokColMajor"/> with the specified matrix dimensions and all entries being /// equal to 0. /// </summary> /// <param name="order">The number of rows/columns of the symmetric matrix to build.</param> public static DokSymmetric CreateEmpty(int order) { var columns = new Dictionary<int, double>[order]; for (int j = 0; j < order; ++j) columns[j] = new Dictionary<int, double>(); //Initial capacity may be optimized. return new DokSymmetric(order, columns); } /// <summary> /// Initializes a new instance of <see cref="DokSymmetric"/> with the specified matrix dimensions and entries /// being the same as the identity matrix. /// WARNING: if you initilize the DOK to identity, then you need to overwrite the diagonal entries with the new values /// (in FEM you only write to each diagonal entry once), instead of adding to them. This precludes the use of the methods /// that add a whole submatrix to the DOK. Therefore, it is more convenient to call <see cref="CreateEmpty(int)"/> /// and after all submatrices have been added, call <see cref="SetStructuralZeroDiagonalEntriesToUnity"/>. /// </summary> /// <param name="order">The number of rows/columns of the symmetric matrix to build.</param> public static DokSymmetric CreateIdentity(int order) { var columns = new Dictionary<int, double>[order]; for (int j = 0; j < order; ++j) { var idenityCol = new Dictionary<int, double>(); //Initial capacity may be optimized. idenityCol[j] = 1.0; columns[j] = idenityCol; } return new DokSymmetric(order, columns); } /// <summary> /// Initializes a new instance of <see cref="DokSymmetric"/> with the specified matrix dimensions and the /// non-zero entries of the provided sparse matrix. /// </summary> /// <param name="matrix">A symmetric sparse matrix whose dimensions and non-zero entries will be used to intialize the /// new <see cref="DokSymmetric"/>. Its symmetry will not be checked explicitly.</param> public static DokSymmetric CreateFromSparseMatrix(ISparseMatrix matrix) { Preconditions.CheckSquare(matrix); return CreateFromSparsePattern(matrix.NumColumns, matrix.EnumerateNonZeros()); } /// <summary> /// Initializes a new instance of <see cref="DokSymmetric"/> with the specified matrix dimensions and the /// non-zero entries defined by the provided pattern. /// </summary> /// <param name="numRows">The number of rows/columns of the symmetric matrix to build.</param> /// <param name="nonZeroEntries">The non-zero entries of the symmetric matrix to build. Its symmetry will not be /// checked explicitly.</param> public static DokSymmetric CreateFromSparsePattern(int order, IEnumerable<(int row, int col, double value)> nonZeroEntries) { DokSymmetric dok = CreateEmpty(order); foreach (var (row, col, val) in nonZeroEntries) { if ( row <= col) dok.columns[col][row] = val; } return dok; } /// <summary> /// Initializes a new instance of <see cref="DokSymmetric"/> with the specified matrix dimensions and the /// non-zero entries of the provided symmetric sparse matrix. /// </summary> /// <param name="matrix">A symmetric sparse matrix whose dimensions and non-zero entries will be used to intialize the /// new <see cref="DokSymmetric"/>.</param> public static DokSymmetric CreateFromSparseSymmetricMatrix(ISparseSymmetricMatrix matrix) { Preconditions.CheckSquare(matrix); //This should not be needed return CreateFromSparseSymmetricPattern(matrix.NumColumns, matrix.EnumerateNonZeros()); } /// <summary> /// Initializes a new instance of <see cref="DokSymmetric"/> with the specified matrix dimensions and the /// non-zero entries defined by the provided symmetric pattern. /// </summary> /// <param name="numRows">The number of rows/columns of the symmetric matrix to build.</param> /// <param name="nonZeroEntries">The non-zero entries of the symmetric matrix to build.</param> public static DokSymmetric CreateFromSparseSymmetricPattern(int order, IEnumerable<(int row, int col, double value)> nonZeroEntries) { DokSymmetric dok = CreateEmpty(order); foreach (var (row, col, val) in nonZeroEntries) dok.columns[col].Add(row, val); return dok; } /// <summary> /// See <see cref="IMatrixBuilder.AddToEntry(int, int, double)"/> /// </summary> public void AddToEntry(int rowIdx, int colIdx, double value) { ProcessIndices(ref rowIdx, ref colIdx); if (columns[colIdx].TryGetValue(rowIdx, out double oldValue)) { columns[colIdx][rowIdx] = value + oldValue; } else columns[colIdx][rowIdx] = value; //The Dictionary columns[rowIdx] is indexed twice in both cases. Is it possible to only index it once? } /// <summary> /// See <see cref="ISymmetricMatrixBuilder.AddSubmatrix(IIndexable2D, IReadOnlyDictionary{int, int}, /// IReadOnlyDictionary{int, int})"/>. /// </summary> public void AddSubmatrix(IIndexable2D subMatrix, IReadOnlyDictionary<int, int> subRowsToGlobalRows, IReadOnlyDictionary<int, int> subColsToGlobalCols) { foreach (var colPair in subColsToGlobalCols) { int subCol = colPair.Key; foreach (var rowPair in subRowsToGlobalRows) { int subRow = rowPair.Key; int globalRow, globalCol; if (rowPair.Value <= colPair.Value) { globalRow = rowPair.Value; globalCol = colPair.Value; } else { globalRow = colPair.Value; globalCol = rowPair.Value; } double subValue = subMatrix[subRow, subCol]; if (columns[globalCol].TryGetValue(globalRow, out double oldGlobalValue)) { columns[globalCol][globalRow] = subValue + oldGlobalValue; } else columns[globalCol][globalRow] = subValue; } } } /// <summary> /// See <see cref="ISymmetricMatrixBuilder.AddSubmatrixSymmetric(IIndexable2D, IReadOnlyDictionary{int, int})"/>. /// </summary> public void AddSubmatrixSymmetric(IIndexable2D subMatrix, IReadOnlyDictionary<int, int> subIndicesToGlobalIndices) { foreach (var colPair in subIndicesToGlobalIndices) { int subCol = colPair.Key; int globalCol = colPair.Value; foreach (var rowPair in subIndicesToGlobalIndices) { int subRow = rowPair.Key; int globalRow = rowPair.Value; if (globalRow <= globalCol) { double subValue = subMatrix[subRow, subCol]; if (columns[globalCol].TryGetValue(globalRow, out double oldGlobalValue)) { columns[globalCol][globalRow] = subValue + oldGlobalValue; } else columns[globalCol][globalRow] = subValue; } } } } /// <summary> /// See <see cref="ISymmetricMatrixBuilder.AddSubmatrixSymmetric(IIndexable2D, int[], int[])"/>. /// </summary> public void AddSubmatrixSymmetric(IIndexable2D subMatrix, int[] subMatrixIndices, int[] globalIndices) { Debug.Assert(subMatrix.NumRows == subMatrix.NumColumns); Debug.Assert(globalIndices.Length == subMatrixIndices.Length); int numRelevantRows = subMatrixIndices.Length; for (int j = 0; j < numRelevantRows; ++j) { int subCol = subMatrixIndices[j]; int globalCol = globalIndices[j]; for (int i = 0; i < numRelevantRows; ++i) { int subRow = subMatrixIndices[i]; int globalRow = globalIndices[i]; if (globalRow <= globalCol) { double subValue = subMatrix[subRow, subCol]; if (columns[globalCol].TryGetValue(globalRow, out double oldGlobalValue)) { columns[globalCol][globalRow] = subValue + oldGlobalValue; } else columns[globalCol][globalRow] = subValue; } } } } /// <summary> /// See <see cref="ISymmetricMatrixBuilder.AddSubmatrixToLowerTriangle(IIndexable2D, IReadOnlyDictionary{int, int}, /// IReadOnlyDictionary{int, int})"/> /// </summary> public void AddSubmatrixToLowerTriangle(IIndexable2D subMatrix, IReadOnlyDictionary<int, int> subRowsToGlobalRows, IReadOnlyDictionary<int, int> subColsToGlobalCols) { foreach (var rowPair in subRowsToGlobalRows) // Transpose(Col major ordering) = Row major ordering { int subRow = rowPair.Key; int globalRow = rowPair.Value; foreach (var colPair in subColsToGlobalCols) { int subCol = colPair.Key; int globalCol = colPair.Value; double subValue = subMatrix[subRow, subCol]; // Transpose the access on the global matrix only. // This is equivalent to calling the indexer for each lower triangle entry, but without the explicit swap. if (columns[globalRow].TryGetValue(globalCol, out double oldGlobalValue)) { columns[globalRow][globalCol] = subValue + oldGlobalValue; } else columns[globalRow][globalCol] = subValue; } } } /// <summary> /// See <see cref="ISymmetricMatrixBuilder.AddSubmatrixToUpperTriangle(IIndexable2D, IReadOnlyDictionary{int, int}, /// IReadOnlyDictionary{int, int})"/> /// </summary> public void AddSubmatrixToUpperTriangle(IIndexable2D subMatrix, IReadOnlyDictionary<int, int> subRowsToGlobalRows, IReadOnlyDictionary<int, int> subColsToGlobalCols) { foreach (var colPair in subColsToGlobalCols) // Col major ordering { int subCol = colPair.Key; int globalCol = colPair.Value; foreach (var rowPair in subRowsToGlobalRows) { int subRow = rowPair.Key; int globalRow = rowPair.Value; double subValue = subMatrix[subRow, subCol]; if (columns[globalCol].TryGetValue(globalRow, out double oldGlobalValue)) { columns[globalCol][globalRow] = subValue + oldGlobalValue; } else columns[globalCol][globalRow] = subValue; } } } public (double[] values, int[] diagOffsets) BuildSkylineArrays() { //TODO: It may be worth it to create a DOK specifically for skyline. As you add entries to it, it will cache the // min row or the height for each column. Alternatively it could use SortedDictionary, but that is slow for // global matrix assembly var diagOffsets = new int[order + 1]; int nnz = 0; for (int j = 0; j < order; ++j) { diagOffsets[j] = nnz; nnz += j - columns[j].Keys.Min() + 1; // Height of column j including the diagonal entry } if (nnz == 0) throw new EmptyMatrixBuilderException("Cannot build symmetric CSC arrays from a DOK with nnz = 0."); diagOffsets[order] = nnz; //The last Skyline entry has diagOffset = nnz. var values = new double[nnz]; for (int j = 0; j < order; ++j) { int temp = diagOffsets[j] + j; foreach (var rowVal in columns[j]) { // offset = diagOffsets[j] + j - row int offset = temp - rowVal.Key; values[offset] = rowVal.Value; } } return (values, diagOffsets); } public SkylineMatrix BuildSkylineMatrix() { (double[] values, int[] diagOffsets) = BuildSkylineArrays(); return SkylineMatrix.CreateFromArrays(NumColumns, values, diagOffsets, false, false); } /// <summary> /// Creates the values and indexing arrays in CSC storage format of the upper triangle of the current symmetric matrix. /// This method should be called after fully defining the matrix in <see cref="DokSymmetric"/> format. /// </summary> /// <param name="sortColsOfEachCol">True to sort the column indices of the CSC matrix between colOffsets[j] and /// colOffsets[j+1] in ascending order. False to leave them unordered. Ordered rows might result in better /// performance during multiplications or they might be required by 3rd party libraries. Conversely, leaving them /// unordered will be faster during creation of the CSC matrix.</param> /// <exception cref="EmptyMatrixBuilderException">Thrown if no non-zero entries have been defined yet.</exception> public (double[] values, int[] rowIndices, int[] columnOffsets) BuildSymmetricCscArrays(bool sortRowsOfEachCol) { int[] colOffsets = new int[order + 1]; int nnz = 0; for (int j = 0; j < order; ++j) { colOffsets[j] = nnz; nnz += columns[j].Count; } if (nnz == 0) throw new EmptyMatrixBuilderException("Cannot build symmetric CSC arrays from a DOK with nnz = 0."); colOffsets[order] = nnz; //The last CSC entry has colOffset = nnz. int[] rowIndices = new int[nnz]; double[] values = new double[nnz]; int counter = 0; if (sortRowsOfEachCol) { for (int j = 0; j < order; ++j) { //TODO: perhaps passing the dictionarirs to new SortedDictionary() is faster than LINQ foreach (var rowVal in columns[j].OrderBy(pair => pair.Key)) { rowIndices[counter] = rowVal.Key; values[counter] = rowVal.Value; ++counter; } } } else { for (int j = 0; j < order; ++j) { foreach (var rowVal in columns[j]) { rowIndices[counter] = rowVal.Key; values[counter] = rowVal.Value; ++counter; } } } return (values, rowIndices, colOffsets); } /// <summary> /// Initializes a <see cref="SymmetricCscMatrix"/> representation of the current matrix. This method should be /// called after fully defining the matrix in <see cref="DokSymmetric"/> format. /// </summary> /// <param name="sortColsOfEachCol">True to sort the column indices of the CSC matrix between colOffsets[j] and /// colOffsets[j+1] in ascending order. False to leave them unordered. Ordered rows might result in better /// performance during multiplications or they might be required by 3rd party libraries. Conversely, leaving them /// unordered will be faster during creation of the CSC matrix.</param> /// <exception cref="EmptyMatrixBuilderException">Thrown if no non-zero entries have been defined yet.</exception> public SymmetricCscMatrix BuildSymmetricCscMatrix(bool sortRowsOfEachCol) { (double[] values, int[] rowIndices, int[] colOffsets) = BuildSymmetricCscArrays(sortRowsOfEachCol); return SymmetricCscMatrix.CreateFromArrays(NumColumns, values, rowIndices, colOffsets, false); } /// <summary> /// Frees all memory held by this <see cref="DokSymmetric"/> instance. Afterwards this object cannot be reused. /// Therefore this method should be called to save up space after building the matrix or its internal arrays. /// </summary> public void Clear() => columns = null; /// <summary> /// See <see cref="ISparseMatrix.CountNonZeros"/>. /// </summary> public int CountNonZeros() { int count = 0; for (int j = 0; j < order; ++j) { //count += (columns[j].Count - 1) * 2 + 1; // Faster, but doesn't work if the diagonal is not present. foreach (var rowVal in columns[j]) { if (rowVal.Key == j) ++count; else count += 2; //Each upper triangle entries has a corresponding lower triangle entry. } } return count; } /// <summary> /// See <see cref="ISparseSymmetricMatrix.CountNonZerosUpper"/>. /// </summary> public int CountNonZerosUpper() { int count = 0; for (int j = 0; j < order; ++j) count += columns[j].Count; return count; } /// <summary> /// See <see cref="ISparseMatrix.EnumerateNonZeros"/>. /// </summary> public IEnumerable<(int row, int col, double value)> EnumerateNonZeros() { for (int j = 0; j < order; ++j) { foreach (var rowVal in columns[j]) { if (rowVal.Key == j) yield return (rowVal.Key, j, rowVal.Value); else //Each upper triangle entries has a corresponding lower triangle entry. { yield return (rowVal.Key, j, rowVal.Value); yield return (j, rowVal.Key, rowVal.Value); } } } } /// <summary> /// See <see cref="ISparseSymmetricMatrix.EnumerateNonZerosUpper"/>. /// </summary> public IEnumerable<(int row, int col, double value)> EnumerateNonZerosUpper() { for (int j = 0; j < order; ++j) { foreach (var rowVal in columns[j]) { yield return (rowVal.Key, j, rowVal.Value); } } } /// <summary> /// See <see cref="IIndexable2D.Equals(IIndexable2D, double)"/>. /// </summary> public bool Equals(IIndexable2D other, double tolerance = 1e-13) { return DenseStrategies.AreEqual(this, other, tolerance); } /// <summary> /// Returns the column with index = <paramref name="colIdx"/> as a sparse vector. Note that the length of the returned /// vector is equal to this.<see cref="NumRows"/>. Since the matrix is symmetric, this method also works for getting /// the row with index = <paramref name="colIdx"/>. /// </summary> /// <param name="colIdx">The index of the column to return. Constraints: Column <paramref name="colIdx"/> must be stored /// and 0 &lt;= <paramref name="colIdx"/> &lt; this.<see cref="NumColumns"/>.</param> /// <exception cref="IndexOutOfRangeException">Thrown if <paramref name="colIdx"/> or <paramref name="tabooRows"/> /// violate the described constraints.</exception> public SparseVector GetColumn(int colIdx) { //TODO: implement another data structure that only holds some sparse columns, but is efficient in returning them whole // The super-diagonal part is readily available. var wholeColumn = new SortedDictionary<int, double>(columns[colIdx]); // The sub-diagonal part of the column is stored as the super-diagonal part of the row with the same index // It must be built by searching all subsequent columns, which is inefficient for (int j = colIdx + 1; j < order; ++j) { bool isNonZero = columns[j].TryGetValue(colIdx, out double value); if (isNonZero) wholeColumn.Add(j, value); } return SparseVector.CreateFromDictionary(order, wholeColumn); } /// <summary> /// Returns the column with index = <paramref name="colIdx"/> as a vector. However, the entries with row index that /// belongs in <paramref name="tabooRows"/> will be set to 0. More accurately, they will not be included in the /// sparsity pattern of the returned <see cref="SparseVector"/>. Note that the length of the returned vector is /// equal to this.<see cref="NumRows"/>. Since the matrix is symmetric, this method also works for getting the row /// with index = <paramref name="colIdx"/>. /// </summary> /// <param name="colIdx">The index of the column to return. Constraints: Column <paramref name="colIdx"/> must be stored /// and 0 &lt;= <paramref name="colIdx"/> &lt; this.<see cref="NumColumns"/>.</param> /// <param name="tabooRows">The entries of the returned column vector at the indices specified by /// <paramref name="tabooRows"/> will be equal to 0. Constraints: foreach rowIdx in <paramref name="tabooRows"/>: /// 0 &lt;= rowIdx &lt; this.<see cref="NumRows"/>.</param> /// <exception cref="IndexOutOfRangeException">Thrown if <paramref name="colIdx"/> or <paramref name="tabooRows"/> /// violate the described constraints.</exception> public SparseVector GetColumnWithoutRows(int colIdx, ISet<int> tabooRows) { //TODO: it's not really slicing, as the rejected rows are set to 0 // The super-diagonal part is straightforward var wholeColumn = new SortedDictionary<int, double>(); foreach (var rowVal in columns[colIdx]) { if (!tabooRows.Contains(rowVal.Key)) wholeColumn.Add(rowVal.Key, rowVal.Value); } // The sub-diagonal part of the column is stored as the super-diagonal part of the row with the same index // It must be accessed by searching all subsequent columns, which is inefficient for (int i = colIdx + 1; i < order; ++i) { if (!tabooRows.Contains(i)) { bool isNonZero = columns[i].TryGetValue(colIdx, out double value); if (isNonZero) wholeColumn.Add(i, value); } } return SparseVector.CreateFromDictionary(order, wholeColumn); } /// <summary> /// Returns a <see cref="Vector"/> with the entries of the matrix's main diagonal and the index of the first zero entry. /// If there are no zero entries, -1 is returned as the index. /// </summary> public (Vector diagonal, int firstZeroIdx) GetDiagonal() { (double[] diagonal, int firstZeroIdx) = GetDiagonalAsArray(); return (Vector.CreateFromArray(diagonal, false), firstZeroIdx); } /// <summary> /// Returns an array with the entries of the matrix's main diagonal and the index of the first zero entry. /// If there are no zero entries, -1 is returned as the index. /// </summary> public (double[] diagonal, int firstZeroIdx) GetDiagonalAsArray() { double[] diag = new double[order]; int firstZeroIdx = -1; for (int j = 0; j < order; ++j) { bool isStored = columns[j].TryGetValue(j, out double val); if (isStored) diag[j] = val; else { diag[j] = 0.0; firstZeroIdx = j; } } return (diag, firstZeroIdx); } /// <summary> /// See <see cref="ISparseMatrix.GetSparseFormat"/>. /// </summary> public SparseFormat GetSparseFormat() { //Perhaps there should be a dedicated symmetric CSC format, identical to CSC. (double[] values, int[] rowIndices, int[] colOffsets) = BuildSymmetricCscArrays(false); var format = new SparseFormat(); format.RawValuesTitle = "Values"; format.RawValuesArray = values; format.RawIndexArrays.Add("Row indices", rowIndices); format.RawIndexArrays.Add("Column offsets", colOffsets); return format; } /// <summary> /// Creates a new <see cref="DokSymmetric"/> by copying only the entries whose row and column index belongs to /// <paramref name="rowsColsToKeep"/>. /// </summary> /// <param name="rowsColsToKeep"> /// Only the entries (i, j) where i and j belongs to <paramref name="rowsColsToKeep"/> will be copied to the new matrix. /// The order of the indices is important. E.g. if <paramref name="rowsColsToKeep"/> = [1, 0], then the resulting /// submatrix will be {{ this[1,1], this[1,0] }, { this[0,1], this[0,0] }} /// </param> public DokSymmetric GetSubmatrix(int[] rowsColsToKeep) { //TODO: work with the stored dictionaries to speed this up. However keep in mind that if keep = {2, 1} then some // transposition is necessary. int subOrder = rowsColsToKeep.Length; var submatrix = DokSymmetric.CreateEmpty(subOrder); for (int subJ = 0; subJ < subOrder; ++subJ) { int thisJ = rowsColsToKeep[subJ]; for (int subI = 0; subI <= subJ; ++subI) { int thisI = rowsColsToKeep[subI]; double value = this[thisI, thisJ]; //TODO: This should be done explicitly if (value != 0.0) submatrix[subI, subJ] = value; } } return submatrix; } /// <summary> /// Sets the column with index <paramref name="colIdx"/> to be equal to the provided <paramref name="newColumn"/>. /// Since the matrix is symmetric, this method also works for modifying the row with index = <paramref name="colIdx"/>. /// </summary> /// <param name="colIdx">The index of the column to modify. Constraints: /// and 0 &lt;= <paramref name="colIdx"/> &lt; this.<see cref="NumColumns"/>.</param> /// <param name="newColumn">The new values that column <paramref name="colIdx"/> will be set to. Constraints: /// <paramref name="newColumn"/>.<see cref="IIndexable1D.Length"/> == this.<see cref="NumRows"/>.</param> public void SetColumn(int colIdx, SparseVector newColumn) { SetColumnToZero(colIdx); // First remove everything int[] rowIndices = newColumn.RawIndices; double[] values = newColumn.RawValues; // The super-diagonal part is straightforward int t = 0; for (; ; ++t) { int rowIdx = rowIndices[t]; if (rowIdx > colIdx) break; columns[colIdx].Add(rowIdx, values[t]); } // The sub-diagonal part of the column is stored as the super-diagonal part of the row with the same index // It must be accessed by searching the relevant subsequent columns for (; t < rowIndices.Length; ++t) { int rowIdx = rowIndices[t]; columns[rowIdx].Add(colIdx, values[t]); // It should have been emptied when it was set to identity } } /// <summary> /// Sets the column with index <paramref name="colIdx"/> to have 1.0 at the main diagonal entry and 0.0 everywhere else. /// Since the matrix is symmetric, this method also works for modifying the row with index = <paramref name="colIdx"/>. /// </summary> /// <param name="colIdx">The index of the column to modify. Constraints: /// and 0 &lt;= <paramref name="colIdx"/> &lt; this.<see cref="NumColumns"/>.</param> public void SetColumnToIdentity(int colIdx) { SetColumnToZero(colIdx); // First remove everything columns[colIdx].Add(colIdx, 1.0); } /// <summary> /// Sets the column with index <paramref name="colIdx"/> to have 0.0 at all entries. /// Since the matrix is symmetric, this method also works for modifying the row with index = <paramref name="colIdx"/>. /// </summary> /// <param name="colIdx">The index of the column to modify. Constraints: /// and 0 &lt;= <paramref name="colIdx"/> &lt; this.<see cref="NumColumns"/>.</param> public void SetColumnToZero(int colIdx) { // The super-diagonal part of the column is straightforward columns[colIdx].Clear(); // The sub-diagonal part of the column is stored as the super-diagonal part of the row with the same index // It must be accessed by searching all subsequent columns, which is inefficient. for (int j = colIdx + 1; j < order; ++j) { columns[j].Remove(colIdx); // If it is 0, then nothing will happen. } } /// <summary> /// Like <see cref="this[int, int]"/>, but will not check or transpose the entry. /// </summary> /// <param name="rowIdx">The row index: 0 &lt;= <paramref name="rowIdx"/> &lt; <see cref="NumRows"/>.</param> /// <param name="colIdx">The column index: 0 &lt;= <paramref name="colIdx"/> &lt; <see cref="NumColumns"/>.</param> /// <param name="value">The value to set.</param> public void SetEntryUpper(int rowIdx, int colIdx, double value) => columns[colIdx][rowIdx] = value; /// <summary> /// Sets all entries that are on the main diagonal and have not been explicitly modified by a previous method or /// constructor, and thus are equal to 0, to 1. /// </summary> public void SetStructuralZeroDiagonalEntriesToUnity() { for (int d = 0; d < NumColumns; ++d) { bool structuralZero = !columns[d].ContainsKey(d); if (structuralZero) columns[d][d] = 1.0; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void ProcessIndices(ref int rowIdx, ref int colIdx) { //Perhaps this should be manually inlined. Testing needed. if (rowIdx > colIdx) { int swap = rowIdx; rowIdx = colIdx; colIdx = swap; } } /// <summary> /// Use this method if 1) both the global DOK and the element matrix are symmetric and 2) the rows and columns correspond /// to the same degrees of freedom. The caller is responsible for making sure that both matrices are symmetric and that /// the dimensions and dofs of the element matrix and dof mappings match. /// </summary> /// <param name="elementMatrix">The element submatrix, entries of which will be added to the global DOK. It must be /// symmetric and its <see cref="IIndexable2D.NumColumns"/> = <see cref="IIndexable2D.NumRows"/> must be equal to /// elemenDofs.Length = globalDofs.Length.</param> /// <param name="elementDofs">The entries in the element matrix to be added to the global matrix. Specificaly, pairs of /// (elementDofs[i], elementDofs[j]) will be added to (globalDofs[i], globalDofs[j]).</param> /// <param name="globalDofs">The entries in the global matrix where element matrix entries will be added to. Specificaly, /// pairs of (elementDofs[i], elementDofs[j]) will be added to (globalDofs[i], globalDofs[j]).</param> private void AddSubmatrixSymmetricOLD(IIndexable2D elementMatrix, int[] elementDofs, int[] globalDofs) //TODO: this should be reworked { int n = elementDofs.Length; for (int j = 0; j < n; ++j) { int elementCol = elementDofs[j]; int globalCol = globalDofs[j]; //Diagonal entry if (columns[globalCol].TryGetValue(globalCol, out double oldGlobalDiagValue)) { columns[globalCol][globalCol] = elementMatrix[elementCol, elementCol] + oldGlobalDiagValue; } else columns[globalCol][globalCol] = elementMatrix[elementCol, elementCol]; //Non diagonal entries for (int i = 0; i <= j; ++i) { int elementRow = elementDofs[j]; int globalRow = globalDofs[j]; double newGlobalValue = elementMatrix[elementRow, elementCol]; if (columns[globalCol].TryGetValue(globalRow, out double oldGlobalValue)) { newGlobalValue += oldGlobalValue; } columns[globalCol][globalRow] = newGlobalValue; } } } } }
50.711514
143
0.561658
[ "Apache-2.0" ]
TheoChristo/Parallel_Tumor_Modelling
Parallel_Tumor_ModellingConsoleApp/Parallel_Tumor_ModellingConsoleApp/MSolveLib/ISAAR.MSolve.LinearAlgebra/Matrices/Builders/DokSymmetric.cs
39,202
C#
using System; using NetRuntimeSystem = System; using System.ComponentModel; using NetOffice.Attributes; namespace NetOffice.WordApi { /// <summary> /// DispatchInterface Frame /// SupportByVersion Word, 9,10,11,12,14,15,16 /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.Frame"/> </remarks> [SupportByVersion("Word", 9,10,11,12,14,15,16)] [EntityType(EntityType.IsDispatchInterface)] public class Frame : COMObject { #pragma warning disable #region Type Information /// <summary> /// Instance Type /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden] public override Type InstanceType { get { return LateBindingApiWrapperType; } } private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(Frame); return _type; } } #endregion #region Ctor /// <param name="factory">current used factory core</param> /// <param name="parentObject">object there has created the proxy</param> /// <param name="proxyShare">proxy share instead if com proxy</param> public Frame(Core factory, ICOMObject parentObject, COMProxyShare proxyShare) : base(factory, parentObject, proxyShare) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> public Frame(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Frame(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Frame(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Frame(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType) { } ///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Frame(ICOMObject replacedObject) : base(replacedObject) { } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Frame() : base() { } /// <param name="progId">registered progID</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Frame(string progId) : base(progId) { } #endregion #region Properties /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.Frame.Application"/> </remarks> [SupportByVersion("Word", 9,10,11,12,14,15,16)] public NetOffice.WordApi.Application Application { get { return Factory.ExecuteKnownReferencePropertyGet<NetOffice.WordApi.Application>(this, "Application", NetOffice.WordApi.Application.LateBindingApiWrapperType); } } /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.Frame.Creator"/> </remarks> [SupportByVersion("Word", 9,10,11,12,14,15,16)] public Int32 Creator { get { return Factory.ExecuteInt32PropertyGet(this, "Creator"); } } /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16 /// Get /// Unknown COM Proxy /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.Frame.Parent"/> </remarks> [SupportByVersion("Word", 9,10,11,12,14,15,16), ProxyResult] public object Parent { get { return Factory.ExecuteReferencePropertyGet(this, "Parent"); } } /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.Frame.HeightRule"/> </remarks> [SupportByVersion("Word", 9,10,11,12,14,15,16)] public NetOffice.WordApi.Enums.WdFrameSizeRule HeightRule { get { return Factory.ExecuteEnumPropertyGet<NetOffice.WordApi.Enums.WdFrameSizeRule>(this, "HeightRule"); } set { Factory.ExecuteEnumPropertySet(this, "HeightRule", value); } } /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.Frame.WidthRule"/> </remarks> [SupportByVersion("Word", 9,10,11,12,14,15,16)] public NetOffice.WordApi.Enums.WdFrameSizeRule WidthRule { get { return Factory.ExecuteEnumPropertyGet<NetOffice.WordApi.Enums.WdFrameSizeRule>(this, "WidthRule"); } set { Factory.ExecuteEnumPropertySet(this, "WidthRule", value); } } /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.Frame.HorizontalDistanceFromText"/> </remarks> [SupportByVersion("Word", 9,10,11,12,14,15,16)] public Single HorizontalDistanceFromText { get { return Factory.ExecuteSinglePropertyGet(this, "HorizontalDistanceFromText"); } set { Factory.ExecuteValuePropertySet(this, "HorizontalDistanceFromText", value); } } /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.Frame.Height"/> </remarks> [SupportByVersion("Word", 9,10,11,12,14,15,16)] public Single Height { get { return Factory.ExecuteSinglePropertyGet(this, "Height"); } set { Factory.ExecuteValuePropertySet(this, "Height", value); } } /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.Frame.HorizontalPosition"/> </remarks> [SupportByVersion("Word", 9,10,11,12,14,15,16)] public Single HorizontalPosition { get { return Factory.ExecuteSinglePropertyGet(this, "HorizontalPosition"); } set { Factory.ExecuteValuePropertySet(this, "HorizontalPosition", value); } } /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.Frame.LockAnchor"/> </remarks> [SupportByVersion("Word", 9,10,11,12,14,15,16)] public bool LockAnchor { get { return Factory.ExecuteBoolPropertyGet(this, "LockAnchor"); } set { Factory.ExecuteValuePropertySet(this, "LockAnchor", value); } } /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.Frame.RelativeHorizontalPosition"/> </remarks> [SupportByVersion("Word", 9,10,11,12,14,15,16)] public NetOffice.WordApi.Enums.WdRelativeHorizontalPosition RelativeHorizontalPosition { get { return Factory.ExecuteEnumPropertyGet<NetOffice.WordApi.Enums.WdRelativeHorizontalPosition>(this, "RelativeHorizontalPosition"); } set { Factory.ExecuteEnumPropertySet(this, "RelativeHorizontalPosition", value); } } /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.Frame.RelativeVerticalPosition"/> </remarks> [SupportByVersion("Word", 9,10,11,12,14,15,16)] public NetOffice.WordApi.Enums.WdRelativeVerticalPosition RelativeVerticalPosition { get { return Factory.ExecuteEnumPropertyGet<NetOffice.WordApi.Enums.WdRelativeVerticalPosition>(this, "RelativeVerticalPosition"); } set { Factory.ExecuteEnumPropertySet(this, "RelativeVerticalPosition", value); } } /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.Frame.VerticalDistanceFromText"/> </remarks> [SupportByVersion("Word", 9,10,11,12,14,15,16)] public Single VerticalDistanceFromText { get { return Factory.ExecuteSinglePropertyGet(this, "VerticalDistanceFromText"); } set { Factory.ExecuteValuePropertySet(this, "VerticalDistanceFromText", value); } } /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.Frame.VerticalPosition"/> </remarks> [SupportByVersion("Word", 9,10,11,12,14,15,16)] public Single VerticalPosition { get { return Factory.ExecuteSinglePropertyGet(this, "VerticalPosition"); } set { Factory.ExecuteValuePropertySet(this, "VerticalPosition", value); } } /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.Frame.Width"/> </remarks> [SupportByVersion("Word", 9,10,11,12,14,15,16)] public Single Width { get { return Factory.ExecuteSinglePropertyGet(this, "Width"); } set { Factory.ExecuteValuePropertySet(this, "Width", value); } } /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.Frame.TextWrap"/> </remarks> [SupportByVersion("Word", 9,10,11,12,14,15,16)] public bool TextWrap { get { return Factory.ExecuteBoolPropertyGet(this, "TextWrap"); } set { Factory.ExecuteValuePropertySet(this, "TextWrap", value); } } /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.Frame.Shading"/> </remarks> [SupportByVersion("Word", 9,10,11,12,14,15,16)] public NetOffice.WordApi.Shading Shading { get { return Factory.ExecuteKnownReferencePropertyGet<NetOffice.WordApi.Shading>(this, "Shading", NetOffice.WordApi.Shading.LateBindingApiWrapperType); } } /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.Frame.Borders"/> </remarks> [SupportByVersion("Word", 9,10,11,12,14,15,16)] public NetOffice.WordApi.Borders Borders { get { return Factory.ExecuteKnownReferencePropertyGet<NetOffice.WordApi.Borders>(this, "Borders", NetOffice.WordApi.Borders.LateBindingApiWrapperType); } set { Factory.ExecuteReferencePropertySet(this, "Borders", value); } } /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.Frame.Range"/> </remarks> [SupportByVersion("Word", 9,10,11,12,14,15,16)] public NetOffice.WordApi.Range Range { get { return Factory.ExecuteKnownReferencePropertyGet<NetOffice.WordApi.Range>(this, "Range", NetOffice.WordApi.Range.LateBindingApiWrapperType); } } #endregion #region Methods /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.Frame.Delete"/> </remarks> [SupportByVersion("Word", 9,10,11,12,14,15,16)] public void Delete() { Factory.ExecuteMethod(this, "Delete"); } /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.Frame.Select"/> </remarks> [SupportByVersion("Word", 9,10,11,12,14,15,16)] public void Select() { Factory.ExecuteMethod(this, "Select"); } /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.Frame.Copy"/> </remarks> [SupportByVersion("Word", 9,10,11,12,14,15,16)] public void Copy() { Factory.ExecuteMethod(this, "Copy"); } /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.Frame.Cut"/> </remarks> [SupportByVersion("Word", 9,10,11,12,14,15,16)] public void Cut() { Factory.ExecuteMethod(this, "Cut"); } #endregion #pragma warning restore } }
30.165591
161
0.66593
[ "MIT" ]
NetOfficeFw/NetOffice
Source/Word/DispatchInterfaces/Frame.cs
14,029
C#
namespace CloselinkAPI.Client { /// <summary> /// <see cref="GlobalConfiguration"/> provides a compile-time extension point for globally configuring /// API Clients. /// </summary> /// <remarks> /// A customized implementation via partial class may reside in another file and may /// be excluded from automatic generation via a .swagger-codegen-ignore file. /// </remarks> public partial class GlobalConfiguration : Configuration { } }
32
106
0.679167
[ "MIT" ]
closelink/closelink-api-net
CloselinkAPI/Client/GlobalConfiguration.cs
480
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.ComponentModel; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; namespace System.Resources.Extensions { public partial class DeserializingResourceReader { private bool _assumeBinaryFormatter; private BinaryFormatter? _formatter; private bool ValidateReaderType(string readerType) { // our format? if (TypeNameComparer.Instance.Equals(readerType, PreserializedResourceWriter.DeserializingResourceReaderFullyQualifiedName)) { return true; } // default format? if (TypeNameComparer.Instance.Equals(readerType, PreserializedResourceWriter.ResourceReaderFullyQualifiedName)) { // we can read the default format, we just assume BinaryFormatter and don't // read the SerializationFormat _assumeBinaryFormatter = true; return true; } return false; } // Issue https://github.com/dotnet/runtime/issues/39292 tracks finding an alternative to BinaryFormatter #pragma warning disable SYSLIB0011 private object ReadBinaryFormattedObject() { if (_formatter == null) { _formatter = new BinaryFormatter() { Binder = new UndoTruncatedTypeNameSerializationBinder() }; } return _formatter.Deserialize(_store.BaseStream); } #pragma warning restore SYSLIB0011 internal sealed class UndoTruncatedTypeNameSerializationBinder : SerializationBinder { public override Type? BindToType(string assemblyName, string typeName) { Type? type = null; // determine if we have a mangled generic type name if (typeName != null && assemblyName != null && !AreBracketsBalanced(typeName)) { // undo the mangling that may have happened with .NETFramework's // incorrect ResXSerialization binder. typeName = typeName + ", " + assemblyName; type = Type.GetType(typeName, throwOnError: false, ignoreCase:false); } // if type is null we'll fall back to the default type binder which is preferable // since it is backed by a cache return type; } private static bool AreBracketsBalanced(string typeName) { // make sure brackets are balanced int firstBracket = typeName.IndexOf('['); if (firstBracket == -1) { return true; } int brackets = 1; for (int i = firstBracket + 1; i < typeName.Length; i++) { if (typeName[i] == '[') { brackets++; } else if (typeName[i] == ']') { brackets--; if (brackets < 0) { // unbalanced, closing bracket without opening break; } } } return brackets == 0; } } private object DeserializeObject(int typeIndex) { Type type = FindType(typeIndex); if (_assumeBinaryFormatter) { return ReadBinaryFormattedObject(); } // read type SerializationFormat format = (SerializationFormat)_store.Read7BitEncodedInt(); object value; // read data switch (format) { case SerializationFormat.BinaryFormatter: { // read length int length = _store.Read7BitEncodedInt(); if (length < 0) { throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResourceDataLengthInvalid, length)); } long originalPosition = _store.BaseStream.Position; value = ReadBinaryFormattedObject(); if (type == typeof(UnknownType)) { // type information was omitted at the time of writing // allow the payload to define the type type = value.GetType(); } long bytesRead = _store.BaseStream.Position - originalPosition; // Ensure BF read what we expected. if (bytesRead != length) { throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResourceDataLengthInvalid, length)); } break; } case SerializationFormat.TypeConverterByteArray: { // read length int length = _store.Read7BitEncodedInt(); if (length < 0) { throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResourceDataLengthInvalid, length)); } byte[] data = _store.ReadBytes(length); TypeConverter converter = TypeDescriptor.GetConverter(type); if (converter == null) { throw new TypeLoadException(SR.Format(SR.TypeLoadException_CannotLoadConverter, type)); } value = converter.ConvertFrom(data)!; break; } case SerializationFormat.TypeConverterString: { string stringData = _store.ReadString(); TypeConverter converter = TypeDescriptor.GetConverter(type); if (converter == null) { throw new TypeLoadException(SR.Format(SR.TypeLoadException_CannotLoadConverter, type)); } value = converter.ConvertFromInvariantString(stringData)!; break; } case SerializationFormat.ActivatorStream: { // read length int length = _store.Read7BitEncodedInt(); if (length < 0) { throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResourceDataLengthInvalid, length)); } Stream stream; if (_store.BaseStream is UnmanagedMemoryStream ums) { // For the case that we've memory mapped in the .resources // file, just return a Stream pointing to that block of memory. unsafe { stream = new UnmanagedMemoryStream(ums.PositionPointer, length, length, FileAccess.Read); } } else { byte[] bytes = _store.ReadBytes(length); // Lifetime of memory == lifetime of this stream. stream = new MemoryStream(bytes, false); } value = Activator.CreateInstance(type, new object[] { stream })!; break; } default: throw new BadImageFormatException(SR.BadImageFormat_TypeMismatch); } // Make sure we deserialized the type that we expected. // This protects against bad typeconverters or bad binaryformatter payloads. if (value.GetType() != type) throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResType_SerBlobMismatch, type.FullName, value.GetType().FullName)); return value; } } }
37.784483
145
0.481748
[ "MIT" ]
333fred/runtime
src/libraries/System.Resources.Extensions/src/System/Resources/Extensions/DeserializingResourceReader.cs
8,766
C#
using System.Collections.Generic; using System.Collections.ObjectModel; using System.Net.Http.Headers; using System.Web.Http.Description; using ASPNETIdentityChavesInt.Areas.HelpPage.ModelDescriptions; namespace ASPNETIdentityChavesInt.Areas.HelpPage.Models { /// <summary> /// The model that represents an API displayed on the help page. /// </summary> public class HelpPageApiModel { /// <summary> /// Initializes a new instance of the <see cref="HelpPageApiModel"/> class. /// </summary> public HelpPageApiModel() { UriParameters = new Collection<ParameterDescription>(); SampleRequests = new Dictionary<MediaTypeHeaderValue, object>(); SampleResponses = new Dictionary<MediaTypeHeaderValue, object>(); ErrorMessages = new Collection<string>(); } /// <summary> /// Gets or sets the <see cref="ApiDescription"/> that describes the API. /// </summary> public ApiDescription ApiDescription { get; set; } /// <summary> /// Gets or sets the <see cref="ParameterDescription"/> collection that describes the URI parameters for the API. /// </summary> public Collection<ParameterDescription> UriParameters { get; private set; } /// <summary> /// Gets or sets the documentation for the request. /// </summary> public string RequestDocumentation { get; set; } /// <summary> /// Gets or sets the <see cref="ModelDescription"/> that describes the request body. /// </summary> public ModelDescription RequestModelDescription { get; set; } /// <summary> /// Gets the request body parameter descriptions. /// </summary> public IList<ParameterDescription> RequestBodyParameters { get { return GetParameterDescriptions(RequestModelDescription); } } /// <summary> /// Gets or sets the <see cref="ModelDescription"/> that describes the resource. /// </summary> public ModelDescription ResourceDescription { get; set; } /// <summary> /// Gets the resource property descriptions. /// </summary> public IList<ParameterDescription> ResourceProperties { get { return GetParameterDescriptions(ResourceDescription); } } /// <summary> /// Gets the sample requests associated with the API. /// </summary> public IDictionary<MediaTypeHeaderValue, object> SampleRequests { get; private set; } /// <summary> /// Gets the sample responses associated with the API. /// </summary> public IDictionary<MediaTypeHeaderValue, object> SampleResponses { get; private set; } /// <summary> /// Gets the error messages associated with this model. /// </summary> public Collection<string> ErrorMessages { get; private set; } private static IList<ParameterDescription> GetParameterDescriptions(ModelDescription modelDescription) { ComplexTypeModelDescription complexTypeModelDescription = modelDescription as ComplexTypeModelDescription; if (complexTypeModelDescription != null) { return complexTypeModelDescription.Properties; } CollectionModelDescription collectionModelDescription = modelDescription as CollectionModelDescription; if (collectionModelDescription != null) { complexTypeModelDescription = collectionModelDescription.ElementDescription as ComplexTypeModelDescription; if (complexTypeModelDescription != null) { return complexTypeModelDescription.Properties; } } return null; } } }
36.814815
123
0.617203
[ "MIT" ]
DesignLiquido/CodingCraftVideos
ASPNETIdentityChavesInt/ASPNETIdentityChavesInt/Areas/HelpPage/Models/HelpPageApiModel.cs
3,976
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xamarin.Forms; #if __ANDROID__ using Xamarin.Forms.Platform.Android; #elif TIZEN4_0 using Xamarin.Forms.Platform.Tizen; #elif __IOS__ using Xamarin.Forms.Platform.iOS; #endif namespace Xamarin.Forms.Platform { internal static class Loader { internal static void Load () { } } #if !WINDOWS_PHONE && !WINDOWS_PHONE_APP && !TIZEN4_0 [RenderWith(typeof(BoxRenderer))] #else [RenderWith (typeof(BoxViewRenderer))] #endif internal class _BoxViewRenderer { } [RenderWith(typeof(EntryRenderer))] internal class _EntryRenderer { } [RenderWith (typeof (EditorRenderer))] internal class _EditorRenderer { } #if __ANDROID__ [RenderWith(typeof(Xamarin.Forms.Platform.Android.LabelRenderer))] #else [RenderWith (typeof (LabelRenderer))] #endif internal class _LabelRenderer { } #if __ANDROID__ [RenderWith(typeof(Xamarin.Forms.Platform.Android.ImageRenderer))] #else [RenderWith (typeof (ImageRenderer))] #endif internal class _ImageRenderer { } [RenderWith (typeof (ButtonRenderer))] internal class _ButtonRenderer { } [RenderWith(typeof(ImageButtonRenderer))] internal class _ImageButtonRenderer { } #if __ANDROID__ [RenderWith(typeof(RadioButtonRenderer))] #elif !TIZEN4_0 [RenderWith(typeof(RadioButtonRenderer))] #endif internal class _RadioButtonRenderer { } [RenderWith (typeof (TableViewRenderer))] internal class _TableViewRenderer { } [RenderWith (typeof (ListViewRenderer))] internal class _ListViewRenderer { } #if !TIZEN4_0 [RenderWith (typeof (CollectionViewRenderer))] #else [RenderWith (typeof (StructuredItemsViewRenderer))] #endif internal class _CollectionViewRenderer { } [RenderWith (typeof (CarouselViewRenderer))] internal class _CarouselViewRenderer { } [RenderWith (typeof (SliderRenderer))] internal class _SliderRenderer { } #if __IOS__ [RenderWith (typeof (WkWebViewRenderer))] internal class _WebViewRenderer { } #else [RenderWith(typeof(WebViewRenderer))] internal class _WebViewRenderer { } #endif [RenderWith (typeof (SearchBarRenderer))] internal class _SearchBarRenderer { } [RenderWith (typeof (SwitchRenderer))] internal class _SwitchRenderer { } [RenderWith (typeof (DatePickerRenderer))] internal class _DatePickerRenderer { } [RenderWith (typeof (TimePickerRenderer))] internal class _TimePickerRenderer { } [RenderWith (typeof (PickerRenderer))] internal class _PickerRenderer { } [RenderWith (typeof (StepperRenderer))] internal class _StepperRenderer { } [RenderWith (typeof (ProgressBarRenderer))] internal class _ProgressBarRenderer { } [RenderWith (typeof (ScrollViewRenderer))] internal class _ScrollViewRenderer { } [RenderWith (typeof (ActivityIndicatorRenderer))] internal class _ActivityIndicatorRenderer { } [RenderWith (typeof (FrameRenderer))] internal class _FrameRenderer { } #if __ANDROID__ // current previewer doesn't work with appcompat so this renderer is here for the previewer only // once previewer switches to appcompat then we can remove this [RenderWith(typeof(CheckBoxDesignerRenderer))] internal class _CheckBoxRenderer { } #endif [RenderWith(typeof(IndicatorViewRenderer))] internal class _IndicatorViewRenderer { } #if __IOS__ // current previewer doesn't work with appcompat so this renderer is here for the previewer only // once previewer switches to appcompat then we can remove this [RenderWith(typeof(CheckBoxRenderer))] internal class _CheckBoxRenderer { } #endif #if !WINDOWS_PHONE && !WINDOWS_PHONE_APP && !TIZEN4_0 [RenderWith (typeof (OpenGLViewRenderer))] #else [RenderWith (null)] #endif internal class _OpenGLViewRenderer { } #if !WINDOWS_PHONE && !WINDOWS_PHONE_APP && !TIZEN4_0 [RenderWith (typeof (TabbedRenderer))] #else [RenderWith (typeof (TabbedPageRenderer))] #endif internal class _TabbedPageRenderer { } #if !WINDOWS_PHONE && !WINDOWS_PHONE_APP && !TIZEN4_0 [RenderWith (typeof (NavigationRenderer))] #else [RenderWith (typeof (NavigationPageRenderer))] #endif internal class _NavigationPageRenderer { } [RenderWith (typeof (CarouselPageRenderer))] internal class _CarouselPageRenderer { } [RenderWith (typeof (PageRenderer))] internal class _PageRenderer { } #if !__IOS__ && !TIZEN4_0 [RenderWith (typeof (MasterDetailRenderer))] #elif TIZEN4_0 [RenderWith (typeof(MasterDetailPageRenderer))] #else [RenderWith (typeof (PhoneMasterDetailRenderer))] #endif internal class _MasterDetailPageRenderer { } [RenderWith (typeof(MediaElementRenderer))] internal class _MediaElementRenderer { } [RenderWith(typeof(RefreshViewRenderer))] internal class _RefreshViewRenderer { } [RenderWith(typeof(SwipeViewRenderer))] internal class _SwipeViewRenderer { } }
25.454545
97
0.77458
[ "MIT" ]
Mikilll94/Xamarin.Forms
Stubs/Xamarin.Forms.Platform.cs
4,760
C#
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS Is" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace Ams.Utils.NPOI.HSSF.Record.Chart { using System; using System.Text; using Ams.Utils.NPOI.HSSF.Record; using Ams.Utils.NPOI.Util; /** * CHARTFRTINFO - Chart Future Record Type Info (0x0850)<br/> * * @author Patrick Cheng */ public class ChartFRTInfoRecord : StandardRecord { public static short sid = 0x850; private short rt; private short grbitFrt; private byte verOriginator; private byte verWriter; private CFRTID[] rgCFRTID; private class CFRTID { public static int ENCODED_SIZE = 4; private int rtFirst; private int rtLast; public CFRTID(RecordInputStream in1) { rtFirst = in1.ReadShort(); rtLast = in1.ReadShort(); } public void Serialize(ILittleEndianOutput out1) { out1.WriteShort(rtFirst); out1.WriteShort(rtLast); } } public ChartFRTInfoRecord(RecordInputStream in1) { rt = in1.ReadShort(); grbitFrt = in1.ReadShort(); verOriginator = (byte)in1.ReadByte(); verWriter = (byte)in1.ReadByte(); int cCFRTID = in1.ReadShort(); rgCFRTID = new CFRTID[cCFRTID]; for (int i = 0; i < cCFRTID; i++) { rgCFRTID[i] = new CFRTID(in1); } } protected override int DataSize { get { return 2 + 2 + 1 + 1 + 2 + rgCFRTID.Length * CFRTID.ENCODED_SIZE; } } public override short Sid { get { return sid; } } public override void Serialize(ILittleEndianOutput out1) { out1.WriteShort(rt); out1.WriteShort(grbitFrt); out1.WriteByte(verOriginator); out1.WriteByte(verWriter); int nCFRTIDs = rgCFRTID.Length; out1.WriteShort(nCFRTIDs); for (int i = 0; i < nCFRTIDs; i++) { rgCFRTID[i].Serialize(out1); } } public override String ToString() { StringBuilder buffer = new StringBuilder(); buffer.Append("[CHARTFRTINFO]\n"); buffer.Append(" .rt =").Append(HexDump.ShortToHex(rt)).Append('\n'); buffer.Append(" .grbitFrt =").Append(HexDump.ShortToHex(grbitFrt)).Append('\n'); buffer.Append(" .verOriginator=").Append(HexDump.ByteToHex(verOriginator)).Append('\n'); buffer.Append(" .verWriter =").Append(HexDump.ByteToHex(verOriginator)).Append('\n'); buffer.Append(" .nCFRTIDs =").Append(HexDump.ShortToHex(rgCFRTID.Length)).Append('\n'); buffer.Append("[/CHARTFRTINFO]\n"); return buffer.ToString(); } } }
31.688
106
0.543802
[ "MIT" ]
SkyGrass/hippos_api_vm
Ams.Utils/Document/Excel/NPOI/HSSF/Record/Chart/ChartFRTInfoRecord.cs
3,961
C#
using System.Collections.Generic; using System.Management; namespace WindowsMonitor.Hardware.OnBoard { /// <summary> /// </summary> public sealed class SystemInformation { public bool Active { get; private set; } public string BaseBoardManufacturer { get; private set; } public string BaseBoardProduct { get; private set; } public string BaseBoardVersion { get; private set; } public byte BiosMajorRelease { get; private set; } public byte BiosMinorRelease { get; private set; } public string BiosReleaseDate { get; private set; } public string BiosVendor { get; private set; } public string BiosVersion { get; private set; } public byte EcFirmwareMajorRelease { get; private set; } public byte EcFirmwareMinorRelease { get; private set; } public string InstanceName { get; private set; } public string SystemFamily { get; private set; } public string SystemManufacturer { get; private set; } public string SystemProductName { get; private set; } public string SystemSku { get; private set; } public string SystemVersion { get; private set; } public static IEnumerable<SystemInformation> Retrieve(string remote, string username, string password) { var options = new ConnectionOptions { Impersonation = ImpersonationLevel.Impersonate, Username = username, Password = password }; var managementScope = new ManagementScope(new ManagementPath($"\\\\{remote}\\root\\wmi"), options); managementScope.Connect(); return Retrieve(managementScope); } public static IEnumerable<SystemInformation> Retrieve() { var managementScope = new ManagementScope(new ManagementPath("root\\wmi")); return Retrieve(managementScope); } public static IEnumerable<SystemInformation> Retrieve(ManagementScope managementScope) { var objectQuery = new ObjectQuery("SELECT * FROM MS_SystemInformation"); var objectSearcher = new ManagementObjectSearcher(managementScope, objectQuery); var objectCollection = objectSearcher.Get(); foreach (ManagementObject managementObject in objectCollection) yield return new SystemInformation { Active = (bool) (managementObject.Properties["Active"]?.Value ?? default(bool)), BaseBoardManufacturer = (string) (managementObject.Properties["BaseBoardManufacturer"]?.Value ?? default(string)), BaseBoardProduct = (string) (managementObject.Properties["BaseBoardProduct"]?.Value ?? default(string)), BaseBoardVersion = (string) (managementObject.Properties["BaseBoardVersion"]?.Value ?? default(string)), BiosMajorRelease = (byte) (managementObject.Properties["BiosMajorRelease"]?.Value ?? default(byte)), BiosMinorRelease = (byte) (managementObject.Properties["BiosMinorRelease"]?.Value ?? default(byte)), BiosReleaseDate = (string) (managementObject.Properties["BIOSReleaseDate"]?.Value ?? default(string)), BiosVendor = (string) (managementObject.Properties["BIOSVendor"]?.Value ?? default(string)), BiosVersion = (string) (managementObject.Properties["BIOSVersion"]?.Value ?? default(string)), EcFirmwareMajorRelease = (byte) (managementObject.Properties["ECFirmwareMajorRelease"]?.Value ?? default(byte)), EcFirmwareMinorRelease = (byte) (managementObject.Properties["ECFirmwareMinorRelease"]?.Value ?? default(byte)), InstanceName = (string) (managementObject.Properties["InstanceName"]?.Value ?? default(string)), SystemFamily = (string) (managementObject.Properties["SystemFamily"]?.Value ?? default(string)), SystemManufacturer = (string) (managementObject.Properties["SystemManufacturer"]?.Value ?? default(string)), SystemProductName = (string) (managementObject.Properties["SystemProductName"]?.Value ?? default(string)), SystemSku = (string) (managementObject.Properties["SystemSKU"]?.Value ?? default(string)), SystemVersion = (string) (managementObject.Properties["SystemVersion"]?.Value ?? default(string)) }; } } }
53.512821
117
0.699569
[ "MIT" ]
Biztactix/WindowsMonitor
WindowsMonitor.Standard/Hardware/OnBoard/SystemInformation.cs
4,174
C#
using System.IO; using Microsoft.AspNetCore.Hosting; using Serilog; namespace DDDSouthWest.Website { public class Program { public static void Main(string[] args) { Log.Logger = new LoggerConfiguration() .Enrich.FromLogContext() .MinimumLevel.Debug() .WriteTo.File("/logs/log.txt", rollingInterval: RollingInterval.Hour, buffered: true) .WriteTo.Console() .CreateLogger(); var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseUrls("http://*:5002") .UseIISIntegration() .UseStartup<Startup>() .Build(); host.Run(); } } }
28.586207
101
0.518697
[ "MIT" ]
JoeStead/dddsouthwest-web
src/DDDSouthWest.Website/Program.cs
831
C#
using System; using SWSniff.SoulWorker.Packets; namespace SWSniff.SoulWorker { public class SnifferEventArgs : EventArgs { public int SocketId { get; } public SWPacket Packet { get; } public bool Outgoing { get; } public SnifferEventArgs(SWPacket packet, bool outgoing, int socketId) { SocketId = socketId; Packet = packet; Outgoing = outgoing; } } }
22.5
77
0.597778
[ "MIT" ]
HoLLy-HaCKeR/SWSniff
SWSniff.SoulWorker/SnifferEventArgs.cs
452
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Nexmo.Api.Test.Integration { [TestClass] public class SmsTest { [TestMethod] public void should_send_sms() { var results = SMS.Send(new SMS.SMSRequest { from = Configuration.Instance.Settings["nexmo_number"], to = Configuration.Instance.Settings["test_number"], text = "this is a test" }); Assert.AreEqual(Configuration.Instance.Settings["test_number"], results.messages[0].to); Assert.AreEqual("0", results.messages[0].status); } } }
31.142857
100
0.587156
[ "MIT" ]
AnnaDodson/nexmo-dotnet
Nexmo.Api.Test.Integration/SmsTest.cs
656
C#
// Copyright (c) Duende Software. All rights reserved. // See LICENSE in the project root for license information. using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; namespace IdentityServer.API.UI { public class SecurityHeadersAttribute : ActionFilterAttribute { public override void OnResultExecuting(ResultExecutingContext context) { var result = context.Result; if (result is ViewResult) { // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options if (!context.HttpContext.Response.Headers.ContainsKey("X-Content-Type-Options")) { context.HttpContext.Response.Headers.Add("X-Content-Type-Options", "nosniff"); } // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options if (!context.HttpContext.Response.Headers.ContainsKey("X-Frame-Options")) { context.HttpContext.Response.Headers.Add("X-Frame-Options", "SAMEORIGIN"); } // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy var csp = "default-src 'self'; object-src 'none'; frame-ancestors 'none'; sandbox allow-forms allow-same-origin allow-scripts; base-uri 'self';"; // also consider adding upgrade-insecure-requests once you have HTTPS in place for production //csp += "upgrade-insecure-requests;"; // also an example if you need client images to be displayed from twitter // csp += "img-src 'self' https://pbs.twimg.com;"; // once for standards compliant browsers if (!context.HttpContext.Response.Headers.ContainsKey("Content-Security-Policy")) { context.HttpContext.Response.Headers.Add("Content-Security-Policy", csp); } // and once again for IE if (!context.HttpContext.Response.Headers.ContainsKey("X-Content-Security-Policy")) { context.HttpContext.Response.Headers.Add("X-Content-Security-Policy", csp); } // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy var referrer_policy = "no-referrer"; if (!context.HttpContext.Response.Headers.ContainsKey("Referrer-Policy")) { context.HttpContext.Response.Headers.Add("Referrer-Policy", referrer_policy); } } } } }
46.894737
161
0.594837
[ "MIT" ]
BuiTanLan/trouble-training
Src/IdentityServer/API/Controlers/SecurityHeadersAttribute.cs
2,673
C#
using Il2CppSystem.Collections.Generic; using DataHelper; namespace GunfireLib.Data { public static class RelicBoxGoodsData { public static Dictionary<int, boxgoodsdataclass> goodsList; public static System.Collections.Generic.Dictionary<int, Classes.BoxGoodsDataClass> parsedGoodsList = new System.Collections.Generic.Dictionary<int, Classes.BoxGoodsDataClass>(); internal static void Setup() { goodsList = relicboxgoodsdata.GetData(); foreach (KeyValuePair<int, boxgoodsdataclass> good in goodsList) { parsedGoodsList.Add(good.Key, new Classes.BoxGoodsDataClass(good.Key, goodsList)); } } } }
33
109
0.672176
[ "MIT" ]
ardittristan/GunfireMod
GunfireLib/Data/RelicBoxGoodsData.cs
728
C#
namespace CardGameBundle { class Card { // I guess I know why these are here private string face; private string suit; // Constructor public Card(string cardFace, string cardSuit) { face = cardFace; suit = cardSuit; } // Every class will have an existing .NET framework ToString() function which we will override public override string ToString() { return face + " of " + suit; } /* Default implementation of ToString() gives back a text representation which is generally * not a useful text representation * * Almost every class should define a ToString() method so that you can produce, * for the caller, a useful string of information * * Even if that string is just a string representation of all of the data inside of an object * that might be used for error message logging purposes * * It's considered a good practice to provide such a method to help users of your class */ } }
32.277778
103
0.579174
[ "MIT" ]
Kirbachu88/Card-Game-Bundle
CardGameBundle/Card.cs
1,164
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20200802 { using Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.PowerShell; /// <summary> /// A PowerShell PSTypeConverter to support converting to an instance of <see cref="UpdateResource" /> /// </summary> public partial class UpdateResourceTypeConverter : global::System.Management.Automation.PSTypeConverter { /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c>. /// </returns> public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="UpdateResource" /// /> type.</param> /// <returns> /// <c>true</c> if the instance could be converted to a <see cref="UpdateResource" /> type, otherwise <c>false</c> /// </returns> public static bool CanConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return true; } global::System.Type type = sourceValue.GetType(); if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { // we say yest to PSObjects return true; } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { // we say yest to Hashtables/dictionaries return true; } try { if (null != sourceValue.ToJsonString()) { return true; } } catch { // Not one of our objects } try { string text = sourceValue.ToString()?.Trim(); return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Json.JsonType.Object; } catch { // Doesn't look like it can be treated as JSON } return false; } /// <summary> /// Determines if the <see cref="sourceValue" /> parameter can be converted to the <see cref="destinationType" /> parameter /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c> /// </returns> public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; /// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns> /// an instance of <see cref="UpdateResource" />, or <c>null</c> if there is no suitable conversion. /// </returns> public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); /// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the value to convert into an instance of <see cref="UpdateResource" />.</param> /// <returns> /// an instance of <see cref="UpdateResource" />, or <c>null</c> if there is no suitable conversion. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20200802.IUpdateResource ConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return null; } global::System.Type type = sourceValue.GetType(); if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20200802.IUpdateResource).IsAssignableFrom(type)) { return sourceValue; } try { return UpdateResource.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; } catch { // Unable to use JSON pattern } if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { return UpdateResource.DeserializeFromPSObject(sourceValue); } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { return UpdateResource.DeserializeFromDictionary(sourceValue); } return null; } /// <summary>NotImplemented -- this will return <c>null</c></summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns>will always return <c>null</c>.</returns> public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; } }
51.535211
263
0.583356
[ "MIT" ]
3quanfeng/azure-powershell
src/ConnectedMachine/generated/api/Models/Api20200802/UpdateResource.TypeConverter.cs
7,177
C#
using Npgsql; using System; using System.Collections.Generic; using System.Data; using Framework.WebAPI.Interfaces; using static Framework.WebAPI.DB.DatabaseFactory; namespace Framework.WebAPI.DB { /// <summary> /// PostgreSQLラッパークラス /// </summary> public class PostgreSQLDB : IDatabase { /// <summary> /// セーブポイント名 /// </summary> private const string SavePointName = "SAVE"; #region プライベートフィールド /// <summary> /// コネクションインスタンス /// </summary> private NpgsqlConnection conn = null; /// <summary> /// トランザクションインスタンス /// </summary> private NpgsqlTransaction tran = null; /// <summary> /// パラメータ /// </summary> private readonly Dictionary<string, object> param; /// <summary> /// トランザクションが開いているか否か /// </summary> private bool isTran = false; /// <summary> /// セーブポイントを設定しているか否か /// </summary> private bool isSetSavePoint = false; #endregion #region プロパティ /// <summary> /// DB種類 /// </summary> public DatabaseTypes DBType { get { return DatabaseTypes.postgres; } } #endregion #region パブリックメソッド /// <summary> /// コンストラクタ /// </summary> /// <param name="connectionString">接続文字列</param> public PostgreSQLDB(string connectionString) { try { this.conn = this.GetConnection(connectionString); this.conn.Open(); this.param = new Dictionary<string, object>(); } catch (PostgresException ex) { throw ex; } catch (Exception ex) { throw new Exception($"「{connectionString}」への接続失敗", ex); } } /// <summary> /// SELECTした行の一部だけを取り出すSQLの文字列を返す /// </summary> /// <param name="limit">取り出す行数</param> /// <param name="offset">スキップ行</param> /// <returns></returns> public string GetLimitSQL(long limit, long offset) { return $" LIMIT {limit} OFFSET {offset} "; } /// <summary> /// パラメータを追加 /// </summary> /// <param name="key">キー</param> /// <param name="value">値</param> public void AddParam(string key, object value) { this.param.Add(key, value); } /// <summary> /// パラメータをクリア /// </summary> public void ClearParam() { this.param.Clear(); } /// <summary> /// SQL実行(登録・更新・削除) /// </summary> /// <param name="sql">SQLステートメント</param> /// <returns>処理件数</returns> public int ExecuteNonQuery(string sql) { // SQL未設定 if (sql == string.Empty) { return 0; } // SQL発行 using (NpgsqlCommand command = conn.CreateCommand()) { command.CommandText = sql; foreach (var key in this.param.Keys) { command.Parameters.AddWithValue(key, this.param[key]); } return command.ExecuteNonQuery(); } } /// <summary> /// 検索SQL実行 /// </summary> /// <param name="sql">SQLステートメント</param> /// <returns>検索結果</returns> public DataTable Fill(string sql) { // SQL未設定 if (sql == string.Empty) { return new DataTable(); } // SQL発行 using (NpgsqlCommand command = conn.CreateCommand()) { command.CommandText = sql; foreach (var key in this.param.Keys) { command.Parameters.AddWithValue(key, this.param[key]); } using (NpgsqlDataReader reader = command.ExecuteReader()) { //スキーマ取得 var result = this.GetShcema(reader); while (reader.Read()) { var addRow = result.NewRow(); foreach (DataColumn col in result.Columns) { addRow[col.ColumnName] = reader[col.ColumnName]; } result.Rows.Add(addRow); } return result; } } } /// <summary> /// トランザクション設定 /// </summary> public void BeginTransaction() { if (isTran && isSetSavePoint) { throw new Exception("トランザクションが設定できませんでした。"); } if (isTran) { tran.Save(SavePointName); isSetSavePoint= true; } else { this.tran = this.conn.BeginTransaction(); this.isTran = true; } } /// <summary> /// コミット /// </summary> public void Commit() { if (!this.isTran) { return; } if (isSetSavePoint) { tran.Release(SavePointName); isSetSavePoint = false; } else { this.tran.Commit(); this.isTran = false; } } /// <summary> /// ロールバック /// </summary> public void Rollback() { if (!this.isTran) { return; } if (isSetSavePoint) { tran.Rollback(SavePointName); isSetSavePoint = false; } else { this.tran.Rollback(); this.isTran = false; } } /// <summary> /// 解放処理 /// </summary> public void Dispose() { if (isSetSavePoint) { tran.Rollback(SavePointName); isSetSavePoint = false; } if (this.isTran) { this.tran.Rollback(); } if (this.tran != null) { this.tran.Dispose(); } this.conn.Close(); this.conn.Dispose(); } #endregion #region プライベートメソッド /// <summary> /// コネクション生成 /// </summary> /// <param name="connectionString">接続文字列</param> /// <returns>コネクションインスタンス</returns> private NpgsqlConnection GetConnection(string connectionString) { return new NpgsqlConnection(connectionString); } /// <summary> /// スキーマ取得 /// </summary> /// <param name="reader"></param> /// <returns></returns> private DataTable GetShcema(NpgsqlDataReader reader) { var result = new DataTable(); for (var i = 0; i < reader.FieldCount; i++) { var dataType = reader.GetFieldType(i); result.Columns.Add(new DataColumn(reader.GetName(i).ToUpper(), dataType)); } return result; } #endregion } }
19.926045
82
0.528804
[ "MIT" ]
kazenetu/TinyServerClientFramework
Source/WebAPI/DB/PostgeSQLDB.cs
6,831
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AWSSDK.LakeFormation")] [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS Lake Formation. Lake Formation: (New Service) AWS Lake Formation is a fully managed service that makes it easier for customers to build, secure and manage data lakes. AWS Lake Formation simplifies and automates many of the complex manual steps usually required to create data lakes including collecting, cleaning and cataloging data and securely making that data available for analytics and machine learning.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 2009-2020 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.100.127")]
55.40625
493
0.763677
[ "Apache-2.0" ]
Melvinerall/aws-sdk-net
sdk/code-analysis/ServiceAnalysis/LakeFormation/Properties/AssemblyInfo.cs
1,773
C#
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // ------------------------------------------------------------ namespace Microsoft.Azure.Cosmos { using System; using Microsoft.Azure.Documents; using Newtonsoft.Json; /// <summary> /// Represents a throughput of the resources in the Azure Cosmos DB service. /// It is the standard pricing for the resource in the Azure Cosmos DB service. /// </summary> /// <remarks> /// It contains provisioned container throughput in measurement of request units per second in the Azure Cosmos service. /// Refer to http://azure.microsoft.com/documentation/articles/documentdb-performance-levels/ for details on provision offer throughput. /// </remarks> /// <example> /// The example below fetch the ThroughputProperties on testContainer. /// <code language="c#"> /// <![CDATA[ /// ThroughputProperties throughputProperties = await testContainer.ReadThroughputAsync().Resource; /// ]]> /// </code> /// </example> public class ThroughputProperties { /// <summary> /// Default constructor for serialization /// </summary> [JsonConstructor] private ThroughputProperties() { } /// <summary> /// Create a instance for fixed throughput /// </summary> private ThroughputProperties(OfferContentProperties offerContentProperties) { this.OfferVersion = Constants.Offers.OfferVersion_V2; this.Content = offerContentProperties; } /// <summary> /// Gets the entity tag associated with the resource from the Azure Cosmos DB service. /// </summary> /// <value> /// The entity tag associated with the resource. /// </value> /// <remarks> /// ETags are used for concurrency checking when updating resources. /// </remarks> [JsonProperty(PropertyName = Constants.Properties.ETag, NullValueHandling = NullValueHandling.Ignore)] public string ETag { get; private set; } /// <summary> /// Gets the last modified time stamp associated with <see cref="DatabaseProperties" /> from the Azure Cosmos DB service. /// </summary> /// <value>The last modified time stamp associated with the resource.</value> [JsonConverter(typeof(UnixDateTimeConverter))] [JsonProperty(PropertyName = Constants.Properties.LastModified, NullValueHandling = NullValueHandling.Ignore)] public DateTime? LastModified { get; private set; } /// <summary> /// Gets the provisioned throughput for a resource in measurement of request units per second in the Azure Cosmos service. /// </summary> [JsonIgnore] public int? Throughput { get => this.Content?.OfferThroughput; private set => this.Content = OfferContentProperties.CreateManualOfferConent(value.Value); } /// <summary> /// The maximum throughput the autoscale will scale to. /// </summary> [JsonIgnore] public int? AutoscaleMaxThroughput => this.Content?.OfferAutoscaleSettings?.MaxThroughput; /// <summary> /// The amount to increment if the maximum RUs is getting throttled. /// </summary> [JsonIgnore] internal int? AutoUpgradeMaxThroughputIncrementPercentage => this.Content?.OfferAutoscaleSettings?.AutoscaleAutoUpgradeProperties?.ThroughputProperties?.IncrementPercent; /// <summary> /// The Throughput properties for manual provisioned throughput offering /// </summary> /// <param name="throughput">The current provisioned throughput for the resource.</param> /// <returns>Returns a ThroughputProperties for manual throughput</returns> public static ThroughputProperties CreateManualThroughput(int throughput) { if (throughput <= 0) { throw new ArgumentOutOfRangeException($"{nameof(throughput)} must be greater than 0"); } return new ThroughputProperties(OfferContentProperties.CreateManualOfferConent(throughput)); } /// <summary> /// The Throughput properties for autoscale provisioned throughput offering /// </summary> /// <param name="autoscaleMaxThroughput">The maximum throughput the resource can scale to.</param> /// <returns>Returns a ThroughputProperties for autoscale provisioned throughput</returns> public static ThroughputProperties CreateAutoscaleThroughput( int autoscaleMaxThroughput) { if (autoscaleMaxThroughput <= 0) { throw new ArgumentOutOfRangeException($"{nameof(autoscaleMaxThroughput)} must be greater than 0"); } return new ThroughputProperties(OfferContentProperties.CreateAutoscaleOfferConent( startingMaxThroughput: autoscaleMaxThroughput, autoUpgradeMaxThroughputIncrementPercentage: null)); } internal static ThroughputProperties CreateManualThroughput(int? throughput) { if (!throughput.HasValue) { return null; } return CreateManualThroughput(throughput.Value); } internal static ThroughputProperties CreateAutoscaleThroughput( int maxAutoscaleThroughput, int? autoUpgradeMaxThroughputIncrementPercentage = null) { return new ThroughputProperties(OfferContentProperties.CreateAutoscaleOfferConent( maxAutoscaleThroughput, autoUpgradeMaxThroughputIncrementPercentage)); } /// <summary> /// Gets the self-link associated with the resource from the Azure Cosmos DB service. /// </summary> /// <value>The self-link associated with the resource.</value> /// <remarks> /// A self-link is a static addressable Uri for each resource within a database account and follows the Azure Cosmos DB resource model. /// E.g. a self-link for a document could be dbs/db_resourceid/colls/coll_resourceid/documents/doc_resourceid /// </remarks> [JsonProperty(PropertyName = Constants.Properties.SelfLink, NullValueHandling = NullValueHandling.Ignore)] public string SelfLink { get; private set; } /// <summary> /// Gets the offer rid. /// </summary> [JsonProperty(PropertyName = Constants.Properties.RId, NullValueHandling = NullValueHandling.Ignore)] internal string OfferRID { get; private set; } /// <summary> /// Gets the resource rid. /// </summary> [JsonProperty(PropertyName = Constants.Properties.OfferResourceId, NullValueHandling = NullValueHandling.Ignore)] internal string ResourceRID { get; private set; } [JsonProperty(PropertyName = "content", DefaultValueHandling = DefaultValueHandling.Ignore)] internal OfferContentProperties Content { get; set; } /// <summary> /// Gets the version of this offer resource in the Azure Cosmos DB service. /// </summary> [JsonProperty(PropertyName = Constants.Properties.OfferVersion, DefaultValueHandling = DefaultValueHandling.Ignore)] internal string OfferVersion { get; private set; } } }
43.491329
178
0.640617
[ "MIT" ]
Camios/azure-cosmos-dotnet-v3
Microsoft.Azure.Cosmos/src/Resource/Settings/ThroughputProperties.cs
7,526
C#
// <copyright file="IHardwareUserFactorProfile.Generated.cs" company="Okta, Inc"> // Copyright (c) 2014 - present Okta, Inc. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. // </copyright> // This file was automatically generated. Don't modify it directly. using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Okta.Sdk { /// <summary>Represents a HardwareUserFactorProfile resource in the Okta API.</summary> public partial interface IHardwareUserFactorProfile : IResource { string CredentialId { get; set; } } }
31.181818
112
0.746356
[ "Apache-2.0" ]
Christian-Oleson/okta-sdk-dotnet
src/Okta.Sdk/Generated/IHardwareUserFactorProfile.Generated.cs
686
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using HardwareKeyboard.Models; namespace HardwareKeyboard.Services { public class MockDataStore : IDataStore<Item> { private List<Item> _items; public MockDataStore() { _items = new List<Item>(); } public async Task<bool> AddItemAsync(Item item) { _items.Insert(0, item); return await Task.FromResult(true); } public async Task<bool> ClearItemsAsync() { _items.Clear(); return await Task.FromResult(true); } public async Task<IEnumerable<Item>> GetItemsAsync(bool forceRefresh = false) { return await Task.FromResult(_items); } } }
23.617647
85
0.590286
[ "MIT" ]
Wasp3r/xamarin-samples
samples/hardware-keyboard/HardwareKeyboard/HardwareKeyboard/Services/MockDataStore.cs
805
C#
// Window responsible with simulating MST algorithms using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Windows.Forms; namespace Soft_educational_APM { public partial class FormAlgo : Form { public FormAlgo() { InitializeComponent(); } //Various variables int step = -1; //the current line of code in focus string[] lines; //the lines of code TextBox[] lineCode = new TextBox[100]; //the textboxes containing the lines of code int nrLines = 0; //the number of the lines //For Kruskal's algorithm public static Dictionary<RoundButton, int> M = new Dictionary<RoundButton, int>(); //the disjoint sets of the nodes public static List<Form1.edge> inMST = new List<Form1.edge> { }; //list of all the nodes in MST int currEdge = -1; Random rand = new Random(); //random for colors //For Prim's algorithm int startNode = 1; int addedNodes = 0; //nr of nodes addded in MST bool[] viz = new bool[200]; //true if node[i] is added in MST Form1.edge mch = new Form1.edge(); //auxiliary edge int NVmin, Vmin; private void FormAlgo_FormClosing(object sender, FormClosingEventArgs e) { //if user tries to close the form, just hide it e.Cancel = true; this.Hide(); } private void FormAlgo_VisibleChanged(object sender, EventArgs e) { comboBox1.SelectedIndex = 0; comboBox2.SelectedIndex = 0; restart_Click(this, e); DisplayCode(comboBox1.SelectedItem.ToString(), comboBox2.SelectedItem.ToString()); comboBox1.SelectedValueChanged += new EventHandler(comboBox1_SelectedValueChanged); comboBox2.SelectedValueChanged += new EventHandler(comboBox2_SelectedValueChanged); } private void FormAlgo_Activated(object sender, EventArgs e) { if (Form1.nrNodes == 0) //check whether the graph is empty { MessageBox.Show("Asigurați-vă că aveți noduri în graf.", "Eroare", MessageBoxButtons.OK, MessageBoxIcon.Error); Hide(); } else if (Form1.graphIsConnected() == false) //check whether the graph is connected { MessageBox.Show("Asigurați-vă că aveți o singură componentă conexă în graf.", "Eroare", MessageBoxButtons.OK, MessageBoxIcon.Error); Hide(); } else { //disable drawing Form1.canDraw = false; Form1.redrawEdges(Color.DarkGray); //disable modifying of the edges Form1.frmEdges.tableLayoutPanel1.Enabled = false; //and restart any previous algorithm restart_Click(this, e); } } private void DisplayCode(string algo, string lang) { //dump the previous code for (int i = 1; i <= nrLines; ++i) lineCode[i].Dispose(); nrLines = 0; //get the new code string code = "code where ???"; if (algo == "Kruskal") { label1.Visible = false; textBox2.Visible = false; if (lang == "Pseudocod") code = Properties.Resources.kruskalPseudo; else if (lang == "C / C++") ; } else if (algo == "Prim") { label1.Visible = true; textBox2.Visible = true; if (lang == "Pseudocod") code = Properties.Resources.primPseudo; else if (lang == "C / C++") ; } lines = code.Split('\n'); foreach (string line in lines) { ++nrLines; lineCode[nrLines] = new TextBox { Text = line, Margin = new Padding(1, 1, 1, 1), Anchor = (AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right), ReadOnly = true, Width = this.Width - 20 }; flowLayoutPanel1.Controls.Add(lineCode[nrLines]); } } private void startStop_Click(object sender, EventArgs e) { string algo = comboBox1.SelectedItem.ToString(); string lang = comboBox2.SelectedItem.ToString(); if (algo == "Kruskal") { if (lang == "Pseudocod") { if (timerKruskalPseudo.Enabled == false) timerKruskalPseudo.Enabled = true; else timerKruskalPseudo.Enabled = false; } else if (lang == "C / C++") ; } else if (algo == "Prim") { if (lang == "Pseudocod") { if (timerPrimPseudo.Enabled == false) timerPrimPseudo.Enabled = true; else timerPrimPseudo.Enabled = false; } else if (lang == "C / C++") ; } } private void stepByStep_Click(object sender, EventArgs e) { //run only one step of the selected algorithm string algo = comboBox1.SelectedItem.ToString(); string lang = comboBox2.SelectedItem.ToString(); if (algo == "Kruskal") { if (lang == "Pseudocod") timerKruskalPseudo_Tick(this, e); else if (lang == "C / C++") ; } else if (algo == "Prim") { if (lang == "Pseudocod") timerPrimPseudo_Tick(this, e); else if (lang == "C / C++") ; } } internal void restart_Click(object sender, EventArgs e) { //stop timer if (timerKruskalPseudo.Enabled == true) timerKruskalPseudo.Enabled = false; //remove highlight if exists foreach (TextBox line in flowLayoutPanel1.Controls) if (line.BackColor == Color.Orange) line.BackColor = this.BackColor; //initialise data structures in preparation for the algorithm step = -1; currEdge = -1; M.Clear(); inMST.Clear(); addedNodes = 0; for (int i = 1; i <= Form1.nrNodes; i++) viz[i] = false; //re-enable playback buttons startStop.Enabled = true; stepByStep.Enabled = true; //revert edges to black Form1.redrawEdges(Color.DarkGray); //and nodes to their initial color for (int i = 1; i <= Form1.nrNodes; i++) Form1.nodes[i].BackColor = Color.Aqua; } private void timerKruskalPseudo_Tick(object sender, EventArgs e) { step++; //increase the step if (step <= nrLines) //if code has not finished, proceed and run the algorithm { if (step >= 1) //remove highlight from current line of code lineCode[step].BackColor = this.BackColor; //and execute the current line of code if (step == 1) { //sort the edges in increasing order of weights for (int i = 0; i < Form1.edges.Count() - 1; i++) { for (int j = i + 1; j < Form1.edges.Count(); j++) if (Form1.edges[i].weight > Form1.edges[j].weight) { Form1.edge aux = new Form1.edge(Form1.edges[i].firstNode, Form1.edges[i].secondNode, Form1.edges[i].weight); Form1.edges[i] = Form1.edges[j]; Form1.edges[j] = aux; } } //and update Form Edges Form1.frmEdges.FormEdges_VisibleChanged(this, e); } else if (step == 2) { //put every node in a separate disjoint set for (int i = 1; i <= Form1.nrNodes; i++) { M[Form1.nodes[i]] = i; //give each node a random color Color randomColor = Color.FromArgb(50+rand.Next(206), 50+rand.Next(206), 50+rand.Next(206)); Form1.nodes[i].BackColor = randomColor; } } else if (step == 3) { //if we already have enough edges in MST (nr_nodes - 1), we STOP if (inMST.Count() == Form1.nrNodes - 1) step = 8; //else, we proceed with the repetitive structure } else if (step == 4) { //extract the edge with the next minimum weight (next edge in the sorted list) currEdge++; Form1.DrawEdge(Form1.edges[currEdge], Color.Yellow); } else if (step == 5) { //if the extremitites of the extracted edge are in the same set, ignore this edge if (M[Form1.edges[currEdge].firstNode] == M[Form1.edges[currEdge].secondNode]) { Form1.DrawEdge(Form1.edges[currEdge], Color.Black); step = 7; } //else, we proceed with the union of the two sets } else if (step == 6) { //add the extracted edge in the MST Form1.DrawEdge(Form1.edges[currEdge], Color.Red); inMST.Add(Form1.edges[currEdge]); } else if (step == 7) { //set A (of one extremity) and set B (of the other extremity), with A < B int A, B; Color myColor = new Color(); //color to change the nodes of one set to if (M[Form1.edges[currEdge].firstNode] < M[Form1.edges[currEdge].secondNode]) { A = M[Form1.edges[currEdge].firstNode]; B = M[Form1.edges[currEdge].secondNode]; myColor = Form1.edges[currEdge].firstNode.BackColor; } else { A = M[Form1.edges[currEdge].secondNode]; B = M[Form1.edges[currEdge].firstNode]; myColor = Form1.edges[currEdge].secondNode.BackColor; } //union the two disjoint sets (all nodes in B get into A) for (int i = 1; i <= Form1.nrNodes; i++) { if (M[Form1.nodes[i]] == B) { M[Form1.nodes[i]] = A; Form1.nodes[i].BackColor = myColor; } } } else if (step == 8) { //jump back to the start of the repetitive loop step = 2; } if (step < nrLines) //highlight next line of code, if exists lineCode[step + 1].BackColor = Color.Orange; } else if (step > nrLines) //else, if the code has finished, stop the timer and reset the algorithm { timerKruskalPseudo.Enabled = false; //disable playback buttons startStop.Enabled = false; stepByStep.Enabled = false; } } private void timerPrimPseudo_Tick(object sender, EventArgs e) { step++; //increase the step if (step <= nrLines) //if code has not finished, proceed and run the algorithm { if (step >= 1) //remove highlight from current line of code lineCode[step].BackColor = this.BackColor; //and execute the current line of code if (step == 1) { //extract the start node startNode = Int32.Parse(textBox2.Text); Vmin = startNode; //mark the start node as visited viz[startNode] = true; addedNodes++; //highlight the node Form1.nodes[startNode].BackColor = Color.Orange; } else if (step == 2) { //if we visited all nodes, STOP the algorithm if (addedNodes == Form1.nrNodes) step = 6; //else, proceed with the repetitive loop } else if (step == 3) { //we consider the unvisited node (NVmin) situated at the minimum distance from an already visited node (Vmin) int min = int.MaxValue; for(int i=0; i<Form1.edges.Count(); i++) { int n1 = Int32.Parse(Form1.edges[i].firstNode.Text); int n2 = Int32.Parse(Form1.edges[i].secondNode.Text); if (viz[n1] == true && viz[n2] == false) { if (Form1.edges[i].weight < min) { min = Form1.edges[i].weight; mch = Form1.edges[i]; NVmin = n2; } } else if (viz[n1] == false && viz[n2] == true) { if(Form1.edges[i].weight < min) { min = Form1.edges[i].weight; mch = Form1.edges[i]; NVmin = n1; } } } //highlight edge and NVmin Form1.DrawEdge(mch, Color.Yellow); Form1.nodes[NVmin].BackColor = Color.Yellow; } else if (step == 4) { //edge NVmin-Vmin gets added to the tree Form1.DrawEdge(mch, Color.Red); } else if (step == 5) { //NVmin is marked as visited addedNodes++; viz[NVmin] = true; Form1.nodes[NVmin].BackColor = Color.Orange; //jump back to the start of the repetitive structure step = 1; } if (step < nrLines) //highlight next line of code, if exists lineCode[step + 1].BackColor = Color.Orange; } else if (step > nrLines) //else, if the code has finished, stop the timer { timerPrimPseudo.Enabled = false; startStop.Enabled = false; stepByStep.Enabled = false; } } private void comboBox1_SelectedValueChanged(object sender, EventArgs e) { var obj = sender as ComboBox; DisplayCode(obj.SelectedItem.ToString(), comboBox2.SelectedItem.ToString()); restart_Click(this, e); } private void comboBox2_SelectedValueChanged(object sender, EventArgs e) { var obj = sender as ComboBox; DisplayCode(comboBox1.SelectedItem.ToString(), obj.SelectedItem.ToString()); restart_Click(this, e); } private void trackBar1_Scroll(object sender, EventArgs e) { timerKruskalPseudo.Interval = 550 - trackBar1.Value * 100; timerPrimPseudo.Interval = 550 - trackBar1.Value * 100; } private void textBox2_TextChanged(object sender, EventArgs e) { var obj = sender as TextBox; if (obj.Text == null || obj.Text == "0") obj.Text = "1"; Int32 st = FormEdges.convertToNumber(obj.Text); if (st > Form1.nrNodes) st = Form1.nrNodes; obj.Text = st.ToString(); } } }
37.453089
210
0.47443
[ "MIT" ]
rares-foica/mst-educational-software
Soft_educational_APM/FormAlgo.cs
16,382
C#
using System.Collections.Generic; using Microsoft.AspNet.Identity; namespace RedisCacheExample.ViewModels.Manage { public class IndexViewModel { public bool HasPassword { get; set; } public IList<UserLoginInfo> Logins { get; set; } public string PhoneNumber { get; set; } public bool TwoFactor { get; set; } public bool BrowserRemembered { get; set; } } }
21.789474
56
0.661836
[ "MIT" ]
marrrcin/aspnet-core-redis-html-cache
src/RedisCacheExample/ViewModels/Manage/IndexViewModel.cs
416
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Northwind.Demo.Views.Suppliers { /// <summary> /// Interaction logic for SuppliersSearch.xaml /// </summary> public partial class SuppliersSearch : UserControl { public SuppliersSearch() { InitializeComponent(); } } }
23.172414
54
0.72619
[ "MIT" ]
GenericCodes/WPFCRUDControl
Northwind.Demo/Views/Suppliers/SuppliersSearch.xaml.cs
674
C#
// This file is automatically generated - DO NOT EDIT MANUALLY! using System.Collections.Generic; using Unity.MARS.Query; namespace Unity.MARS.Data { public partial class MARSDatabase { bool FindRelationTraits(Relations relations, RelationTraitCache cache) { if (relations.GetTypeCount(out IRelation<System.Int32>[] intRelations) > 0) { if (!cache.TryGetType(out List<RelationTraitCache.ChildTraits<System.Int32>> intTraits)) return false; if (!FindTraitCollections(IntTraitProvider, intRelations, intTraits)) return false; } if (relations.GetTypeCount(out IRelation<UnityEngine.Pose>[] poseRelations) > 0) { if (!cache.TryGetType(out List<RelationTraitCache.ChildTraits<UnityEngine.Pose>> poseTraits)) return false; if (!FindTraitCollections(PoseTraitProvider, poseRelations, poseTraits)) return false; } if (relations.GetTypeCount(out IRelation<UnityEngine.Vector2>[] vector2Relations) > 0) { if (!cache.TryGetType(out List<RelationTraitCache.ChildTraits<UnityEngine.Vector2>> vector2Traits)) return false; if (!FindTraitCollections(Vector2TraitProvider, vector2Relations, vector2Traits)) return false; } return true; } bool DataStillMatches(Dictionary<IMRObject, int> dataAssignments, Relations relations, Dictionary<IMRObject, SetChildArgs> children, HashSet<IMRObject> nonRequiredChildrenLost) { if (relations.TryGetType(out IRelation<System.Int32>[] intRelations) && intRelations.Length > 0) { if (!CheckIfDataStillMatches(dataAssignments, intRelations, IntTraitProvider, children, nonRequiredChildrenLost)) return false; } if (relations.TryGetType(out IRelation<UnityEngine.Pose>[] poseRelations) && poseRelations.Length > 0) { if (!CheckIfDataStillMatches(dataAssignments, poseRelations, PoseTraitProvider, children, nonRequiredChildrenLost)) return false; } if (relations.TryGetType(out IRelation<UnityEngine.Vector2>[] vector2Relations) && vector2Relations.Length > 0) { if (!CheckIfDataStillMatches(dataAssignments, vector2Relations, Vector2TraitProvider, children, nonRequiredChildrenLost)) return false; } return true; } void FillRelationTraits(Dictionary<IMRObject, int> dataAssignments, Relations relations, Dictionary<IMRObject, QueryResult> childResults) { if (relations.TryGetType(out IRelation<System.Int32>[] intRelations) && intRelations.Length > 0) { foreach (var relation in intRelations) { var child1 = relation.child1; if (childResults.TryGetValue(child1, out var child1Result)) { var trait1Name = relation.child1TraitName; IntTraitProvider.TryGetTraitValue(dataAssignments[child1], trait1Name, out var value1); child1Result.SetTrait(trait1Name, value1); } var child2 = relation.child2; if (childResults.TryGetValue(child2, out var child2Result)) { var trait2Name = relation.child2TraitName; IntTraitProvider.TryGetTraitValue(dataAssignments[child2], trait2Name, out var value2); child2Result.SetTrait(trait2Name, value2); } } } if (relations.TryGetType(out IRelation<UnityEngine.Vector2>[] vector2Relations) && vector2Relations.Length > 0) { foreach (var relation in vector2Relations) { var child1 = relation.child1; if (childResults.TryGetValue(child1, out var child1Result)) { var trait1Name = relation.child1TraitName; Vector2TraitProvider.TryGetTraitValue(dataAssignments[child1], trait1Name, out var value1); child1Result.SetTrait(trait1Name, value1); } var child2 = relation.child2; if (childResults.TryGetValue(child2, out var child2Result)) { var trait2Name = relation.child2TraitName; Vector2TraitProvider.TryGetTraitValue(dataAssignments[child2], trait2Name, out var value2); child2Result.SetTrait(trait2Name, value2); } } } } } }
43.529915
123
0.568035
[ "Apache-2.0" ]
bsides44/MARSGeofencing
MARS geofencing/Assets/MARS/Generated/MARSDatabase.Relations.Generated.cs
5,093
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Microsoft.ML.Runtime; using Microsoft.ML.Runtime.CommandLine; using Microsoft.ML.Runtime.Data; using Microsoft.ML.Runtime.Data.Conversion; using Microsoft.ML.Runtime.EntryPoints; using Microsoft.ML.Runtime.Internal.Utilities; using Microsoft.ML.Runtime.Model; [assembly: LoadableClass(UngroupTransform.Summary, typeof(UngroupTransform), typeof(UngroupTransform.Arguments), typeof(SignatureDataTransform), UngroupTransform.UserName, UngroupTransform.ShortName)] [assembly: LoadableClass(UngroupTransform.Summary, typeof(UngroupTransform), null, typeof(SignatureLoadDataTransform), UngroupTransform.UserName, UngroupTransform.LoaderSignature)] namespace Microsoft.ML.Runtime.Data { /// <summary> /// This can be thought of as an inverse of <see cref="GroupTransform"/>. For all specified vector columns /// ("pivot" columns), performs the "ungroup" (or "unroll") operation as outlined below. /// /// If the only pivot column is called P, and has size K, then for every row of the input we will produce /// K rows, that are identical in all columns except P. The column P will become a scalar column, and this /// column will hold all the original values of input's P, one value per row, in order. The order of columns /// will remain the same. /// /// Variable-length pivot columns are supported (including zero, which will eliminate the row from the result). /// /// Multiple pivot columns are also supported: /// * A number of output rows is controlled by the 'mode' parameter. /// - outer: it is equal to the maximum length of pivot columns, /// - inner: it is equal to the minimum length of pivot columns, /// - first: it is equal to the length of the first pivot column. /// * If a particular pivot column has size that is different than the number of output rows, the extra slots will /// be ignored, and the missing slots will be 'padded' with default values. /// /// All metadata is preserved for the retained columns. For 'unrolled' columns, all known metadata /// except slot names is preserved. /// </summary> public sealed class UngroupTransform : TransformBase { public const string Summary = "Un-groups vector columns into sequences of rows, inverse of Group transform"; public const string LoaderSignature = "UngroupTransform"; public const string ShortName = "Ungroup"; public const string UserName = "Un-group Transform"; private static VersionInfo GetVersionInfo() { return new VersionInfo( modelSignature: "UNGRP XF", verWrittenCur: 0x00010001, // Initial verReadableCur: 0x00010001, verWeCanReadBack: 0x00010001, loaderSignature: LoaderSignature); } /// <summary> /// Controls the number of output rows produced by the <see cref="UngroupTransform"/> transform /// </summary> public enum UngroupMode { /// <summary> /// The number of output rows is equal to the minimum length of pivot columns /// </summary> Inner, /// <summary> /// The number of output rows is equal to the maximum length of pivot columns /// </summary> Outer, /// <summary> /// The number of output rows is equal to the length of the first pivot column. /// </summary> First } public sealed class Arguments : TransformInputBase { [Argument(ArgumentType.Multiple | ArgumentType.Required, HelpText = "Columns to unroll, or 'pivot'", ShortName = "col")] public string[] Column; [Argument(ArgumentType.AtMostOnce, HelpText = "Specifies how to unroll multiple pivot columns of different size.")] public UngroupMode Mode = UngroupMode.Inner; } private readonly SchemaImpl _schemaImpl; /// <summary> /// Convenience constructor for public facing API. /// </summary> /// <param name="env">Host Environment.</param> /// <param name="input">Input <see cref="IDataView"/>. This is the output from previous transform or loader.</param> /// <param name="mode">Specifies how to unroll multiple pivot columns of different size.</param> /// <param name="columns">Columns to unroll, or 'pivot'</param> public UngroupTransform(IHostEnvironment env, IDataView input, UngroupMode mode, params string[] columns) : this(env, new Arguments() { Column = columns, Mode = mode }, input) { } public UngroupTransform(IHostEnvironment env, Arguments args, IDataView input) : base(env, LoaderSignature, input) { Host.CheckValue(args, nameof(args)); Host.CheckUserArg(Utils.Size(args.Column) > 0, nameof(args.Column), "There must be at least one pivot column"); Host.CheckUserArg(args.Column.Distinct().Count() == args.Column.Length, nameof(args.Column), "Duplicate pivot columns are not allowed"); _schemaImpl = new SchemaImpl(Host, Source.Schema, args.Mode, args.Column); } public static UngroupTransform Create(IHostEnvironment env, ModelLoadContext ctx, IDataView input) { Contracts.CheckValue(env, nameof(env)); env.CheckValue(ctx, nameof(ctx)); ctx.CheckAtModel(GetVersionInfo()); env.CheckValue(input, nameof(input)); var h = env.Register(LoaderSignature); return h.Apply("Loading Model", ch => new UngroupTransform(h, ctx, input)); } private UngroupTransform(IHost host, ModelLoadContext ctx, IDataView input) : base(host, input) { Host.AssertValue(ctx); // *** Binary format *** // (schema) _schemaImpl = SchemaImpl.Create(ctx, host, input.Schema); } public override void Save(ModelSaveContext ctx) { Host.CheckValue(ctx, nameof(ctx)); ctx.CheckAtModel(); ctx.SetVersionInfo(GetVersionInfo()); // *** Binary format *** // (schema) _schemaImpl.Save(ctx); } public override long? GetRowCount(bool lazy = true) { // Row count is known if the input's row count is known, and pivot column sizes are fixed. var commonSize = _schemaImpl.GetCommonPivotColumnSize(); if (commonSize > 0) { long? srcRowCount = Source.GetRowCount(true); if (srcRowCount.HasValue && srcRowCount.Value <= (long.MaxValue / commonSize)) return srcRowCount.Value * commonSize; } return null; } public override ISchema Schema { get { return _schemaImpl; } } protected override bool? ShouldUseParallelCursors(Func<int, bool> predicate) { // This transform doesn't benefit from parallel cursors, but it can support them. return null; } // Technically, we could shuffle the ungrouped data if the source can shuffle. However, we want to maintain // contiguous groups. There's also a question whether we should shuffle inside groups or just shuffle groups // themselves. With these issues, and no anticipated use for shuffled version, it's safer to not shuffle at all. public override bool CanShuffle { get { return false; } } protected override IRowCursor GetRowCursorCore(Func<int, bool> predicate, IRandom rand = null) { var activeInput = _schemaImpl.GetActiveInput(predicate); var inputCursor = Source.GetRowCursor(col => activeInput[col], null); return new Cursor(Host, inputCursor, _schemaImpl, predicate); } public override IRowCursor[] GetRowCursorSet(out IRowCursorConsolidator consolidator, Func<int, bool> predicate, int n, IRandom rand = null) { var activeInput = _schemaImpl.GetActiveInput(predicate); var inputCursors = Source.GetRowCursorSet(out consolidator, col => activeInput[col], n, null); return Utils.BuildArray<IRowCursor>(inputCursors.Length, x => new Cursor(Host, inputCursors[x], _schemaImpl, predicate)); } private sealed class SchemaImpl : ISchema { private static bool ShouldPreserveMetadata(string kind) { switch (kind) { case MetadataUtils.Kinds.IsNormalized: case MetadataUtils.Kinds.KeyValues: case MetadataUtils.Kinds.ScoreColumnSetId: case MetadataUtils.Kinds.ScoreColumnKind: case MetadataUtils.Kinds.ScoreValueKind: case MetadataUtils.Kinds.HasMissingValues: case MetadataUtils.Kinds.IsUserVisible: return true; default: return false; } } public struct PivotColumnInfo { public readonly string Name; public readonly int Index; public readonly int Size; public readonly PrimitiveType ItemType; public PivotColumnInfo(string name, int index, int size, PrimitiveType itemType) { Contracts.AssertNonEmpty(name); Contracts.Assert(index >= 0); Contracts.Assert(size >= 0); Contracts.AssertValue(itemType); Name = name; Index = index; Size = size; ItemType = itemType; } } private readonly ISchema _inputSchema; private readonly IExceptionContext _ectx; public readonly UngroupMode Mode; private readonly PivotColumnInfo[] _infos; // The indices of pivot columns. private readonly Dictionary<string, int> _pivotColMap; // pivotIndex[col] = -1 for non-pivot columns, and the index of the corresponding info in _infos for pivot columns. private readonly int[] _pivotIndex; public SchemaImpl(IExceptionContext ectx, ISchema inputSchema, UngroupMode mode, string[] pivotColumns) { Contracts.AssertValueOrNull(ectx); _ectx = ectx; _ectx.AssertValue(inputSchema); _ectx.AssertNonEmpty(pivotColumns); _inputSchema = inputSchema; Mode = mode; CheckAndBind(_ectx, inputSchema, pivotColumns, out _infos); _pivotColMap = new Dictionary<string, int>(); _pivotIndex = Utils.CreateArray(_inputSchema.ColumnCount, -1); for (int i = 0; i < _infos.Length; i++) { var info = _infos[i]; _pivotColMap[info.Name] = info.Index; _ectx.Assert(_pivotIndex[info.Index] == -1); _pivotIndex[info.Index] = i; } } private static void CheckAndBind(IExceptionContext ectx, ISchema inputSchema, string[] pivotColumns, out PivotColumnInfo[] infos) { Contracts.AssertValueOrNull(ectx); ectx.AssertValue(inputSchema); ectx.AssertNonEmpty(pivotColumns); infos = new PivotColumnInfo[pivotColumns.Length]; for (int i = 0; i < pivotColumns.Length; i++) { var name = pivotColumns[i]; // REVIEW: replace Check with CheckUser, once existing CheckUser is renamed to CheckUserArg or something. ectx.CheckUserArg(!string.IsNullOrEmpty(name), nameof(Arguments.Column), "Column name cannot be empty"); int col; if (!inputSchema.TryGetColumnIndex(name, out col)) throw ectx.ExceptUserArg(nameof(Arguments.Column), "Pivot column '{0}' is not found", name); var colType = inputSchema.GetColumnType(col); if (!colType.IsVector || !colType.ItemType.IsPrimitive) throw ectx.ExceptUserArg(nameof(Arguments.Column), "Pivot column '{0}' has type '{1}', but must be a vector of primitive types", name, colType); infos[i] = new PivotColumnInfo(name, col, colType.VectorSize, colType.ItemType.AsPrimitive); } } public static SchemaImpl Create(ModelLoadContext ctx, IExceptionContext ectx, ISchema inputSchema) { Contracts.AssertValueOrNull(ectx); ectx.AssertValue(ctx); ectx.AssertValue(inputSchema); // *** Binary format *** // int: ungroup mode // int: K - number of pivot columns // int[K]: ids of pivot column names int modeIndex = ctx.Reader.ReadInt32(); ectx.CheckDecode(Enum.IsDefined(typeof(UngroupMode), modeIndex)); UngroupMode mode = (UngroupMode)modeIndex; int k = ctx.Reader.ReadInt32(); ectx.CheckDecode(k > 0); var pivotColumns = new string[k]; for (int i = 0; i < k; i++) pivotColumns[i] = ctx.LoadNonEmptyString(); return new SchemaImpl(ectx, inputSchema, mode, pivotColumns); } public void Save(ModelSaveContext ctx) { _ectx.AssertValue(ctx); // *** Binary format *** // int: ungroup mode // int: K - number of pivot columns // int[K]: ids of pivot column names ctx.Writer.Write((int)Mode); ctx.Writer.Write(_infos.Length); foreach (var ex in _infos) ctx.SaveNonEmptyString(ex.Name); } /// <summary> /// Return an array of active input columns given the target predicate. /// </summary> public bool[] GetActiveInput(Func<int, bool> predicate) { var activeInput = Utils.BuildArray(ColumnCount, predicate); for (int i = 0; i < _infos.Length; i++) { bool isNeededForSize = (_infos[i].Size == 0) && (i == 0 || Mode != UngroupMode.First); activeInput[_infos[i].Index] |= isNeededForSize; } return activeInput; } public int PivotColumnCount { get { return _infos.Length; } } public PivotColumnInfo GetPivotColumnInfo(int iinfo) { _ectx.Assert(0 <= iinfo && iinfo < _infos.Length); return _infos[iinfo]; } public PivotColumnInfo GetPivotColumnInfoByCol(int col) { _ectx.Assert(0 <= col && col < ColumnCount); _ectx.Assert(_pivotIndex[col] >= 0); return _infos[_pivotIndex[col]]; } public bool IsPivot(int col) { _ectx.Assert(0 <= col && col < ColumnCount); return _pivotIndex[col] >= 0; } public int GetCommonPivotColumnSize() { if (Mode == UngroupMode.First) return _infos[0].Size; var size = 0; foreach (var ex in _infos) { if (ex.Size == 0) return 0; if (size == 0) size = ex.Size; else if (size > ex.Size && Mode == UngroupMode.Inner) size = ex.Size; else if (size < ex.Size && Mode == UngroupMode.Outer) size = ex.Size; } return size; } public int ColumnCount { get { return _inputSchema.ColumnCount; } } public bool TryGetColumnIndex(string name, out int col) { return _inputSchema.TryGetColumnIndex(name, out col); } public string GetColumnName(int col) { return _inputSchema.GetColumnName(col); } public ColumnType GetColumnType(int col) { _ectx.Check(0 <= col && col < ColumnCount); if (!IsPivot(col)) return _inputSchema.GetColumnType(col); _ectx.Assert(0 <= _pivotIndex[col] && _pivotIndex[col] < _infos.Length); return _infos[_pivotIndex[col]].ItemType; } public IEnumerable<KeyValuePair<string, ColumnType>> GetMetadataTypes(int col) { _ectx.Check(0 <= col && col < ColumnCount); if (!IsPivot(col)) return _inputSchema.GetMetadataTypes(col); return _inputSchema.GetMetadataTypes(col).Where(pair => ShouldPreserveMetadata(pair.Key)); } public ColumnType GetMetadataTypeOrNull(string kind, int col) { _ectx.Check(0 <= col && col < ColumnCount); if (IsPivot(col) && !ShouldPreserveMetadata(kind)) return null; return _inputSchema.GetMetadataTypeOrNull(kind, col); } public void GetMetadata<TValue>(string kind, int col, ref TValue value) { _ectx.Check(0 <= col && col < ColumnCount); if (IsPivot(col) && !ShouldPreserveMetadata(kind)) throw _ectx.ExceptGetMetadata(); _inputSchema.GetMetadata(kind, col, ref value); } } private sealed class Cursor : LinkedRootCursorBase<IRowCursor>, IRowCursor { private readonly SchemaImpl _schema; // The size of the pivot column in the current row. If the cursor is in good state, this is positive. // It's calculated on every row, based on UngroupMode. private int _pivotColSize; // The current position within the pivot columns. If the cursor is in good state, this is in [0, _pivotColSize). private int _pivotColPosition; // Total count is ColumnCount. private readonly bool[] _active; // Getters for pivot columns. Cached on first creation. Parallel to columns, and always null for non-pivot columns. private readonly Delegate[] _cachedGetters; // Size (min, max or target) of fixed columns. Zero here means that there are no fixed-size columns. private readonly int _fixedSize; // For each pivot column that we care about, these getters return the vector size. private readonly Func<int>[] _sizeGetters; // As a side effect, getters also populate these actual sizes of the necessary pivot columns on MoveNext. // Parallel to columns. private int[] _colSizes; public Cursor(IChannelProvider provider, IRowCursor input, SchemaImpl schema, Func<int, bool> predicate) : base(provider, input) { _schema = schema; _active = Utils.BuildArray(_schema.ColumnCount, predicate); _cachedGetters = new Delegate[_schema.ColumnCount]; _colSizes = new int[_schema.ColumnCount]; int sizeColumnsLim = _schema.Mode == UngroupMode.First ? 1 : _schema.PivotColumnCount; _fixedSize = 0; var needed = new List<Func<int>>(); for (int i = 0; i < sizeColumnsLim; i++) { var info = _schema.GetPivotColumnInfo(i); if (info.Size > 0) { if (_fixedSize == 0) _fixedSize = info.Size; else if (_schema.Mode == UngroupMode.Inner && _fixedSize > info.Size) _fixedSize = info.Size; else if (_schema.Mode == UngroupMode.Outer && _fixedSize < info.Size) _fixedSize = info.Size; } else { // This will also create and cache a getter for the pivot column. // That's why MakeSizeGetter is an instance method. var rawItemType = info.ItemType.RawType; Func<int, Func<int>> del = MakeSizeGetter<int>; var mi = del.GetMethodInfo().GetGenericMethodDefinition().MakeGenericMethod(rawItemType); var sizeGetter = (Func<int>)mi.Invoke(this, new object[] { info.Index }); needed.Add(sizeGetter); } } _sizeGetters = needed.ToArray(); Ch.Assert(_fixedSize > 0 || _sizeGetters.Length > 0); } public override long Batch { get { return Input.Batch; } } public override ValueGetter<UInt128> GetIdGetter() { var idGetter = Input.GetIdGetter(); return (ref UInt128 val) => { idGetter(ref val); val = val.Combine(new UInt128((ulong)_pivotColPosition, 0)); }; } protected override bool MoveNextCore() { Ch.Assert(State == CursorState.NotStarted || (0 <= _pivotColPosition && _pivotColPosition < _pivotColSize)); // In the very first call to MoveNext, both _pivotColPosition and _pivotColSize are equal to zero. // So, the below code will work seamlessly, advancing the input cursor. _pivotColPosition++; while (_pivotColPosition >= _pivotColSize) { bool result = Input.MoveNext(); if (!result) return false; _pivotColPosition = 0; _pivotColSize = CalcPivotColSize(); // If the current input row's pivot column size is zero, the condition in while loop will be true again, // and we'll skip the row. } return true; } private int CalcPivotColSize() { var size = _fixedSize; foreach (var getter in _sizeGetters) { var colSize = getter(); if (_schema.Mode == UngroupMode.Inner && colSize == 0) return 0; if (size == 0) size = colSize; else if (_schema.Mode == UngroupMode.Inner && size > colSize) size = colSize; else if (_schema.Mode == UngroupMode.Outer && size < colSize) size = colSize; } return size; } private Func<int> MakeSizeGetter<T>(int col) { Contracts.Assert(0 <= col && col < _schema.ColumnCount); var srcGetter = GetGetter<T>(col); var cur = default(T); return () => { srcGetter(ref cur); // We don't care about cur, we only need _colSizes to be populated. return _colSizes[col]; }; } public ISchema Schema { get { return _schema; } } public bool IsColumnActive(int col) { Ch.Check(0 <= col && col < _schema.ColumnCount); return _active[col]; } public ValueGetter<TValue> GetGetter<TValue>(int col) { Ch.CheckParam(0 <= col && col < _schema.ColumnCount, nameof(col)); if (!_schema.IsPivot(col)) return Input.GetGetter<TValue>(col); if (_cachedGetters[col] == null) _cachedGetters[col] = MakeGetter<TValue>(col, _schema.GetPivotColumnInfoByCol(col).ItemType); var result = _cachedGetters[col] as ValueGetter<TValue>; Ch.Check(result != null, "Unexpected getter type requested"); return result; } private ValueGetter<T> MakeGetter<T>(int col, PrimitiveType itemType) { var srcGetter = Input.GetGetter<VBuffer<T>>(col); // The position of the source cursor. Used to extract the source row once. long cachedPosition = -1; // The position inside the sparse row. If the row is sparse, the invariant is // cachedIndex == row.Count || _pivotColPosition <= row.Indices[cachedIndex]. int cachedIndex = 0; VBuffer<T> row = default(VBuffer<T>); T naValue = Conversions.Instance.GetNAOrDefault<T>(itemType); return (ref T value) => { // This delegate can be called from within MoveNext, so our own IsGood is not yet set. Ch.Check(Input.State == CursorState.Good, "Cursor is not active"); Ch.Assert(cachedPosition <= Input.Position); if (cachedPosition < Input.Position) { srcGetter(ref row); // Side effect: populate the column size. _colSizes[col] = row.Length; cachedPosition = Input.Position; cachedIndex = 0; } if (_pivotColPosition >= row.Length) value = naValue; else if (row.IsDense) value = row.Values[_pivotColPosition]; else { // The row is sparse. while (cachedIndex < row.Count && _pivotColPosition > row.Indices[cachedIndex]) cachedIndex++; if (cachedIndex < row.Count && _pivotColPosition == row.Indices[cachedIndex]) value = row.Values[cachedIndex]; else value = default(T); } }; } } } public static partial class GroupingOperations { [TlcModule.EntryPoint(Name = "Transforms.Segregator", Desc = UngroupTransform.Summary, UserName = UngroupTransform.UserName, ShortName = UngroupTransform.ShortName)] public static CommonOutputs.TransformOutput Ungroup(IHostEnvironment env, UngroupTransform.Arguments input) { Contracts.CheckValue(env, nameof(env)); env.CheckValue(input, nameof(input)); var h = EntryPointUtils.CheckArgsAndCreateHost(env, "UngroupTransform", input); var view = new UngroupTransform(h, input, input.Data); return new CommonOutputs.TransformOutput() { Model = new TransformModel(h, view, input.Data), OutputData = view }; } } }
42.450893
173
0.541452
[ "MIT" ]
antarikshnarain/machinelearning
src/Microsoft.ML.Transforms/UngroupTransform.cs
28,527
C#
namespace sample.microservice.state.reservation; public class ReservationState { public Guid OrderId { get; set; } public List<ItemReservation>? ReservedItems { get; set; } }
20.555556
61
0.740541
[ "MIT" ]
PacktPublishing/Practical-Microservices-with-Dapr-and-.NET-Second-Edition
chapter07/sample.microservice.reservation/State/ReservationState.cs
185
C#
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion #if !(NET35 || NET20 || PORTABLE || DNXCORE50) using System; using System.Collections.Generic; using System.ComponentModel; using System.Dynamic; using System.IO; using System.Linq; using System.Runtime.Serialization; using System.Text; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; #if DNXCORE50 using Xunit; using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; #endif using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Tests.TestObjects; using Newtonsoft.Json.Utilities; using System.Globalization; using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; namespace Newtonsoft.Json.Tests.Documentation { [TestFixture] public class ReadingAndWritingJsonTests : TestFixtureBase { public void ReadingAndWritingJsonText() { #region ReadingAndWritingJsonText StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter writer = new JsonTextWriter(sw)) { writer.Formatting = Formatting.Indented; writer.WriteStartObject(); writer.WritePropertyName("CPU"); writer.WriteValue("Intel"); writer.WritePropertyName("PSU"); writer.WriteValue("500W"); writer.WritePropertyName("Drives"); writer.WriteStartArray(); writer.WriteValue("DVD read/writer"); writer.WriteComment("(broken)"); writer.WriteValue("500 gigabyte hard drive"); writer.WriteValue("200 gigabype hard drive"); writer.WriteEnd(); writer.WriteEndObject(); } // { // "CPU": "Intel", // "PSU": "500W", // "Drives": [ // "DVD read/writer" // /*(broken)*/, // "500 gigabyte hard drive", // "200 gigabype hard drive" // ] // } #endregion } [Test] public void ReadingJsonText() { #region ReadingJsonText string json = @"{ 'CPU': 'Intel', 'PSU': '500W', 'Drives': [ 'DVD read/writer' /*(broken)*/, '500 gigabyte hard drive', '200 gigabype hard drive' ] }"; JsonTextReader reader = new JsonTextReader(new StringReader(json)); while (reader.Read()) { if (reader.Value != null) { Console.WriteLine("Token: {0}, Value: {1}", reader.TokenType, reader.Value); } else { Console.WriteLine("Token: {0}", reader.TokenType); } } // Token: StartObject // Token: PropertyName, Value: CPU // Token: String, Value: Intel // Token: PropertyName, Value: PSU // Token: String, Value: 500W // Token: PropertyName, Value: Drives // Token: StartArray // Token: String, Value: DVD read/writer // Token: Comment, Value: (broken) // Token: String, Value: 500 gigabyte hard drive // Token: String, Value: 200 gigabype hard drive // Token: EndArray // Token: EndObject #endregion } public void ReadingAndWritingJsonLinq() { #region ReadingAndWritingJsonLinq JObject o = new JObject( new JProperty("Name", "John Smith"), new JProperty("BirthDate", new DateTime(1983, 3, 20)) ); JsonSerializer serializer = new JsonSerializer(); Person p = (Person)serializer.Deserialize(new JTokenReader(o), typeof(Person)); Console.WriteLine(p.Name); // John Smith #endregion } } } #endif
34.096774
96
0.578619
[ "MIT" ]
0xced/Newtonsoft.Json
Src/Newtonsoft.Json.Tests/Documentation/ReadingAndWritingJsonTests.cs
5,287
C#
using System; using System.Collections.Generic; namespace leetcodesln { public class FindAllDuplicatesInAnArray { public IList<int> FindDuplicates(int[] nums) { var ans = new List<int>(); for (int i = 0; i < nums.Length; ++i) { int index = Math.Abs(nums[i]) - 1; if (nums[index] < 0) ans.Add(index + 1); else nums[index] = -nums[index]; } return ans; } } }
22.909091
56
0.484127
[ "MIT" ]
matwming/TrialOfTheGrasses
CSharp/leetcodesln/FindAllDuplicatesInAnArray.cs
506
C#
// Copyright (c) MOSA Project. Licensed under the New BSD License. // This code was generated by an automated template. using Mosa.Compiler.Framework; namespace Mosa.Compiler.Framework.Transform.Auto.StrengthReduction { /// <summary> /// Compare64x64RemUnsigned /// </summary> public sealed class Compare64x64RemUnsigned : BaseTransformation { public Compare64x64RemUnsigned() : base(IRInstruction.Compare64x64) { } public override bool Match(Context context, TransformContext transformContext) { if (context.ConditionCode != ConditionCode.Equal) return false; if (!context.Operand1.IsVirtualRegister) return false; if (!context.Operand2.IsResolvedConstant) return false; if (context.Operand2.ConstantUnsigned64 != 0) return false; if (context.Operand1.Definitions.Count != 1) return false; if (context.Operand1.Definitions[0].Instruction != IRInstruction.RemUnsigned64) return false; if (!context.Operand1.Definitions[0].Operand2.IsResolvedConstant) return false; if (context.Operand1.Definitions[0].Operand2.ConstantUnsigned64 != 2) return false; return true; } public override void Transform(Context context, TransformContext transformContext) { var result = context.Result; var t1 = context.Operand1.Definitions[0].Operand1; var c1 = transformContext.CreateConstant(1); context.SetInstruction(IRInstruction.And64, result, t1, c1); } } /// <summary> /// Compare64x64RemUnsigned_v1 /// </summary> public sealed class Compare64x64RemUnsigned_v1 : BaseTransformation { public Compare64x64RemUnsigned_v1() : base(IRInstruction.Compare64x64) { } public override bool Match(Context context, TransformContext transformContext) { if (context.ConditionCode != ConditionCode.Equal) return false; if (!context.Operand1.IsResolvedConstant) return false; if (context.Operand1.ConstantUnsigned64 != 0) return false; if (!context.Operand2.IsVirtualRegister) return false; if (context.Operand2.Definitions.Count != 1) return false; if (context.Operand2.Definitions[0].Instruction != IRInstruction.RemUnsigned64) return false; if (!context.Operand2.Definitions[0].Operand2.IsResolvedConstant) return false; if (context.Operand2.Definitions[0].Operand2.ConstantUnsigned64 != 2) return false; return true; } public override void Transform(Context context, TransformContext transformContext) { var result = context.Result; var t1 = context.Operand2.Definitions[0].Operand1; var c1 = transformContext.CreateConstant(1); context.SetInstruction(IRInstruction.And64, result, t1, c1); } } }
24.669725
84
0.735589
[ "BSD-3-Clause" ]
AnErrupTion/MOSA-Project
Source/Mosa.Compiler.Framework/Transform/Auto/StrengthReduction/Compare64x64RemUnsigned.cs
2,689
C#
using System.Runtime.InteropServices; namespace Lunar.Native.Structures { [StructLayout(LayoutKind.Sequential)] internal readonly struct ListEntry32 { internal readonly int Flink; internal readonly int Blink; } [StructLayout(LayoutKind.Sequential)] internal readonly struct ListEntry64 { internal readonly long Flink; internal readonly long Blink; } }
20.95
41
0.694511
[ "MIT" ]
igromanru/Lunar
Lunar/Native/Structures/ListEntry.cs
419
C#
using System.Threading.Tasks; using FluentScheduler; using Plutus.Core.Enums; using Plutus.Core.Interfaces; namespace Plutus.Core.Jobs { public class BuyJob : IJob { private readonly IPlutusService _plutusService; private readonly bool _test; public BuyJob(IPlutusService plutusService, bool test) { _plutusService = plutusService; _test = test; } public void Execute() { Parallel.ForEach(_plutusService.Orders, async (order) => { // Check price of symbol var price = await _plutusService.GetPrice(order.Base, order.Symbol); // Determine if its going up or down var prediction = await _plutusService.GetPricePrediction(order.Base, order.Symbol, Period.Hourly); if (prediction == PricePrediction.Bullish) { // If its going up, var buyAmount = order.BuyAmount; // Calculate cost var cost = price * buyAmount; // Check if balance is sufficent var isBalanceSufficent = await _plutusService.CheckBalance(cost, order.Base); if (isBalanceSufficent) { // If balance is sufficient, buy if (_test) { await _plutusService.BuyTest(order.Symbol, order.Base, buyAmount, price); } else { await _plutusService.Buy(order.Symbol, order.Base, buyAmount, price); } } } }); } } }
32.482143
114
0.492029
[ "MIT" ]
umutseven92/Plutus
Plutus.Core/Jobs/BuyJob.cs
1,821
C#
using System; namespace g { class Program { static void Main(string[] args) { Console.WriteLine("Q#53 (g)"); int n; float n = 3.8 ; n = x; Console.WriteLine(n); } } }
16.529412
43
0.384342
[ "Apache-2.0" ]
AbdulMueed209/Assingnment-4
Q#53 g.cs
283
C#
using System; [Serializable] public class ChunkDefinition { public string Asset = "..."; public float Width = 0f; }
15.625
32
0.672
[ "MIT" ]
Master-Maniac/Endless-Runner-Entitas-ECS
Assets/Sources/Data/ChunkDefinition.cs
127
C#
//////////////////////////////////////////////////////////////////////////////// //EF Core Provider for LCPI OLE DB. // IBProvider and Contributors. 07.05.2021. using System; using System.Diagnostics; using System.Reflection; namespace Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb.Basement.EF.Root.Query.Local.Expressions.Op2.Code{ //////////////////////////////////////////////////////////////////////////////// //using using T_ARG1 =System.Int16; using T_ARG2 =System.Nullable<System.Int32>; using T_RESULT =System.Boolean; //////////////////////////////////////////////////////////////////////////////// //class Op2_Code__Equal___Int16__NullableInt32 static class Op2_Code__Equal___Int16__NullableInt32 { public static readonly System.Reflection.MethodInfo MethodInfo_V_V =typeof(Op2_Code__Equal___Int16__NullableInt32) .GetTypeInfo() .GetDeclaredMethod(nameof(Exec_V_V)); //----------------------------------------------------------------------- private static T_RESULT Exec_V_V(T_ARG1 a,T_ARG2 b) { if(!b.HasValue) return Op2_MasterResults__Equal.VALUE__NULL; Debug.Assert(b.HasValue); return MasterCode.Op2_MasterCode__Equal___Int32__Int32.Exec (a, b.Value); }//Exec_V_V };//class Op2_Code__Equal___Int16__NullableInt32 //////////////////////////////////////////////////////////////////////////////// }//namespace Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb.Basement.EF.Root.Query.Local.Expressions.Op2.Code
31.708333
110
0.564389
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Code/Provider/Source/Basement/EF/Root/Query/Local/Expressions/Op2/Code/Equal/Int16/Op2_Code__Equal___Int16__NullableInt32.cs
1,524
C#
namespace XXX.Plugin.FreeSql { /// <summary> /// 实体之间隐射配置 /// 数据库实体与AO业务实体互相映射 /// </summary> public class UserMapper : Profile, IOrderedMapperProfile { /// <summary> /// /// </summary> public UserMapper() { //数据库实体映射AO业务实体,ReverseMap可实现双向映射 CreateMap<UserInsertAo, User>().ReverseMap(); CreateMap<UserUpdateAo, User>().ReverseMap(); CreateMap<UserInsertAo, UserProfile>().ReverseMap(); } /// <summary> /// 映射顺序,默认0即可,无需更改 /// </summary> public int Order => 0; } }
24
64
0.522436
[ "MIT" ]
KamenRiderKuuga/NetPro
src/sample/XXX.Plugin.FreeSql/Mapper/XXXMapper.cs
734
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Lp.Model.EarlyBound { [System.Runtime.Serialization.DataContractAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "9.0.0.9369")] public enum SystemForm_FormPresentation { [System.Runtime.Serialization.EnumMemberAttribute()] AirForm = 1, [System.Runtime.Serialization.EnumMemberAttribute()] ClassicForm = 0, [System.Runtime.Serialization.EnumMemberAttribute()] ConvertedICForm = 2, } }
29.814815
80
0.585093
[ "Unlicense" ]
DEFRA/license-and-permitting-dynamics
Crm/LicensingandPermitting/Defra.Lp/Model.Lp/EarlyBound/OptionSets/SystemForm_FormPresentation.cs
805
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace meshDatabase.Database { public class Record { public Record(DBC dbc) { Source = dbc; } public DBC Source { get; private set; } public List<int> Values = new List<int>(); public int this[int index] { get { return Values[index]; } } public float GetFloat(int index) { var data = BitConverter.GetBytes(Values[index]); return BitConverter.ToSingle(data, 0); } public string GetString(int index) { return Source.GetStringByOffset(Values[index]); } } public class DBC { public DBC(Stream src) { using (src) { using (var reader = new BinaryReader(src)) { var magic = reader.ReadBytes(4); RecordCount = reader.ReadInt32(); Records = new List<Record>(RecordCount); Fields = reader.ReadInt32(); RecordSize = reader.ReadInt32(); var stringBlockSize = reader.ReadInt32(); for (int i = 0; i < RecordCount; i++) { var rec = new Record(this); Records.Add(rec); int size = 0; for (int f = 0; f < Fields; f++) { if (size + 4 > RecordSize) { IsFaulty = true; break; } rec.Values.Add(reader.ReadInt32()); size += 4; } } StringBlock = reader.ReadBytes(stringBlockSize); } } } public string GetStringByOffset(int offset) { int len = 0; for (int i = offset; i < StringBlock.Length; i++) { if (StringBlock[i] == 0x00) { len = (i - offset); break; } } return Encoding.UTF8.GetString(StringBlock, offset, len); } public Record GetRecordById(int id) { // we assume Id is index 0 return Records.Where(r => r.Values[0] == id).FirstOrDefault(); } public string Name { get; private set; } public List<Record> Records { get; private set; } public int RecordCount { get; private set; } public int Fields { get; private set; } public int RecordSize { get; private set; } public byte[] StringBlock { get; private set; } public bool IsFaulty { get; private set; } } }
29.54717
75
0.416986
[ "Unlicense" ]
Bia10/meshReader
meshDatabase/Database/DBC.cs
3,134
C#
namespace Altsoft.PDFO { using Altsoft.Common; using System; public class AnnotationText : AnnotationMarkup { // Methods public AnnotationText(PDFDict dict) : base(dict) { } public static AnnotationText Create(Rect rect) { PDFDict dict1 = Library.CreateDict(); dict1["Subtype"] = Library.CreateName("Text"); dict1["Type"] = Library.CreateName("Annot"); AnnotationText text1 = (Resources.Get(dict1, typeof(AnnotationText)) as AnnotationText); text1.Rect = rect; Library.CreateIndirect(dict1); return text1; } // Properties public string IconName { get { PDFName name1 = (this.Dict["Name"] as PDFName); if (name1 == null) { return "Note"; } return name1.Value; } set { this.Dict["Name"] = Library.CreateName(value); } } public Annotation InReplyTo { get { PDFDict dict1 = (this.Dict["IRT"] as PDFDict); if (dict1 == null) { return null; } return (Resources.Get(dict1, typeof(Annotation)) as Annotation); } set { this.Dict["IRT"] = value.Direct; } } public bool OpenFlag { get { PDFBoolean flag1 = (this.Dict["Open"] as PDFBoolean); if (flag1 == null) { return false; } return flag1.Value; } set { this.Dict["Open"] = Library.CreateBoolean(value); } } public States State { get { PDFString text1 = (this.Dict["State"] as PDFString); if (text1 == null) { if (this.StateModel == StateModels.Marked) { return States.Unmarked; } return States.None; } string text2 = text1.Value; if (text2 == null) { goto Label_00A3; } text2 = string.IsInterned(text2); if (text2 != "Marked") { if (text2 == "Unmarked") { goto Label_0097; } if (text2 == "Accepted") { goto Label_0099; } if (text2 == "Rejected") { goto Label_009B; } if (text2 == "Cancelled") { goto Label_009D; } if (text2 == "Completed") { goto Label_009F; } if (text2 == "None") { goto Label_00A1; } goto Label_00A3; } return States.Marked; Label_0097: return States.Unmarked; Label_0099: return States.Accepted; Label_009B: return States.Rejected; Label_009D: return States.Cancelled; Label_009F: return States.Completed; Label_00A1: return States.None; Label_00A3: throw new Exception("Unknown state"); } set { string text1 = "None"; States states1 = value; switch (states1) { case States.Marked: { text1 = "Marked"; goto Label_0062; } case States.Unmarked: { text1 = "Unmarked"; goto Label_0062; } case States.Accepted: { text1 = "Accepted"; goto Label_0062; } case States.Rejected: { text1 = "Rejected"; goto Label_0062; } case States.Cancelled: { text1 = "Cancelled"; goto Label_0062; } case States.Completed: { text1 = "Completed"; goto Label_0062; } case States.None: { goto Label_005C; } } goto Label_0062; Label_005C: text1 = "None"; Label_0062: this.Dict["State"] = Library.CreateString(text1); } } public StateModels StateModel { get { PDFString text1 = (this.Dict["StateModel"] as PDFString); if (text1 == null) { return StateModels.None; } string text2 = text1.Value; if (text2 == null) { goto Label_004E; } text2 = string.IsInterned(text2); if (text2 != "Review") { if (text2 == "Marked") { goto Label_004C; } goto Label_004E; } return StateModels.Review; Label_004C: return StateModels.Marked; Label_004E: throw new Exception("Unknown state model"); } set { string text1 = "Unknown"; StateModels models1 = value; switch (models1) { case StateModels.Marked: { goto Label_0020; } case StateModels.Review: { text1 = "Review"; goto Label_0026; } } goto Label_0026; Label_0020: text1 = "Marked"; Label_0026: this.Dict["StateModel"] = Library.CreateString(text1); } } // Fields public const string SubType = "Text"; } }
28.971774
100
0.346138
[ "MIT" ]
silvath/siscobras
mdlPDF/Xml2PDF/Source/Altsoft/PDFO/AnnotationText.cs
7,185
C#
using SystemDot.Messaging.Simple; using Machine.Specifications; namespace SystemDot.Specifications.messenger { [Subject(SpecificationGroup.Description)] public class when_sending_a_message_to_a_registered_handler_that_replies_and_the_reply_is_handled_in_the_call { static TestReply handledReply; static TestRequest request; static TestReply reply; Establish context = () => { request = new TestRequest(); reply = new TestReply(); Messenger.RegisterHandler<TestRequest>(m => Messenger.Reply(reply)); }; Because of = () => Messenger.Send<TestRequest, TestReply>(request, r => handledReply = r); It should_handle_the_response = () => handledReply.ShouldBeTheSameAs(reply); } }
33.041667
113
0.686003
[ "Apache-2.0" ]
SystemDot/SystemDotCore
Projects/SystemDot.Specifications/messenger/when_sending_a_message_to_a_registered_handler_that_replies_and_the_reply_is_handled_in_the_call.cs
793
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.Gcp.Diagflow.Inputs { public sealed class FulfillmentGenericWebServiceArgs : Pulumi.ResourceArgs { /// <summary> /// The password for HTTP Basic authentication. /// </summary> [Input("password")] public Input<string>? Password { get; set; } [Input("requestHeaders")] private InputMap<string>? _requestHeaders; /// <summary> /// The HTTP request headers to send together with fulfillment requests. /// </summary> public InputMap<string> RequestHeaders { get => _requestHeaders ?? (_requestHeaders = new InputMap<string>()); set => _requestHeaders = value; } /// <summary> /// The fulfillment URI for receiving POST requests. It must use https protocol. /// </summary> [Input("uri", required: true)] public Input<string> Uri { get; set; } = null!; /// <summary> /// The user name for HTTP Basic authentication. /// </summary> [Input("username")] public Input<string>? Username { get; set; } public FulfillmentGenericWebServiceArgs() { } } }
30.42
88
0.608153
[ "ECL-2.0", "Apache-2.0" ]
la3mmchen/pulumi-gcp
sdk/dotnet/Diagflow/Inputs/FulfillmentGenericWebServiceArgs.cs
1,521
C#
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Shapes; /// <summary> /// A canvas that can visualise a 2d array of rectangles. /// </summary> public class RectangleCanvas : Canvas { /// <summary> /// This variable specifies the width of the canvas and therefore the amount of rectangles that can be visualised. Once modified use update rects to apply the change. /// </summary> public int GridWidth { get { return (int) GetValue(GridWidthProperty); } set { SetValue(GridWidthProperty, value); Width = value; } } public static readonly DependencyProperty GridWidthProperty = DependencyProperty.Register("GridWidth", typeof(int), typeof(RectangleCanvas), new PropertyMetadata(0)); /// <summary> /// This variable specifies the height of the canvas and therefore the amount of rectangles that can be visualised. Once modified use update rects to apply the change. /// </summary> public int GridHeight { get { return (int) GetValue(GridHeightProperty); } set { SetValue(GridHeightProperty, value); Height = value; } } public static readonly DependencyProperty GridHeightProperty = DependencyProperty.Register("GridHeight", typeof(int), typeof(RectangleCanvas), new PropertyMetadata(0)); /// <summary> /// This variable specifies the pixel size of each rect. Once modified use update rects to apply the change. /// </summary> public int PointSize { get { return (int)GetValue(PointSizeProperty); } set { SetValue(PointSizeProperty, value); } } public static readonly DependencyProperty PointSizeProperty = DependencyProperty.Register("PointSize", typeof(int), typeof(RectangleCanvas), new PropertyMetadata(0)); public Rectangle[,] Rectangles; /// <summary> /// This method has to be called in order to commit the change from a height / width change /// </summary> public void UpdateRects() { GenerateRects(); } protected void GenerateRects() { Rectangles = new Rectangle[GridHeight / PointSize, GridWidth / PointSize]; // width for (int x = 0; x < GridWidth; x += PointSize) { // height for (int y = 0; y < GridHeight; y += PointSize) { Rectangle rect = new Rectangle { Opacity = 0, Width = Math.Min(PointSize, GridWidth - x), Height = Math.Min(PointSize, GridHeight - y), }; SetLeft(rect, x); SetTop(rect, y); Rectangles[y / PointSize, x / PointSize] = rect; Children.Add(rect); } } } protected Rectangle[] GetNeighbours(Rectangle[,] rectangles, int row, int column) { int height = rectangles.GetLength(0); int width = rectangles.GetLength(1); Rectangle[] rects = new Rectangle[8]; // cells above if (row > 0) { // cell topleft if (column > 0) { rects[0] = rectangles[row - 1, column - 1]; } // cell top rects[1] = rectangles[row - 1, column]; // cell topright if (column + 1 < width) { rects[2] = rectangles[row - 1, column + 1]; } } // cell right if (column + 1 < width) { rects[3] = rectangles[row, column + 1]; } if (row + 1 < height) { // cell bottom right if (column + 1 < width) { rects[4] = rectangles[row + 1, column + 1]; } // cell bottom rects[5] = rectangles[row + 1, column]; if (column > 0) { rects[6] = rectangles[row + 1, column - 1]; } } if (column > 0) { rects[7] = rectangles[row, column - 1]; } return rects; } public void Clear() { if (Rectangles != null) { foreach (Rectangle rectangle in Rectangles) { rectangle.Opacity = 0; rectangle.Fill = null; } } } /// <summary> /// The values of the panels normalised between [0;1] /// </summary> /// <returns>The normalised values.</returns> public double[,] GetValues() { if (Rectangles == null) { return null; } double[,] values = new double[Rectangles.GetLength(0), Rectangles.GetLength(1)]; for (int i = 0; i < Rectangles.GetLength(0); i++) { for (int j = 0; j < Rectangles.GetLength(1); j++) { values[i, j] = Rectangles[i, j].Opacity; } } return values; } }
22.47541
168
0.648189
[ "MIT" ]
GreekDictionary/Sigma
Sigma.Core.Monitors.WPF/View/CustomControls/Panels/Control/RectangleCanvas.cs
4,115
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; using Azure.ResourceManager.Compute.Models; namespace Azure.ResourceManager.Compute { /// <summary> The operation to create or update the VMSS VM extension. </summary> public partial class VirtualMachineScaleSetVMExtensionsCreateOrUpdateOperation : Operation<VirtualMachineExtension>, IOperationSource<VirtualMachineExtension> { private readonly ArmOperationHelpers<VirtualMachineExtension> _operation; /// <summary> Initializes a new instance of VirtualMachineScaleSetVMExtensionsCreateOrUpdateOperation for mocking. </summary> protected VirtualMachineScaleSetVMExtensionsCreateOrUpdateOperation() { } internal VirtualMachineScaleSetVMExtensionsCreateOrUpdateOperation(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, Request request, Response response) { _operation = new ArmOperationHelpers<VirtualMachineExtension>(this, clientDiagnostics, pipeline, request, response, OperationFinalStateVia.Location, "VirtualMachineScaleSetVMExtensionsCreateOrUpdateOperation"); } /// <inheritdoc /> public override string Id => _operation.Id; /// <inheritdoc /> public override VirtualMachineExtension Value => _operation.Value; /// <inheritdoc /> public override bool HasCompleted => _operation.HasCompleted; /// <inheritdoc /> public override bool HasValue => _operation.HasValue; /// <inheritdoc /> public override Response GetRawResponse() => _operation.GetRawResponse(); /// <inheritdoc /> public override Response UpdateStatus(CancellationToken cancellationToken = default) => _operation.UpdateStatus(cancellationToken); /// <inheritdoc /> public override ValueTask<Response> UpdateStatusAsync(CancellationToken cancellationToken = default) => _operation.UpdateStatusAsync(cancellationToken); /// <inheritdoc /> public override ValueTask<Response<VirtualMachineExtension>> WaitForCompletionAsync(CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(cancellationToken); /// <inheritdoc /> public override ValueTask<Response<VirtualMachineExtension>> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(pollingInterval, cancellationToken); VirtualMachineExtension IOperationSource<VirtualMachineExtension>.CreateResult(Response response, CancellationToken cancellationToken) { using var document = JsonDocument.Parse(response.ContentStream); return VirtualMachineExtension.DeserializeVirtualMachineExtension(document.RootElement); } async ValueTask<VirtualMachineExtension> IOperationSource<VirtualMachineExtension>.CreateResultAsync(Response response, CancellationToken cancellationToken) { using var document = await JsonDocument.ParseAsync(response.ContentStream, default, cancellationToken).ConfigureAwait(false); return VirtualMachineExtension.DeserializeVirtualMachineExtension(document.RootElement); } } }
47.438356
238
0.757147
[ "MIT" ]
AME-Redmond/azure-sdk-for-net
sdk/compute/Azure.ResourceManager.Compute/src/Generated/VirtualMachineScaleSetVMExtensionsCreateOrUpdateOperation.cs
3,463
C#
//--------------------------------------------------------------------------------------------------- // <auto-generated> // Changes to this file may cause incorrect behavior and will be lost if the code is regenerated. // Generated by DynamicsCrm.DevKit - https://github.com/phuocle/Dynamics-Crm-DevKit // </auto-generated> //--------------------------------------------------------------------------------------------------- using Microsoft.Xrm.Sdk; using System; using System.Diagnostics; namespace Dev.DevKit.Shared.Entities.msdyn_projectapprovalOptionSets { public enum msdyn_BillingType { /// <summary> /// Chargeable = 192350001 /// </summary> Chargeable = 192350001, /// <summary> /// Complimentary = 192350002 /// </summary> Complimentary = 192350002, /// <summary> /// Non_Chargeable = 192350000 /// </summary> Non_Chargeable = 192350000, /// <summary> /// Not_Available = 192350003 /// </summary> Not_Available = 192350003 } public enum msdyn_EntryType { /// <summary> /// Expense = 1 /// </summary> Expense = 1, /// <summary> /// Time = 0 /// </summary> Time = 0 } public enum msdyn_recordstage { /// <summary> /// Approved = 2 /// </summary> Approved = 2, /// <summary> /// Pending = 3 /// </summary> Pending = 3, /// <summary> /// Recall_Request_Approved = 5 /// </summary> Recall_Request_Approved = 5, /// <summary> /// Recall_Request_Rejected = 6 /// </summary> Recall_Request_Rejected = 6, /// <summary> /// Recall_Requested = 4 /// </summary> Recall_Requested = 4, /// <summary> /// Rejected = 1 /// </summary> Rejected = 1, /// <summary> /// Submitted = 0 /// </summary> Submitted = 0 } public enum statecode { /// <summary> /// Active = 0 /// </summary> Active = 0, /// <summary> /// Inactive = 1 /// </summary> Inactive = 1 } public enum statuscode { /// <summary> /// Active = 1 /// </summary> Active = 1, /// <summary> /// Inactive = 2 /// </summary> Inactive = 2 } } namespace Dev.DevKit.Shared.Entities { public partial class msdyn_projectapproval : EntityBase { public struct Fields { public const string CreatedBy = "createdby"; public const string CreatedOn = "createdon"; public const string CreatedOnBehalfBy = "createdonbehalfby"; public const string ExchangeRate = "exchangerate"; public const string ImportSequenceNumber = "importsequencenumber"; public const string ModifiedBy = "modifiedby"; public const string ModifiedOn = "modifiedon"; public const string ModifiedOnBehalfBy = "modifiedonbehalfby"; public const string msdyn_ApprovedBy = "msdyn_approvedby"; public const string msdyn_ApprovedOn = "msdyn_approvedon"; public const string msdyn_BillingType = "msdyn_billingtype"; public const string msdyn_bookableresource = "msdyn_bookableresource"; public const string msdyn_costamount = "msdyn_costamount"; public const string msdyn_costamount_Base = "msdyn_costamount_base"; public const string msdyn_CostPrice = "msdyn_costprice"; public const string msdyn_costprice_Base = "msdyn_costprice_base"; public const string msdyn_CostQuantity = "msdyn_costquantity"; public const string msdyn_date = "msdyn_date"; public const string msdyn_EntryType = "msdyn_entrytype"; public const string msdyn_ExpenseCategory = "msdyn_expensecategory"; public const string msdyn_ExpenseEntry = "msdyn_expenseentry"; public const string msdyn_ExternalComments = "msdyn_externalcomments"; public const string msdyn_hasreceipt = "msdyn_hasreceipt"; public const string msdyn_InternalComments = "msdyn_internalcomments"; public const string msdyn_JournalTransaction = "msdyn_journaltransaction"; public const string msdyn_Manager = "msdyn_manager"; public const string msdyn_name = "msdyn_name"; public const string msdyn_Project = "msdyn_project"; public const string msdyn_projectapprovalId = "msdyn_projectapprovalid"; public const string msdyn_ProjectTask = "msdyn_projecttask"; public const string msdyn_recordstage = "msdyn_recordstage"; public const string msdyn_referenceexpenseid = "msdyn_referenceexpenseid"; public const string msdyn_referencejournalline = "msdyn_referencejournalline"; public const string msdyn_referencetimeid = "msdyn_referencetimeid"; public const string msdyn_ResourceCategory = "msdyn_resourcecategory"; public const string msdyn_salesamount = "msdyn_salesamount"; public const string msdyn_salesamount_Base = "msdyn_salesamount_base"; public const string msdyn_SalesPrice = "msdyn_salesprice"; public const string msdyn_salesprice_Base = "msdyn_salesprice_base"; public const string msdyn_SalesQuantity = "msdyn_salesquantity"; public const string msdyn_SubmittedBy = "msdyn_submittedby"; public const string msdyn_TimeEntry = "msdyn_timeentry"; public const string msdyn_TransactionCategory = "msdyn_transactioncategory"; public const string OverriddenCreatedOn = "overriddencreatedon"; public const string OwnerId = "ownerid"; public const string OwningBusinessUnit = "owningbusinessunit"; public const string OwningTeam = "owningteam"; public const string OwningUser = "owninguser"; public const string statecode = "statecode"; public const string statuscode = "statuscode"; public const string TimeZoneRuleVersionNumber = "timezoneruleversionnumber"; public const string TransactionCurrencyId = "transactioncurrencyid"; public const string UTCConversionTimeZoneCode = "utcconversiontimezonecode"; public const string VersionNumber = "versionnumber"; } public const string EntityLogicalName = "msdyn_projectapproval"; public const int EntityTypeCode = 10364; [DebuggerNonUserCode()] public msdyn_projectapproval() { Entity = new Entity(EntityLogicalName); PreEntity = CloneThisEntity(Entity); } [DebuggerNonUserCode()] public msdyn_projectapproval(Guid msdyn_projectapprovalId) { Entity = new Entity(EntityLogicalName, msdyn_projectapprovalId); PreEntity = CloneThisEntity(Entity); } [DebuggerNonUserCode()] public msdyn_projectapproval(string keyName, object keyValue) { Entity = new Entity(EntityLogicalName, keyName, keyValue); PreEntity = CloneThisEntity(Entity); } [DebuggerNonUserCode()] public msdyn_projectapproval(Entity entity) { Entity = entity; PreEntity = CloneThisEntity(Entity); } [DebuggerNonUserCode()] public msdyn_projectapproval(Entity entity, Entity merge) { Entity = entity; foreach (var property in merge?.Attributes) { var key = property.Key; var value = property.Value; Entity[key] = value; } PreEntity = CloneThisEntity(Entity); } [DebuggerNonUserCode()] public msdyn_projectapproval(KeyAttributeCollection keys) { Entity = new Entity(EntityLogicalName, keys); PreEntity = CloneThisEntity(Entity); } /// <summary> /// <para>Unique identifier of the user who created the record.</para> /// <para>ReadOnly - Lookup to systemuser</para> /// <para>Created By</para> /// </summary> [DebuggerNonUserCode()] public EntityReference CreatedBy { get { return Entity.GetAttributeValue<EntityReference>(Fields.CreatedBy); } } /// <summary> /// <para>Date and time when the record was created.</para> /// <para>ReadOnly - DateTimeBehavior: UserLocal - DateTimeFormat: DateAndTime</para> /// <para>Created On</para> /// </summary> [DebuggerNonUserCode()] public DateTime? CreatedOnUtc { get { return Entity.GetAttributeValue<DateTime?>(Fields.CreatedOn); } } /// <summary> /// <para>Unique identifier of the delegate user who created the record.</para> /// <para>ReadOnly - Lookup to systemuser</para> /// <para>Created By (Delegate)</para> /// </summary> [DebuggerNonUserCode()] public EntityReference CreatedOnBehalfBy { get { return Entity.GetAttributeValue<EntityReference>(Fields.CreatedOnBehalfBy); } } /// <summary> /// <para>Exchange rate for the currency associated with the entity with respect to the base currency.</para> /// <para>ReadOnly - Decimal - MinValue: 0 - MaxValue: 100,000,000,000</para> /// <para>Exchange Rate</para> /// </summary> [DebuggerNonUserCode()] public decimal? ExchangeRate { get { return Entity.GetAttributeValue<decimal?>(Fields.ExchangeRate); } } /// <summary> /// <para>Sequence number of the import that created this record.</para> /// <para>Integer - MinValue: -2,147,483,648 - MaxValue: 2,147,483,647</para> /// <para>Import Sequence Number</para> /// </summary> [DebuggerNonUserCode()] public int? ImportSequenceNumber { get { return Entity.GetAttributeValue<int?>(Fields.ImportSequenceNumber); } set { Entity.Attributes[Fields.ImportSequenceNumber] = value; } } /// <summary> /// <para>Unique identifier of the user who modified the record.</para> /// <para>ReadOnly - Lookup to systemuser</para> /// <para>Modified By</para> /// </summary> [DebuggerNonUserCode()] public EntityReference ModifiedBy { get { return Entity.GetAttributeValue<EntityReference>(Fields.ModifiedBy); } } /// <summary> /// <para>Date and time when the record was modified.</para> /// <para>ReadOnly - DateTimeBehavior: UserLocal - DateTimeFormat: DateAndTime</para> /// <para>Modified On</para> /// </summary> [DebuggerNonUserCode()] public DateTime? ModifiedOnUtc { get { return Entity.GetAttributeValue<DateTime?>(Fields.ModifiedOn); } } /// <summary> /// <para>Unique identifier of the delegate user who modified the record.</para> /// <para>ReadOnly - Lookup to systemuser</para> /// <para>Modified By (Delegate)</para> /// </summary> [DebuggerNonUserCode()] public EntityReference ModifiedOnBehalfBy { get { return Entity.GetAttributeValue<EntityReference>(Fields.ModifiedOnBehalfBy); } } /// <summary> /// <para>Shows the name of the approver.</para> /// <para>Lookup to systemuser</para> /// <para>Approved By</para> /// </summary> [DebuggerNonUserCode()] public EntityReference msdyn_ApprovedBy { get { return Entity.GetAttributeValue<EntityReference>(Fields.msdyn_ApprovedBy); } set { Entity.Attributes[Fields.msdyn_ApprovedBy] = value; } } /// <summary> /// <para>Shows the date of the approval.</para> /// <para>DateTimeBehavior: UserLocal - DateTimeFormat: DateOnly</para> /// <para>Approved On</para> /// </summary> [DebuggerNonUserCode()] public DateTime? msdyn_ApprovedOnUtc { get { return Entity.GetAttributeValue<DateTime?>(Fields.msdyn_ApprovedOn); } set { Entity.Attributes[Fields.msdyn_ApprovedOn] = value; } } /// <summary> /// <para>Billing type for the project approval line.</para> /// <para>Picklist</para> /// <para>Billing Type</para> /// </summary> [DebuggerNonUserCode()] public Dev.DevKit.Shared.Entities.msdyn_projectapprovalOptionSets.msdyn_BillingType? msdyn_BillingType { get { var value = Entity.GetAttributeValue<OptionSetValue>(Fields.msdyn_BillingType); if (value == null) return null; return (Dev.DevKit.Shared.Entities.msdyn_projectapprovalOptionSets.msdyn_BillingType)value.Value; } set { if (value.HasValue) Entity.Attributes[Fields.msdyn_BillingType] = new OptionSetValue((int)value.Value); else Entity.Attributes[Fields.msdyn_BillingType] = null; } } /// <summary> /// <para>Shows the resource that the entry is submitted for.</para> /// <para>Lookup to bookableresource</para> /// <para>Resource</para> /// </summary> [DebuggerNonUserCode()] public EntityReference msdyn_bookableresource { get { return Entity.GetAttributeValue<EntityReference>(Fields.msdyn_bookableresource); } set { Entity.Attributes[Fields.msdyn_bookableresource] = value; } } /// <summary> /// <para>Shows the cost amount of the transaction.</para> /// <para>ReadOnly - Money - MinValue: -922,337,203,685,477 - MaxValue: 922,337,203,685,477</para> /// <para>Cost Amount</para> /// </summary> [DebuggerNonUserCode()] public decimal? msdyn_costamount { get { var value = Entity.GetAttributeValue<Money>(Fields.msdyn_costamount); if (value == null) return null; return value.Value; } } /// <summary> /// <para>Value of the Cost Amount in base currency.</para> /// <para>ReadOnly - Money - MinValue: -922,337,203,685,477 - MaxValue: 922,337,203,685,477</para> /// <para>Cost Amount (Base)</para> /// </summary> [DebuggerNonUserCode()] public decimal? msdyn_costamount_Base { get { var value = Entity.GetAttributeValue<Money>(Fields.msdyn_costamount_Base); if (value == null) return null; return value.Value; } } /// <summary> /// <para>Shows the cost price of the transaction.</para> /// <para>Money - MinValue: -922,337,203,685,477 - MaxValue: 922,337,203,685,477</para> /// <para>Cost Price</para> /// </summary> [DebuggerNonUserCode()] public decimal? msdyn_CostPrice { get { var value = Entity.GetAttributeValue<Money>(Fields.msdyn_CostPrice); if (value == null) return null; return value.Value; } set { if (value.HasValue) Entity.Attributes[Fields.msdyn_CostPrice] = new Money(value.Value); else Entity.Attributes[Fields.msdyn_CostPrice] = null; } } /// <summary> /// <para>Value of the Cost Price in base currency.</para> /// <para>ReadOnly - Money - MinValue: -922,337,203,685,477 - MaxValue: 922,337,203,685,477</para> /// <para>Cost Price (Base)</para> /// </summary> [DebuggerNonUserCode()] public decimal? msdyn_costprice_Base { get { var value = Entity.GetAttributeValue<Money>(Fields.msdyn_costprice_Base); if (value == null) return null; return value.Value; } } /// <summary> /// <para>Shows the hours submitted for the transaction.</para> /// <para>Decimal - MinValue: -100,000,000,000 - MaxValue: 100,000,000,000</para> /// <para>Submitted (hrs)</para> /// </summary> [DebuggerNonUserCode()] public decimal? msdyn_CostQuantity { get { return Entity.GetAttributeValue<decimal?>(Fields.msdyn_CostQuantity); } set { Entity.Attributes[Fields.msdyn_CostQuantity] = value; } } /// <summary> /// <para>Shows the date of the transaction.</para> /// <para>DateTimeBehavior: UserLocal - DateTimeFormat: DateOnly</para> /// <para>Date</para> /// </summary> [DebuggerNonUserCode()] public DateTime? msdyn_dateUtc { get { return Entity.GetAttributeValue<DateTime?>(Fields.msdyn_date); } set { Entity.Attributes[Fields.msdyn_date] = value; } } /// <summary> /// <para>Shows the entry type of the transaction.</para> /// <para>Picklist</para> /// <para>Entry Type</para> /// </summary> [DebuggerNonUserCode()] public Dev.DevKit.Shared.Entities.msdyn_projectapprovalOptionSets.msdyn_EntryType? msdyn_EntryType { get { var value = Entity.GetAttributeValue<OptionSetValue>(Fields.msdyn_EntryType); if (value == null) return null; return (Dev.DevKit.Shared.Entities.msdyn_projectapprovalOptionSets.msdyn_EntryType)value.Value; } set { if (value.HasValue) Entity.Attributes[Fields.msdyn_EntryType] = new OptionSetValue((int)value.Value); else Entity.Attributes[Fields.msdyn_EntryType] = null; } } /// <summary> /// <para>Shows the expense category of the transaction.</para> /// <para>Lookup to msdyn_expensecategory</para> /// <para>Expense Category</para> /// </summary> [DebuggerNonUserCode()] public EntityReference msdyn_ExpenseCategory { get { return Entity.GetAttributeValue<EntityReference>(Fields.msdyn_ExpenseCategory); } set { Entity.Attributes[Fields.msdyn_ExpenseCategory] = value; } } /// <summary> /// <para>Expense Entry Id.</para> /// <para>Lookup to msdyn_expense</para> /// <para>Expense Entry</para> /// </summary> [DebuggerNonUserCode()] public EntityReference msdyn_ExpenseEntry { get { return Entity.GetAttributeValue<EntityReference>(Fields.msdyn_ExpenseEntry); } set { Entity.Attributes[Fields.msdyn_ExpenseEntry] = value; } } /// <summary> /// <para>Shows the external comments entered for the transaction.</para> /// <para>String - MaxLength: 100</para> /// <para>External Comments</para> /// </summary> [DebuggerNonUserCode()] public string msdyn_ExternalComments { get { return Entity.GetAttributeValue<string>(Fields.msdyn_ExternalComments); } set { Entity.Attributes[Fields.msdyn_ExternalComments] = value; } } /// <summary> /// <para>Shows whether the transaction has a receipt.</para> /// <para>Boolean</para> /// <para>Has Receipt</para> /// </summary> [DebuggerNonUserCode()] public bool? msdyn_hasreceipt { get { return Entity.GetAttributeValue<bool?>(Fields.msdyn_hasreceipt); } set { Entity.Attributes[Fields.msdyn_hasreceipt] = value; } } /// <summary> /// <para>Shows the internal comments entered for the transaction.</para> /// <para>String - MaxLength: 100</para> /// <para>Internal Comments</para> /// </summary> [DebuggerNonUserCode()] public string msdyn_InternalComments { get { return Entity.GetAttributeValue<string>(Fields.msdyn_InternalComments); } set { Entity.Attributes[Fields.msdyn_InternalComments] = value; } } /// <summary> /// <para>Shows whether the transaction was entered by a journal.</para> /// <para>String - MaxLength: 100</para> /// <para>JournalTransaction</para> /// </summary> [DebuggerNonUserCode()] public string msdyn_JournalTransaction { get { return Entity.GetAttributeValue<string>(Fields.msdyn_JournalTransaction); } set { Entity.Attributes[Fields.msdyn_JournalTransaction] = value; } } /// <summary> /// <para>Shows the manager of the person who submitted the transaction.</para> /// <para>Lookup to systemuser</para> /// <para>Manager</para> /// </summary> [DebuggerNonUserCode()] public EntityReference msdyn_Manager { get { return Entity.GetAttributeValue<EntityReference>(Fields.msdyn_Manager); } set { Entity.Attributes[Fields.msdyn_Manager] = value; } } /// <summary> /// <para>The name of the custom entity.</para> /// <para>Required - String - MaxLength: 100</para> /// <para>Name</para> /// </summary> [DebuggerNonUserCode()] public string msdyn_name { get { return Entity.GetAttributeValue<string>(Fields.msdyn_name); } set { Entity.Attributes[Fields.msdyn_name] = value; } } /// <summary> /// <para>Shows the project for the transaction.</para> /// <para>Lookup to msdyn_project</para> /// <para>Project</para> /// </summary> [DebuggerNonUserCode()] public EntityReference msdyn_Project { get { return Entity.GetAttributeValue<EntityReference>(Fields.msdyn_Project); } set { Entity.Attributes[Fields.msdyn_Project] = value; } } /// <summary> /// <para>Unique identifier for entity instances</para> /// <para>Primary Key - Uniqueidentifier</para> /// <para>ApprovalsTable</para> /// </summary> [DebuggerNonUserCode()] public Guid msdyn_projectapprovalId { get { return Id; } set { Entity.Attributes[Fields.msdyn_projectapprovalId] = value; Entity.Id = value; } } /// <summary> /// <para>Shows the project task for the transaction.</para> /// <para>Lookup to msdyn_projecttask</para> /// <para>Project Task</para> /// </summary> [DebuggerNonUserCode()] public EntityReference msdyn_ProjectTask { get { return Entity.GetAttributeValue<EntityReference>(Fields.msdyn_ProjectTask); } set { Entity.Attributes[Fields.msdyn_ProjectTask] = value; } } /// <summary> /// <para>Shows the stage of the record.</para> /// <para>Picklist</para> /// <para>Record Stage</para> /// </summary> [DebuggerNonUserCode()] public Dev.DevKit.Shared.Entities.msdyn_projectapprovalOptionSets.msdyn_recordstage? msdyn_recordstage { get { var value = Entity.GetAttributeValue<OptionSetValue>(Fields.msdyn_recordstage); if (value == null) return null; return (Dev.DevKit.Shared.Entities.msdyn_projectapprovalOptionSets.msdyn_recordstage)value.Value; } set { if (value.HasValue) Entity.Attributes[Fields.msdyn_recordstage] = new OptionSetValue((int)value.Value); else Entity.Attributes[Fields.msdyn_recordstage] = null; } } /// <summary> /// <para>Shows the reference ID for the expense entry.</para> /// <para>String - MaxLength: 100</para> /// <para>Reference expense id</para> /// </summary> [DebuggerNonUserCode()] public string msdyn_referenceexpenseid { get { return Entity.GetAttributeValue<string>(Fields.msdyn_referenceexpenseid); } set { Entity.Attributes[Fields.msdyn_referenceexpenseid] = value; } } /// <summary> /// <para>Shows the journal line ID for the journal transaction.</para> /// <para>Lookup to msdyn_journalline</para> /// <para>reference journal line</para> /// </summary> [DebuggerNonUserCode()] public EntityReference msdyn_referencejournalline { get { return Entity.GetAttributeValue<EntityReference>(Fields.msdyn_referencejournalline); } set { Entity.Attributes[Fields.msdyn_referencejournalline] = value; } } /// <summary> /// <para>String - MaxLength: 100</para> /// <para>Reference time id</para> /// </summary> [DebuggerNonUserCode()] public string msdyn_referencetimeid { get { return Entity.GetAttributeValue<string>(Fields.msdyn_referencetimeid); } set { Entity.Attributes[Fields.msdyn_referencetimeid] = value; } } /// <summary> /// <para>Shows the role for the resource for this transaction.</para> /// <para>Lookup to bookableresourcecategory</para> /// <para>Resource Role</para> /// </summary> [DebuggerNonUserCode()] public EntityReference msdyn_ResourceCategory { get { return Entity.GetAttributeValue<EntityReference>(Fields.msdyn_ResourceCategory); } set { Entity.Attributes[Fields.msdyn_ResourceCategory] = value; } } /// <summary> /// <para>Shows the sales amount of the transaction.</para> /// <para>ReadOnly - Money - MinValue: -922,337,203,685,477 - MaxValue: 922,337,203,685,477</para> /// <para>Sales Amount</para> /// </summary> [DebuggerNonUserCode()] public decimal? msdyn_salesamount { get { var value = Entity.GetAttributeValue<Money>(Fields.msdyn_salesamount); if (value == null) return null; return value.Value; } } /// <summary> /// <para>Value of the Sales Amount in base currency.</para> /// <para>ReadOnly - Money - MinValue: -922,337,203,685,477 - MaxValue: 922,337,203,685,477</para> /// <para>Sales Amount (Base)</para> /// </summary> [DebuggerNonUserCode()] public decimal? msdyn_salesamount_Base { get { var value = Entity.GetAttributeValue<Money>(Fields.msdyn_salesamount_Base); if (value == null) return null; return value.Value; } } /// <summary> /// <para>Shows the sales price of the transaction.</para> /// <para>Money - MinValue: -922,337,203,685,477 - MaxValue: 922,337,203,685,477</para> /// <para>Sales Price</para> /// </summary> [DebuggerNonUserCode()] public decimal? msdyn_SalesPrice { get { var value = Entity.GetAttributeValue<Money>(Fields.msdyn_SalesPrice); if (value == null) return null; return value.Value; } set { if (value.HasValue) Entity.Attributes[Fields.msdyn_SalesPrice] = new Money(value.Value); else Entity.Attributes[Fields.msdyn_SalesPrice] = null; } } /// <summary> /// <para>Value of the Sales Price in base currency.</para> /// <para>ReadOnly - Money - MinValue: -922,337,203,685,477 - MaxValue: 922,337,203,685,477</para> /// <para>Sales Price (Base)</para> /// </summary> [DebuggerNonUserCode()] public decimal? msdyn_salesprice_Base { get { var value = Entity.GetAttributeValue<Money>(Fields.msdyn_salesprice_Base); if (value == null) return null; return value.Value; } } /// <summary> /// <para>Shows the billable hours for the transaction.</para> /// <para>Decimal - MinValue: -100,000,000,000 - MaxValue: 100,000,000,000</para> /// <para>Billable (hrs)</para> /// </summary> [DebuggerNonUserCode()] public decimal? msdyn_SalesQuantity { get { return Entity.GetAttributeValue<decimal?>(Fields.msdyn_SalesQuantity); } set { Entity.Attributes[Fields.msdyn_SalesQuantity] = value; } } /// <summary> /// <para>Resource that has submitted the entry for approval.</para> /// <para>Required - Lookup to bookableresource</para> /// <para>Submitted By</para> /// </summary> [DebuggerNonUserCode()] public EntityReference msdyn_SubmittedBy { get { return Entity.GetAttributeValue<EntityReference>(Fields.msdyn_SubmittedBy); } set { Entity.Attributes[Fields.msdyn_SubmittedBy] = value; } } /// <summary> /// <para>Time Entry Id.</para> /// <para>Lookup to msdyn_timeentry</para> /// <para>Time Entry</para> /// </summary> [DebuggerNonUserCode()] public EntityReference msdyn_TimeEntry { get { return Entity.GetAttributeValue<EntityReference>(Fields.msdyn_TimeEntry); } set { Entity.Attributes[Fields.msdyn_TimeEntry] = value; } } /// <summary> /// <para>Shows the transaction category.</para> /// <para>Lookup to msdyn_transactioncategory</para> /// <para>Transaction Category</para> /// </summary> [DebuggerNonUserCode()] public EntityReference msdyn_TransactionCategory { get { return Entity.GetAttributeValue<EntityReference>(Fields.msdyn_TransactionCategory); } set { Entity.Attributes[Fields.msdyn_TransactionCategory] = value; } } /// <summary> /// <para>Date and time that the record was migrated.</para> /// <para>DateTimeBehavior: UserLocal - DateTimeFormat: DateOnly</para> /// <para>Record Created On</para> /// </summary> [DebuggerNonUserCode()] public DateTime? OverriddenCreatedOnUtc { get { return Entity.GetAttributeValue<DateTime?>(Fields.OverriddenCreatedOn); } set { Entity.Attributes[Fields.OverriddenCreatedOn] = value; } } /// <summary> /// <para>Owner Id</para> /// <para>Owner</para> /// <para>Owner</para> /// </summary> [DebuggerNonUserCode()] public EntityReference OwnerId { get { return Entity.GetAttributeValue<EntityReference>(Fields.OwnerId); } set { Entity.Attributes[Fields.OwnerId] = value; } } /// <summary> /// <para>Unique identifier for the business unit that owns the record</para> /// <para>ReadOnly - Lookup to businessunit</para> /// <para>Owning Business Unit</para> /// </summary> [DebuggerNonUserCode()] public EntityReference OwningBusinessUnit { get { return Entity.GetAttributeValue<EntityReference>(Fields.OwningBusinessUnit); } } /// <summary> /// <para>Unique identifier for the team that owns the record.</para> /// <para>ReadOnly - Lookup to team</para> /// <para>Owning Team</para> /// </summary> [DebuggerNonUserCode()] public EntityReference OwningTeam { get { return Entity.GetAttributeValue<EntityReference>(Fields.OwningTeam); } } /// <summary> /// <para>Unique identifier for the user that owns the record.</para> /// <para>ReadOnly - Lookup to systemuser</para> /// <para>Owning User</para> /// </summary> [DebuggerNonUserCode()] public EntityReference OwningUser { get { return Entity.GetAttributeValue<EntityReference>(Fields.OwningUser); } } /// <summary> /// <para>Status of the ApprovalsTable</para> /// <para>State</para> /// <para>Status</para> /// </summary> [DebuggerNonUserCode()] public Dev.DevKit.Shared.Entities.msdyn_projectapprovalOptionSets.statecode? statecode { get { var value = Entity.GetAttributeValue<OptionSetValue>(Fields.statecode); if (value == null) return null; return (Dev.DevKit.Shared.Entities.msdyn_projectapprovalOptionSets.statecode)value.Value; } set { if (value.HasValue) Entity.Attributes[Fields.statecode] = new OptionSetValue((int)value.Value); else Entity.Attributes[Fields.statecode] = null; } } /// <summary> /// <para>Reason for the status of the ApprovalsTable</para> /// <para>Status</para> /// <para>Status Reason</para> /// </summary> [DebuggerNonUserCode()] public Dev.DevKit.Shared.Entities.msdyn_projectapprovalOptionSets.statuscode? statuscode { get { var value = Entity.GetAttributeValue<OptionSetValue>(Fields.statuscode); if (value == null) return null; return (Dev.DevKit.Shared.Entities.msdyn_projectapprovalOptionSets.statuscode)value.Value; } set { if (value.HasValue) Entity.Attributes[Fields.statuscode] = new OptionSetValue((int)value.Value); else Entity.Attributes[Fields.statuscode] = null; } } /// <summary> /// <para>For internal use only.</para> /// <para>Integer - MinValue: -1 - MaxValue: 2,147,483,647</para> /// <para>Time Zone Rule Version Number</para> /// </summary> [DebuggerNonUserCode()] public int? TimeZoneRuleVersionNumber { get { return Entity.GetAttributeValue<int?>(Fields.TimeZoneRuleVersionNumber); } set { Entity.Attributes[Fields.TimeZoneRuleVersionNumber] = value; } } /// <summary> /// <para>Shows the currency associated with the entity.</para> /// <para>Lookup to transactioncurrency</para> /// <para>Currency</para> /// </summary> [DebuggerNonUserCode()] public EntityReference TransactionCurrencyId { get { return Entity.GetAttributeValue<EntityReference>(Fields.TransactionCurrencyId); } set { Entity.Attributes[Fields.TransactionCurrencyId] = value; } } /// <summary> /// <para>Time zone code that was in use when the record was created.</para> /// <para>Integer - MinValue: -1 - MaxValue: 2,147,483,647</para> /// <para>UTC Conversion Time Zone Code</para> /// </summary> [DebuggerNonUserCode()] public int? UTCConversionTimeZoneCode { get { return Entity.GetAttributeValue<int?>(Fields.UTCConversionTimeZoneCode); } set { Entity.Attributes[Fields.UTCConversionTimeZoneCode] = value; } } /// <summary> /// <para>Version Number</para> /// <para>ReadOnly - BigInt</para> /// <para>Version Number</para> /// </summary> [DebuggerNonUserCode()] public long? VersionNumber { get { return Entity.GetAttributeValue<long?>(Fields.VersionNumber); } } } }
31.746347
111
0.689705
[ "MIT" ]
Kayserheimer/Dynamics-Crm-DevKit
test/v.2.12.31/TestAllEntities/All-DEMO/Dev.DevKit.Shared/Entities/msdyn_projectapproval.generated.cs
30,415
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // As informações gerais sobre um assembly são controladas por // conjunto de atributos. Altere estes valores de atributo para modificar as informações // associada a um assembly. [assembly: AssemblyTitle("ProjetoModeloDDD.Domain")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ProjetoModeloDDD.Domain")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Definir ComVisible como false torna os tipos neste assembly invisíveis // para componentes COM. Caso precise acessar um tipo neste assembly de // COM, defina o atributo ComVisible como true nesse tipo. [assembly: ComVisible(false)] // O GUID a seguir será destinado à ID de typelib se este projeto for exposto para COM [assembly: Guid("38d19d1b-78cf-4073-80ec-977745c7c620")] // As informações da versão de um assembly consistem nos quatro valores a seguir: // // Versão Principal // Versão Secundária // Número da Versão // Revisão // // É possível especificar todos os valores ou usar como padrão os Números de Build e da Revisão // usando o '*' como mostrado abaixo: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.756757
95
0.75523
[ "MIT" ]
murilohpucci/BookStoreDDD
ProjetoModeloDDD.Domain/Properties/AssemblyInfo.cs
1,459
C#
using JetBrains.Annotations; using JsonApiDotNetCore.Queries; namespace JsonApiDotNetCore.QueryStrings { /// <summary> /// Reads the 'filter' query string parameter and produces a set of query constraints from it. /// </summary> [PublicAPI] public interface IFilterQueryStringParameterReader : IQueryStringParameterReader, IQueryConstraintProvider { } }
27.357143
110
0.749347
[ "MIT" ]
3volutionsAG/JsonApiDotNetCore
src/JsonApiDotNetCore/QueryStrings/IFilterQueryStringParameterReader.cs
383
C#
using Common; using System.Windows; namespace IoTEdgeInstaller { public partial class MainWindow : Window { private PageFlow _pageFlow; public MainWindow() { // Uncomment to test localization // System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("de-DE"); Title = Strings.AboutSubtitle; InitializeComponent(); _pageFlow = new PageFlow(_NavigationFrame); _pageFlow.Navigate(typeof(PageProvisionDeviceWithAzure)); } } }
25.25
119
0.615512
[ "MIT" ]
Azure/Industrial-IoT-Edge-Installer
IoTEdgeInstallerApp/MainPage.xaml.cs
608
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/WbemCli.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using System.Runtime.InteropServices; namespace TerraFX.Interop.Windows; /// <include file='WbemContext.xml' path='doc/member[@name="WbemContext"]/*' /> [Guid("674B6698-EE92-11D0-AD71-00C04FD8FDFF")] public partial struct WbemContext { }
35.066667
145
0.764259
[ "MIT" ]
IngmarBitter/terrafx.interop.windows
sources/Interop/Windows/Windows/um/WbemCli/WbemContext.cs
528
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using ILRuntime.CLR.TypeSystem; using ILRuntime.CLR.Method; using ILRuntime.Runtime.Enviorment; using ILRuntime.Runtime.Intepreter; using ILRuntime.Runtime.Stack; using ILRuntime.Reflection; using ILRuntime.CLR.Utils; namespace ILRuntime.Runtime.Generated { unsafe class UnityEngine_UI_DataBindingProperty_Binding { public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app) { BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; MethodBase method; FieldInfo field; Type[] args; Type type = typeof(UnityEngine.UI.DataBindingProperty); args = new Type[]{}; method = type.GetMethod("GetValue", flag, null, args, null); app.RegisterCLRMethodRedirection(method, GetValue_0); field = type.GetField("Property", flag); app.RegisterCLRFieldGetter(field, get_Property_0); app.RegisterCLRFieldSetter(field, set_Property_0); field = type.GetField("PropertyOwner", flag); app.RegisterCLRFieldGetter(field, get_PropertyOwner_1); app.RegisterCLRFieldSetter(field, set_PropertyOwner_1); field = type.GetField("PropertyOwnerKey", flag); app.RegisterCLRFieldGetter(field, get_PropertyOwnerKey_2); app.RegisterCLRFieldSetter(field, set_PropertyOwnerKey_2); field = type.GetField("ConvertMethod", flag); app.RegisterCLRFieldGetter(field, get_ConvertMethod_3); app.RegisterCLRFieldSetter(field, set_ConvertMethod_3); field = type.GetField("PropertyName", flag); app.RegisterCLRFieldGetter(field, get_PropertyName_4); app.RegisterCLRFieldSetter(field, set_PropertyName_4); args = new Type[]{typeof(System.Object), typeof(System.String), typeof(System.String)}; method = type.GetConstructor(flag, null, args, null); app.RegisterCLRMethodRedirection(method, Ctor_0); } static StackObject* GetValue_0(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); UnityEngine.UI.DataBindingProperty instance_of_this_method = (UnityEngine.UI.DataBindingProperty)typeof(UnityEngine.UI.DataBindingProperty).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.GetValue(); object obj_result_of_this_method = result_of_this_method; if(obj_result_of_this_method is CrossBindingAdaptorType) { return ILIntepreter.PushObject(__ret, __mStack, ((CrossBindingAdaptorType)obj_result_of_this_method).ILInstance, true); } return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method, true); } static object get_Property_0(ref object o) { return ((UnityEngine.UI.DataBindingProperty)o).Property; } static void set_Property_0(ref object o, object v) { ((UnityEngine.UI.DataBindingProperty)o).Property = (System.Reflection.PropertyInfo)v; } static object get_PropertyOwner_1(ref object o) { return ((UnityEngine.UI.DataBindingProperty)o).PropertyOwner; } static void set_PropertyOwner_1(ref object o, object v) { ((UnityEngine.UI.DataBindingProperty)o).PropertyOwner = (System.Object)v; } static object get_PropertyOwnerKey_2(ref object o) { return ((UnityEngine.UI.DataBindingProperty)o).PropertyOwnerKey; } static void set_PropertyOwnerKey_2(ref object o, object v) { ((UnityEngine.UI.DataBindingProperty)o).PropertyOwnerKey = (System.String)v; } static object get_ConvertMethod_3(ref object o) { return ((UnityEngine.UI.DataBindingProperty)o).ConvertMethod; } static void set_ConvertMethod_3(ref object o, object v) { ((UnityEngine.UI.DataBindingProperty)o).ConvertMethod = (System.Reflection.MethodInfo)v; } static object get_PropertyName_4(ref object o) { return ((UnityEngine.UI.DataBindingProperty)o).PropertyName; } static void set_PropertyName_4(ref object o, object v) { ((UnityEngine.UI.DataBindingProperty)o).PropertyName = (System.String)v; } static StackObject* Ctor_0(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 3); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.String @rPropName = (System.String)typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); System.String @rPropOwnerKey = (System.String)typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 3); System.Object @rPropOwner = (System.Object)typeof(System.Object).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = new UnityEngine.UI.DataBindingProperty(@rPropOwner, @rPropOwnerKey, @rPropName); return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method); } } }
44.93617
228
0.678662
[ "MIT" ]
JansonC/knight
knight-client/Assets/Game/Script/Generate/ILRuntime/UnityEngine_UI_DataBindingProperty_Binding.cs
6,336
C#
namespace CloudPhoto.Web { using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; public static class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
26.142857
70
0.559199
[ "MIT" ]
chemiliq-git/CloudPhoto
src/Web/CloudPhoto.Web/Program.cs
551
C#
using System; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Azure.Storage.Queues; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace FarmerConnect.Azure.Messaging.StorageQueue { public class StorageQueueConsumer : BackgroundService { private readonly EventSubscriptionManager _subscriptionManager; private readonly MessagingOptions _options; private readonly IServiceProvider _serviceProvider; private readonly ILogger<StorageQueueConsumer> _logger; public StorageQueueConsumer(EventSubscriptionManager subscriptionManager, IOptions<MessagingOptions> options, IServiceProvider serviceProvider, ILogger<StorageQueueConsumer> logger) { _subscriptionManager = subscriptionManager; _options = options.Value; _serviceProvider = serviceProvider; _logger = logger; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { var queue = new QueueClient(_options.ConnectionString, _options.QueueName); await queue.CreateIfNotExistsAsync(cancellationToken: stoppingToken); var waitTime = 100; while (!stoppingToken.IsCancellationRequested) { _logger.LogDebug("Checking for new messages..."); // When a message is found, the runtime waits 100 milliseconds and then checks for another message // When no message is found, it waits about 200 milliseconds before trying again. // After subsequent failed attempts to get a queue message, the wait time continues to increase until it reaches the maximum wait time, which defaults to one minute. // The maximum wait time is configurable via the maxPollingInterval property in the host.json file. var messages = queue.ReceiveMessages(_options.MaxMessages, cancellationToken: stoppingToken).Value; if (messages.Length > 0) { _logger.LogDebug("We have some new messages, let's process them"); waitTime = 100; foreach (var message in messages) { try { var jsonDocument = JsonDocument.Parse(message.Body); var eventName = jsonDocument.RootElement.GetProperty("eventName").GetString(); var eventType = _subscriptionManager.GetEventTypeByName(eventName); var messageData = jsonDocument.RootElement.GetProperty("data").GetString(); var integrationEvent = JsonSerializer.Deserialize(messageData, eventType, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }); using (var scope = _serviceProvider.CreateScope()) { var eventHandlerTypes = _subscriptionManager.GetHandlersForEvent(eventName); foreach (var handler in eventHandlerTypes) { var eventHandler = scope.ServiceProvider.GetService(handler); if (eventHandler == null) { _logger.LogWarning("Unable to find registered service for: {EventHandler}", handler.Name); continue; } var concreteType = (IIntegrationEventHandler)scope.ServiceProvider.GetService(handler); await concreteType.Handle(integrationEvent).ConfigureAwait(false); } } } catch (Exception ex) { _logger.LogError(ex, "Unable to process message: {MessageBody}", message.Body); } finally { await queue.DeleteMessageAsync(message.MessageId, message.PopReceipt, stoppingToken); } await Task.Delay(100, stoppingToken); } } else { if (waitTime < _options.MaxPollingInterval) { waitTime *= 2; } _logger.LogDebug("No new message was received. Increasing the polling wait timer to {WaitTimeInMs}ms", waitTime); await Task.Delay(waitTime, stoppingToken); } } } } }
47.037736
189
0.55716
[ "Apache-2.0" ]
farmerconnect/farmerconnect-azure
src/FarmerConnect.Azure.Messaging/StorageQueue/StorageQueueConsumer.cs
4,988
C#
// ----------------------------------------------------------------------------------------- // <copyright file="TestHelper.cs" company="Microsoft"> // Copyright 2013 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // ----------------------------------------------------------------------------------------- using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using System; using System.IO; using System.Net; using System.Threading.Tasks; using Windows.Storage.Streams; namespace Microsoft.WindowsAzure.Storage { public partial class TestHelper { /// <summary> /// Compares the streams from the current position to the end. /// </summary> internal static async Task AssertStreamsAreEqualAsync(IInputStream src, IInputStream dst) { Stream srcAsStream = src.AsStreamForRead(); Stream dstAsStream = dst.AsStreamForRead(); byte[] srcBuffer = new byte[64 * 1024]; int srcRead; byte[] dstBuffer = new byte[64 * 1024]; int dstRead; do { srcRead = await srcAsStream.ReadAsync(srcBuffer, 0, srcBuffer.Length); dstRead = await dstAsStream.ReadAsync(dstBuffer, 0, dstBuffer.Length); Assert.AreEqual(srcRead, dstRead); for (int i = 0; i < srcRead; i++) { Assert.AreEqual(srcBuffer[i], dstBuffer[i]); } } while (srcRead > 0); } /// <summary> /// Compares the streams from the current position to the end. /// </summary> internal static async Task AssertStreamsAreEqualAsync(Stream src, Stream dst) { byte[] srcBuffer = new byte[64 * 1024]; int srcRead; byte[] dstBuffer = new byte[64 * 1024]; int dstRead; do { srcRead = await src.ReadAsync(srcBuffer, 0, srcBuffer.Length); dstRead = await dst.ReadAsync(dstBuffer, 0, dstBuffer.Length); Assert.AreEqual(srcRead, dstRead); for (int i = 0; i < srcRead; i++) { Assert.AreEqual(srcBuffer[i], dstBuffer[i]); } } while (srcRead > 0); } /// <summary> /// Runs a given operation that is expected to throw an exception. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="operation"></param> /// <param name="operationDescription"></param> internal static async Task<T> ExpectedExceptionAsync<T>(Func<Task> operation, string operationDescription) where T : Exception { try { await operation(); } catch (T e) { return e; } catch (Exception ex) { T e = ex as T; // Test framework changes the value under debugger if (e != null) { return e; } Assert.Fail("Invalid exception {0} for operation: {1}", ex.GetType(), operationDescription); } Assert.Fail("No exception received while expecting {0}: {1}", typeof(T).ToString(), operationDescription); return null; } /// <summary> /// Runs a given operation that is expected to throw an exception. /// </summary> /// <param name="operation"></param> /// <param name="operationDescription"></param> /// <param name="expectedStatusCode"></param> internal static async Task ExpectedExceptionAsync(Func<Task> operation, OperationContext operationContext, string operationDescription, HttpStatusCode expectedStatusCode, string requestErrorCode = null) { try { await operation(); } catch (StorageException storageException) { Assert.AreEqual((int)expectedStatusCode, storageException.RequestInformation.HttpStatusCode, "Http status code is unexpected."); if (!string.IsNullOrEmpty(requestErrorCode)) { Assert.IsNotNull(storageException.RequestInformation.ExtendedErrorInformation); Assert.AreEqual(requestErrorCode, storageException.RequestInformation.ExtendedErrorInformation.ErrorCode); } return; } catch (Exception) { Assert.AreEqual((int)expectedStatusCode, operationContext.LastResult.HttpStatusCode, "Http status code is unexpected."); if (!string.IsNullOrEmpty(requestErrorCode)) { Assert.IsNotNull(operationContext.LastResult.ExtendedErrorInformation); Assert.AreEqual(requestErrorCode, operationContext.LastResult.ExtendedErrorInformation.ErrorCode); } return; } Assert.Fail("No exception received while expecting {0}: {1}", expectedStatusCode, operationDescription); } } }
37.535484
210
0.552252
[ "Apache-2.0" ]
am11/azure-storage-net
Test/WindowsRuntime/TestHelper.cs
5,820
C#
using System; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using VRage.Plugins; using VRage.Scripting; namespace TelnetPlugin { public class TelnetPlugin : IPlugin { public void Dispose() { } private static string LOG_FILE = "c:\\users\\jarno\\documents\\telnetplugin.txt"; internal static void Log(string msg) { System.IO.File.AppendAllText(LOG_FILE, msg + "\n"); } private static void RegisterPluginModAPI() { var name = Assembly.GetExecutingAssembly().GetName().Name; var path = new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath; Log($"Registering assembly {name} @ {path}"); MyScriptCompiler.Static.AddReferencedAssemblies(path); using (var handle = MyScriptCompiler.Static.Whitelist.OpenBatch()) { handle.AllowNamespaceOfTypes(MyWhitelistTarget.ModApi, typeof(ModAPI.Telnet)); } AppDomain.CurrentDomain.AssemblyResolve += (object sender, ResolveEventArgs args) => { if (args.Name.StartsWith(name)) { return Assembly.GetExecutingAssembly(); } else return null; }; } private TelnetServer server; private static MySynchronizationContext mySynchronizationContext; public static SynchronizationContext synchronizationContext => mySynchronizationContext; public static MySynchronizationContext.UsingSynchronizationContext UsingSC() { SynchronizationContext sc = synchronizationContext; if (sc == null) sc = SynchronizationContext.Current; return new MySynchronizationContext.UsingSynchronizationContext(sc); } public void Init(object gameInstance) { System.IO.File.WriteAllText(LOG_FILE, "Init!\n"); RegisterPluginModAPI(); mySynchronizationContext = new MySynchronizationContext(); server = TelnetServer.Create(57888); server.Accept(() => { server.Write("Type in your name: "); server.ReadLine(name => { server.WriteLine($"Hello {name}"); server.Close(); }); }); } public void Update() { using (MySynchronizationContext.Using()) { mySynchronizationContext.Run(); } } } }
29.888889
96
0.580669
[ "MIT" ]
jarno-r/SETelnet
TelnetPlugin/TelnetPlugin.cs
2,692
C#
using System; using System.Security.Cryptography; using System.Collections.Generic; using System.Linq; using RSAExtensions; namespace DwFramework.Core.Encrypt { public static class RSA { /// <summary> /// 填充位数 /// </summary> private static readonly Dictionary<RSAEncryptionPadding, int> PaddingLength = new Dictionary<RSAEncryptionPadding, int>() { [RSAEncryptionPadding.Pkcs1] = 11, [RSAEncryptionPadding.OaepSHA1] = 42, [RSAEncryptionPadding.OaepSHA256] = 66, [RSAEncryptionPadding.OaepSHA384] = 98, [RSAEncryptionPadding.OaepSHA512] = 130 }; /// <summary> /// 生成RSA密钥对 /// </summary> /// <param name="type"></param> /// <param name="size"></param> /// <param name="isPem"></param> /// <returns></returns> public static (string PrivateKey, string PublicKey) GenerateKeyPair(RSAKeyType type = RSAKeyType.Pkcs1, int size = 1024, bool isPem = false) { using var rsa = System.Security.Cryptography.RSA.Create(size); return (rsa.ExportPrivateKey(type, isPem), rsa.ExportPublicKey(type, isPem)); } /// <summary> /// 加密 /// </summary> /// <param name="rsa"></param> /// <param name="data"></param> /// <param name="padding"></param> /// <returns></returns> private static byte[] Encrypt(System.Security.Cryptography.RSA rsa, byte[] data, RSAEncryptionPadding padding = null) { padding ??= RSAEncryptionPadding.Pkcs1; byte[] result; var maxLength = rsa.KeySize / 8 - PaddingLength[padding]; // 长数据分割 if (maxLength < data.Length) { var pointer = 0; var resBytes = new List<byte>(); while (pointer < data.Length) { var length = pointer + maxLength > data.Length ? data.Length - pointer : maxLength; resBytes.AddRange(rsa.Encrypt(data.Skip(pointer).Take(length).ToArray(), padding)); pointer += maxLength; } result = resBytes.ToArray(); } else result = rsa.Encrypt(data, padding); return result; } /// <summary> /// 解密 /// </summary> /// <param name="rsa"></param> /// <param name="encryptedData"></param> /// <param name="padding"></param> /// <returns></returns> private static byte[] Decrypt(System.Security.Cryptography.RSA rsa, byte[] encryptedData, RSAEncryptionPadding padding = null) { padding ??= RSAEncryptionPadding.Pkcs1; byte[] result; var step = rsa.KeySize / 8; // 长数据分割 if (step != encryptedData.Length) { var pointer = 0; var resBytes = new List<byte>(); while (pointer < encryptedData.Length) { resBytes.AddRange(rsa.Decrypt(encryptedData.Skip(pointer).Take(step).ToArray(), padding)); pointer += step; } result = resBytes.ToArray(); } else result = rsa.Decrypt(encryptedData, padding); return result; } /// <summary> /// 公钥加密 /// </summary> /// <param name="data"></param> /// <param name="type"></param> /// <param name="publicKey"></param> /// <param name="isPem"></param> /// <param name="padding"></param> /// <returns></returns> public static byte[] EncryptWithPublicKey(byte[] data, RSAKeyType type, string publicKey, bool isPem = false, RSAEncryptionPadding padding = null) { using var rsa = System.Security.Cryptography.RSA.Create(); rsa.ImportPublicKey(type, publicKey, isPem); return Encrypt(rsa, data, padding); } /// <summary> /// 私钥加密 /// </summary> /// <param name="data"></param> /// <param name="type"></param> /// <param name="privateKey"></param> /// <param name="isPem"></param> /// <param name="padding"></param> /// <returns></returns> public static byte[] EncryptWithPrivateKey(byte[] data, RSAKeyType type, string privateKey, bool isPem = false, RSAEncryptionPadding padding = null) { using var rsa = System.Security.Cryptography.RSA.Create(); rsa.ImportPrivateKey(type, privateKey, isPem); return Encrypt(rsa, data, padding); } /// <summary> /// 私钥解密 /// </summary> /// <param name="encryptedData"></param> /// <param name="type"></param> /// <param name="privateKey"></param> /// <param name="isPem"></param> /// <param name="padding"></param> /// <returns></returns> public static byte[] Decrypt(byte[] encryptedData, RSAKeyType type, string privateKey, bool isPem = false, RSAEncryptionPadding padding = null) { using var rsa = System.Security.Cryptography.RSA.Create(); rsa.ImportPrivateKey(type, privateKey, isPem); return Decrypt(rsa, encryptedData, padding); } } }
38.297872
156
0.537593
[ "MIT" ]
DwGoingJiang/DwFramework
src/DwFramework.Core/Plugins/Encrypt/RSA.cs
5,470
C#
using UnityEngine; namespace Expanse.Motion { /// <summary> /// Motion that moves an AudioSource volume value towards a target volume. /// </summary> public class AudioSourceVolumeMotion : FloatMotion { public AudioSource AudioSource { get; private set; } public AudioSourceVolumeMotion() : base(1, null, null) { } public AudioSourceVolumeMotion(float duration) : base(duration, null, null) { } public AudioSourceVolumeMotion(float duration, CallBackRelay cbr) : base(duration, cbr, null) { } public AudioSourceVolumeMotion(float duration, MonoBehaviour attachedMonobehaviour) : base(duration, null, attachedMonobehaviour) { } public AudioSourceVolumeMotion(float duration, CallBackRelay cbr, MonoBehaviour attachedMonobehaviour) : base(duration, cbr, attachedMonobehaviour) { } public void SetParameters(AudioSource audioSource, float targetVolume) { AudioSource = audioSource; SetValues(() => this.AudioSource.volume, targetVolume); } public void SetParameters(AudioSource audioSource, float startVolume, float targetVolume) { AudioSource = audioSource; SetValues(startVolume, targetVolume); } protected override void OnValueChanged() { if (AudioSource != null) { AudioSource.volume = CurrentValue; } } } }
37.410256
159
0.656614
[ "MIT" ]
AikenParker/Expanse
Motion/ComponentMotion/AudioSourceVolumeMotion.cs
1,461
C#
// <copyright file="IAuthenticationResultExpandables.cs" company="Stormpath, Inc."> // Copyright (c) 2016 Stormpath, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using Stormpath.SDK.Account; namespace Stormpath.SDK.Linq.Expandables { /// <summary> /// Represents resources that can be expanded from an <see cref="Auth.IAuthenticationResult"/>. /// </summary> public interface IAuthenticationResultExpandables { /// <summary> /// Expands the <c>account</c> resource. /// </summary> /// <returns>Not applicable.</returns> IAccount GetAccount(); } }
34.818182
99
0.694517
[ "Apache-2.0" ]
stormpath/stormpath-sdk-csharp
src/Stormpath.SDK.Abstractions/Linq/Expandables/IAuthenticationResultExpandables.cs
1,151
C#
using Moq; using NUnit.Framework; using RabbitMQ.Client; using System; using System.Collections.Generic; using System.Text; using TacitusLogger.Builders; using TacitusLogger.Destinations.RabbitMq; using TacitusLogger.Serializers; namespace TacitusLogger.Destinations.RabbitMq.IntegrationTests { [TestFixture] public class BuilderTests { RabbitMqTestManager _rabbitMqTestManager; [TearDown] public void TearDown() { _rabbitMqTestManager.CleanUp(); } [SetUp] public void SetUp() { _rabbitMqTestManager = new RabbitMqTestManager(); } [Test] public void LoggerBuilder_With_One_LogGroup_Containing_One_RabbitMq_Destination_With_Custom_Components() { // Arrange var connection = new Mock<IConnection>().Object; var publicationAddressProvider = new Mock<IPublicationAddressProvider>().Object; var logSerializer = new Mock<ILogSerializer>().Object; var messagePublisher = new Mock<IMessagePublisher>().Object; // Act Logger logger = (Logger)LoggerBuilder.Logger().NewLogGroup("group1").ForAllLogs() .RabbitMq() .WithConnection(connection) .WithAddress(publicationAddressProvider) .WithLogSerializer(logSerializer) .WithPublisher(messagePublisher) .Add() .BuildLogger(); // Assert var logGroup = (LogGroup)logger.GetLogGroup("group1"); Assert.AreEqual(1, logGroup.LogDestinations.Count); Assert.IsInstanceOf<RabbitMqDestination>(logGroup.LogDestinations[0]); var rabbitMqDestination = (RabbitMqDestination)logGroup.LogDestinations[0]; // Connection asserts. Assert.AreEqual(connection, rabbitMqDestination.RabbitMqConnection); // Publication address provider asserts. Assert.AreEqual(publicationAddressProvider, rabbitMqDestination.PublicationAddressProvider); // Log serializer asserts. Assert.AreEqual(logSerializer, rabbitMqDestination.LogSerializer); // Message publisher asserts. Assert.AreEqual(messagePublisher, rabbitMqDestination.MessagePublisher); } [Test] public void LoggerBuilder_With_RabbitMq_Destination_When_Connection_Is_Not_Specified_Throws_InvalidOperationException() { // Arrange var publicationAddressProvider = new Mock<IPublicationAddressProvider>().Object; var logSerializer = new Mock<ILogSerializer>().Object; var messagePublisher = new Mock<IMessagePublisher>().Object; Assert.Catch<InvalidOperationException>(() => { // Act Logger logger = (Logger)LoggerBuilder.Logger().NewLogGroup("group1").ForAllLogs() .RabbitMq() .WithAddress(publicationAddressProvider) .WithLogSerializer(logSerializer) .WithPublisher(messagePublisher) .Add() .BuildLogger(); }); } [Test] public void LoggerBuilder_With_RabbitMq_Destination_When_Publication_Address_Provider_Is_Not_Specified_Throws_InvalidOperationException() { // Arrange var connection = new Mock<IConnection>().Object; var logSerializer = new Mock<ILogSerializer>().Object; var messagePublisher = new Mock<IMessagePublisher>().Object; Assert.Catch<InvalidOperationException>(() => { // Act Logger logger = (Logger)LoggerBuilder.Logger().NewLogGroup("group1").ForAllLogs() .RabbitMq() .WithConnection(connection) .WithLogSerializer(logSerializer) .WithPublisher(messagePublisher) .Add() .BuildLogger(); }); } [Test] public void LoggerBuilder_With_RabbitMq_Destination_When_Log_Serializer_Is_Not_Specified_Sets_Default_Log_Serializer() { // Arrange var connection = new Mock<IConnection>().Object; var publicationAddressProvider = new Mock<IPublicationAddressProvider>().Object; var messagePublisher = new Mock<IMessagePublisher>().Object; // Act Logger logger = (Logger)LoggerBuilder.Logger().NewLogGroup("group1").ForAllLogs() .RabbitMq() .WithConnection(connection) .WithAddress(publicationAddressProvider) .WithPublisher(messagePublisher) .Add() .BuildLogger(); // Assert var logGroup = (LogGroup)logger.GetLogGroup("group1"); Assert.AreEqual(1, logGroup.LogDestinations.Count); Assert.IsInstanceOf<RabbitMqDestination>(logGroup.LogDestinations[0]); var rabbitMqDestination = (RabbitMqDestination)logGroup.LogDestinations[0]; // Log serializer asserts. Assert.IsInstanceOf<JsonLogSerializer>(rabbitMqDestination.LogSerializer); var logSerializer = (JsonLogSerializer)rabbitMqDestination.LogSerializer; Assert.AreEqual(JsonLogSerializer.DefaultConverter, logSerializer.Converter); Assert.AreEqual(JsonLogSerializer.DefaultJsonSerializerSettings, logSerializer.JsonSerializerSettings); } [Test] public void LoggerBuilder_With_RabbitMq_Destination_When_Message_Publisher_Not_Specified_Sets_Default_Message_Publisher() { // Arrange var connection = new Mock<IConnection>().Object; var publicationAddressProvider = new Mock<IPublicationAddressProvider>().Object; var logSerializer = new Mock<ILogSerializer>().Object; // Act Logger logger = (Logger)LoggerBuilder.Logger().NewLogGroup("group1").ForAllLogs() .RabbitMq() .WithConnection(connection) .WithAddress(publicationAddressProvider) .WithLogSerializer(logSerializer) .Add() .BuildLogger(); // Assert var logGroup = (LogGroup)logger.GetLogGroup("group1"); Assert.AreEqual(1, logGroup.LogDestinations.Count); Assert.IsInstanceOf<RabbitMqDestination>(logGroup.LogDestinations[0]); var rabbitMqDestination = (RabbitMqDestination)logGroup.LogDestinations[0]; // Message publisher asserts. Assert.IsInstanceOf<BasicMessagePublisher>(rabbitMqDestination.MessagePublisher); var messagePublisher = (BasicMessagePublisher)rabbitMqDestination.MessagePublisher; Assert.AreEqual(null, messagePublisher.BasicProperties); } [Test] public void LoggerBuilder_With_One_LogGroup_Containing_One_RabbitMq_Destination_In_It() { var connection = _rabbitMqTestManager.Connection; string exchangeName = "exchangeName"; string exchangeType = "exchangeType"; string routingKey = "routingKey"; // Act Logger logger = (Logger)LoggerBuilder.Logger().NewLogGroup("group1").ForAllLogs() .RabbitMq() .WithConnection(connection) .WithAddress(exchangeName, exchangeType, routingKey) .WithSimpleTemplateLogText() .Add() .BuildLogger(); // Assert var logGroup = (LogGroup)logger.GetLogGroup("group1"); Assert.AreEqual(1, logGroup.LogDestinations.Count); Assert.IsInstanceOf<RabbitMqDestination>(logGroup.LogDestinations[0]); var rabbitMqDestination = (RabbitMqDestination)logGroup.LogDestinations[0]; // Connection asserts. Assert.AreEqual(connection, rabbitMqDestination.RabbitMqConnection); // Publication address provider asserts. Assert.IsInstanceOf<DirectPublicationAddressProvider>(rabbitMqDestination.PublicationAddressProvider); var publicationAddressProvider = (DirectPublicationAddressProvider)rabbitMqDestination.PublicationAddressProvider; Assert.AreEqual(exchangeName, publicationAddressProvider.PublicationAddress.ExchangeName); Assert.AreEqual(exchangeType, publicationAddressProvider.PublicationAddress.ExchangeType); Assert.AreEqual(routingKey, publicationAddressProvider.PublicationAddress.RoutingKey); // Log serializer asserts. Assert.IsInstanceOf<SimpleTemplateLogSerializer>(rabbitMqDestination.LogSerializer); var logSerializer = (SimpleTemplateLogSerializer)rabbitMqDestination.LogSerializer; Assert.AreEqual(SimpleTemplateLogSerializer.DefaultTemplate, logSerializer.Template); // Message publisher asserts. Assert.IsInstanceOf<BasicMessagePublisher>(rabbitMqDestination.MessagePublisher); var messagePublisher = (BasicMessagePublisher)rabbitMqDestination.MessagePublisher; Assert.AreEqual(null, messagePublisher.BasicProperties); } } }
60.035176
145
0.506738
[ "Apache-2.0" ]
khanlarmammadov/TacitusLogger.Destinations.RabbitMq
src/TacitusLogger.Destinations.RabbitMq.IntegrationTests/BuilderTests.cs
11,949
C#