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 |
|---|---|---|---|---|---|---|---|---|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Rakuten.Test.Web.UserService {
using System.Runtime.Serialization;
using System;
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="ServiceResultOfUser", Namespace="http://tempuri.org/")]
[System.SerializableAttribute()]
public partial class ServiceResultOfUser : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged {
[System.NonSerializedAttribute()]
private System.Runtime.Serialization.ExtensionDataObject extensionDataField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private Rakuten.Test.Web.UserService.User DataField;
private bool HasErrorField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private string ErrorMessageField;
[global::System.ComponentModel.BrowsableAttribute(false)]
public System.Runtime.Serialization.ExtensionDataObject ExtensionData {
get {
return this.extensionDataField;
}
set {
this.extensionDataField = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false)]
public Rakuten.Test.Web.UserService.User Data {
get {
return this.DataField;
}
set {
if ((object.ReferenceEquals(this.DataField, value) != true)) {
this.DataField = value;
this.RaisePropertyChanged("Data");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute(IsRequired=true)]
public bool HasError {
get {
return this.HasErrorField;
}
set {
if ((this.HasErrorField.Equals(value) != true)) {
this.HasErrorField = value;
this.RaisePropertyChanged("HasError");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=2)]
public string ErrorMessage {
get {
return this.ErrorMessageField;
}
set {
if ((object.ReferenceEquals(this.ErrorMessageField, value) != true)) {
this.ErrorMessageField = value;
this.RaisePropertyChanged("ErrorMessage");
}
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName) {
System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null)) {
propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="User", Namespace="http://tempuri.org/")]
[System.SerializableAttribute()]
public partial class User : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged {
[System.NonSerializedAttribute()]
private System.Runtime.Serialization.ExtensionDataObject extensionDataField;
private int IdField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private string FirstNameField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private string LastNameField;
private Rakuten.Test.Web.UserService.GenderType GenderField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private string DocumentIdField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private string RgField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private string EmailField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private string PasswordField;
private bool IntegratedField;
private System.DateTime DateCreationField;
private System.DateTime DateModifiedField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private Rakuten.Test.Web.UserService.AddressData[] AddressesField;
[global::System.ComponentModel.BrowsableAttribute(false)]
public System.Runtime.Serialization.ExtensionDataObject ExtensionData {
get {
return this.extensionDataField;
}
set {
this.extensionDataField = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute(IsRequired=true)]
public int Id {
get {
return this.IdField;
}
set {
if ((this.IdField.Equals(value) != true)) {
this.IdField = value;
this.RaisePropertyChanged("Id");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=1)]
public string FirstName {
get {
return this.FirstNameField;
}
set {
if ((object.ReferenceEquals(this.FirstNameField, value) != true)) {
this.FirstNameField = value;
this.RaisePropertyChanged("FirstName");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=2)]
public string LastName {
get {
return this.LastNameField;
}
set {
if ((object.ReferenceEquals(this.LastNameField, value) != true)) {
this.LastNameField = value;
this.RaisePropertyChanged("LastName");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute(IsRequired=true, Order=3)]
public Rakuten.Test.Web.UserService.GenderType Gender {
get {
return this.GenderField;
}
set {
if ((this.GenderField.Equals(value) != true)) {
this.GenderField = value;
this.RaisePropertyChanged("Gender");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=4)]
public string DocumentId {
get {
return this.DocumentIdField;
}
set {
if ((object.ReferenceEquals(this.DocumentIdField, value) != true)) {
this.DocumentIdField = value;
this.RaisePropertyChanged("DocumentId");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=5)]
public string Rg {
get {
return this.RgField;
}
set {
if ((object.ReferenceEquals(this.RgField, value) != true)) {
this.RgField = value;
this.RaisePropertyChanged("Rg");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=6)]
public string Email {
get {
return this.EmailField;
}
set {
if ((object.ReferenceEquals(this.EmailField, value) != true)) {
this.EmailField = value;
this.RaisePropertyChanged("Email");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=7)]
public string Password {
get {
return this.PasswordField;
}
set {
if ((object.ReferenceEquals(this.PasswordField, value) != true)) {
this.PasswordField = value;
this.RaisePropertyChanged("Password");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute(IsRequired=true, Order=8)]
public bool Integrated {
get {
return this.IntegratedField;
}
set {
if ((this.IntegratedField.Equals(value) != true)) {
this.IntegratedField = value;
this.RaisePropertyChanged("Integrated");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute(IsRequired=true, Order=9)]
public System.DateTime DateCreation {
get {
return this.DateCreationField;
}
set {
if ((this.DateCreationField.Equals(value) != true)) {
this.DateCreationField = value;
this.RaisePropertyChanged("DateCreation");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute(IsRequired=true, Order=10)]
public System.DateTime DateModified {
get {
return this.DateModifiedField;
}
set {
if ((this.DateModifiedField.Equals(value) != true)) {
this.DateModifiedField = value;
this.RaisePropertyChanged("DateModified");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=11)]
public Rakuten.Test.Web.UserService.AddressData[] Addresses {
get {
return this.AddressesField;
}
set {
if ((object.ReferenceEquals(this.AddressesField, value) != true)) {
this.AddressesField = value;
this.RaisePropertyChanged("Addresses");
}
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName) {
System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null)) {
propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="GenderType", Namespace="http://tempuri.org/")]
public enum GenderType : int {
[System.Runtime.Serialization.EnumMemberAttribute()]
Male = 0,
[System.Runtime.Serialization.EnumMemberAttribute()]
Female = 1,
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="AddressData", Namespace="http://tempuri.org/")]
[System.SerializableAttribute()]
public partial class AddressData : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged {
[System.NonSerializedAttribute()]
private System.Runtime.Serialization.ExtensionDataObject extensionDataField;
private int IdField;
private int UserIdField;
private Rakuten.Test.Web.UserService.AddressType TypeField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private string ZipCodeField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private string AddressField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private string DistrictField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private string CityField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private string StateField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private string CountryField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private string PhoneNumberField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private string CellphoneField;
private System.DateTime DateCreationField;
private System.DateTime DateModifiedField;
[global::System.ComponentModel.BrowsableAttribute(false)]
public System.Runtime.Serialization.ExtensionDataObject ExtensionData {
get {
return this.extensionDataField;
}
set {
this.extensionDataField = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute(IsRequired=true)]
public int Id {
get {
return this.IdField;
}
set {
if ((this.IdField.Equals(value) != true)) {
this.IdField = value;
this.RaisePropertyChanged("Id");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute(IsRequired=true)]
public int UserId {
get {
return this.UserIdField;
}
set {
if ((this.UserIdField.Equals(value) != true)) {
this.UserIdField = value;
this.RaisePropertyChanged("UserId");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute(IsRequired=true, Order=2)]
public Rakuten.Test.Web.UserService.AddressType Type {
get {
return this.TypeField;
}
set {
if ((this.TypeField.Equals(value) != true)) {
this.TypeField = value;
this.RaisePropertyChanged("Type");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=3)]
public string ZipCode {
get {
return this.ZipCodeField;
}
set {
if ((object.ReferenceEquals(this.ZipCodeField, value) != true)) {
this.ZipCodeField = value;
this.RaisePropertyChanged("ZipCode");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=4)]
public string Address {
get {
return this.AddressField;
}
set {
if ((object.ReferenceEquals(this.AddressField, value) != true)) {
this.AddressField = value;
this.RaisePropertyChanged("Address");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=5)]
public string District {
get {
return this.DistrictField;
}
set {
if ((object.ReferenceEquals(this.DistrictField, value) != true)) {
this.DistrictField = value;
this.RaisePropertyChanged("District");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=6)]
public string City {
get {
return this.CityField;
}
set {
if ((object.ReferenceEquals(this.CityField, value) != true)) {
this.CityField = value;
this.RaisePropertyChanged("City");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=7)]
public string State {
get {
return this.StateField;
}
set {
if ((object.ReferenceEquals(this.StateField, value) != true)) {
this.StateField = value;
this.RaisePropertyChanged("State");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=8)]
public string Country {
get {
return this.CountryField;
}
set {
if ((object.ReferenceEquals(this.CountryField, value) != true)) {
this.CountryField = value;
this.RaisePropertyChanged("Country");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=9)]
public string PhoneNumber {
get {
return this.PhoneNumberField;
}
set {
if ((object.ReferenceEquals(this.PhoneNumberField, value) != true)) {
this.PhoneNumberField = value;
this.RaisePropertyChanged("PhoneNumber");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=10)]
public string Cellphone {
get {
return this.CellphoneField;
}
set {
if ((object.ReferenceEquals(this.CellphoneField, value) != true)) {
this.CellphoneField = value;
this.RaisePropertyChanged("Cellphone");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute(IsRequired=true, Order=11)]
public System.DateTime DateCreation {
get {
return this.DateCreationField;
}
set {
if ((this.DateCreationField.Equals(value) != true)) {
this.DateCreationField = value;
this.RaisePropertyChanged("DateCreation");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute(IsRequired=true, Order=12)]
public System.DateTime DateModified {
get {
return this.DateModifiedField;
}
set {
if ((this.DateModifiedField.Equals(value) != true)) {
this.DateModifiedField = value;
this.RaisePropertyChanged("DateModified");
}
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName) {
System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null)) {
propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="AddressType", Namespace="http://tempuri.org/")]
public enum AddressType : int {
[System.Runtime.Serialization.EnumMemberAttribute()]
Home = 0,
[System.Runtime.Serialization.EnumMemberAttribute()]
Work = 1,
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="ServiceResultOfListOfUser", Namespace="http://tempuri.org/")]
[System.SerializableAttribute()]
public partial class ServiceResultOfListOfUser : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged {
[System.NonSerializedAttribute()]
private System.Runtime.Serialization.ExtensionDataObject extensionDataField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private Rakuten.Test.Web.UserService.User[] DataField;
private bool HasErrorField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private string ErrorMessageField;
[global::System.ComponentModel.BrowsableAttribute(false)]
public System.Runtime.Serialization.ExtensionDataObject ExtensionData {
get {
return this.extensionDataField;
}
set {
this.extensionDataField = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false)]
public Rakuten.Test.Web.UserService.User[] Data {
get {
return this.DataField;
}
set {
if ((object.ReferenceEquals(this.DataField, value) != true)) {
this.DataField = value;
this.RaisePropertyChanged("Data");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute(IsRequired=true)]
public bool HasError {
get {
return this.HasErrorField;
}
set {
if ((this.HasErrorField.Equals(value) != true)) {
this.HasErrorField = value;
this.RaisePropertyChanged("HasError");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=2)]
public string ErrorMessage {
get {
return this.ErrorMessageField;
}
set {
if ((object.ReferenceEquals(this.ErrorMessageField, value) != true)) {
this.ErrorMessageField = value;
this.RaisePropertyChanged("ErrorMessage");
}
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName) {
System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null)) {
propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="ServiceResultOfServiceResponse", Namespace="http://tempuri.org/")]
[System.SerializableAttribute()]
public partial class ServiceResultOfServiceResponse : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged {
[System.NonSerializedAttribute()]
private System.Runtime.Serialization.ExtensionDataObject extensionDataField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private Rakuten.Test.Web.UserService.ServiceResponse DataField;
private bool HasErrorField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private string ErrorMessageField;
[global::System.ComponentModel.BrowsableAttribute(false)]
public System.Runtime.Serialization.ExtensionDataObject ExtensionData {
get {
return this.extensionDataField;
}
set {
this.extensionDataField = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false)]
public Rakuten.Test.Web.UserService.ServiceResponse Data {
get {
return this.DataField;
}
set {
if ((object.ReferenceEquals(this.DataField, value) != true)) {
this.DataField = value;
this.RaisePropertyChanged("Data");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute(IsRequired=true)]
public bool HasError {
get {
return this.HasErrorField;
}
set {
if ((this.HasErrorField.Equals(value) != true)) {
this.HasErrorField = value;
this.RaisePropertyChanged("HasError");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=2)]
public string ErrorMessage {
get {
return this.ErrorMessageField;
}
set {
if ((object.ReferenceEquals(this.ErrorMessageField, value) != true)) {
this.ErrorMessageField = value;
this.RaisePropertyChanged("ErrorMessage");
}
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName) {
System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null)) {
propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="ServiceResponse", Namespace="http://tempuri.org/")]
[System.SerializableAttribute()]
public partial class ServiceResponse : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged {
[System.NonSerializedAttribute()]
private System.Runtime.Serialization.ExtensionDataObject extensionDataField;
private Rakuten.Test.Web.UserService.ServiceResponseStatus StatusField;
[global::System.ComponentModel.BrowsableAttribute(false)]
public System.Runtime.Serialization.ExtensionDataObject ExtensionData {
get {
return this.extensionDataField;
}
set {
this.extensionDataField = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute(IsRequired=true)]
public Rakuten.Test.Web.UserService.ServiceResponseStatus Status {
get {
return this.StatusField;
}
set {
if ((this.StatusField.Equals(value) != true)) {
this.StatusField = value;
this.RaisePropertyChanged("Status");
}
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName) {
System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null)) {
propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="ServiceResponseStatus", Namespace="http://tempuri.org/")]
public enum ServiceResponseStatus : int {
[System.Runtime.Serialization.EnumMemberAttribute()]
No = 0,
[System.Runtime.Serialization.EnumMemberAttribute()]
Yes = 1,
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(ConfigurationName="UserService.UserSoap")]
public interface UserSoap {
// CODEGEN: Generating message contract since element name GetUserResult from namespace http://tempuri.org/ is not marked nillable
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/GetUser", ReplyAction="*")]
Rakuten.Test.Web.UserService.GetUserResponse GetUser(Rakuten.Test.Web.UserService.GetUserRequest request);
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/GetUser", ReplyAction="*")]
System.Threading.Tasks.Task<Rakuten.Test.Web.UserService.GetUserResponse> GetUserAsync(Rakuten.Test.Web.UserService.GetUserRequest request);
// CODEGEN: Generating message contract since element name GetUsersResult from namespace http://tempuri.org/ is not marked nillable
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/GetUsers", ReplyAction="*")]
Rakuten.Test.Web.UserService.GetUsersResponse GetUsers(Rakuten.Test.Web.UserService.GetUsersRequest request);
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/GetUsers", ReplyAction="*")]
System.Threading.Tasks.Task<Rakuten.Test.Web.UserService.GetUsersResponse> GetUsersAsync(Rakuten.Test.Web.UserService.GetUsersRequest request);
// CODEGEN: Generating message contract since element name user from namespace http://tempuri.org/ is not marked nillable
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/AddUser", ReplyAction="*")]
Rakuten.Test.Web.UserService.AddUserResponse AddUser(Rakuten.Test.Web.UserService.AddUserRequest request);
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/AddUser", ReplyAction="*")]
System.Threading.Tasks.Task<Rakuten.Test.Web.UserService.AddUserResponse> AddUserAsync(Rakuten.Test.Web.UserService.AddUserRequest request);
// CODEGEN: Generating message contract since element name user from namespace http://tempuri.org/ is not marked nillable
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/UpdateUser", ReplyAction="*")]
Rakuten.Test.Web.UserService.UpdateUserResponse UpdateUser(Rakuten.Test.Web.UserService.UpdateUserRequest request);
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/UpdateUser", ReplyAction="*")]
System.Threading.Tasks.Task<Rakuten.Test.Web.UserService.UpdateUserResponse> UpdateUserAsync(Rakuten.Test.Web.UserService.UpdateUserRequest request);
// CODEGEN: Generating message contract since element name DeleteUserResult from namespace http://tempuri.org/ is not marked nillable
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/DeleteUser", ReplyAction="*")]
Rakuten.Test.Web.UserService.DeleteUserResponse DeleteUser(Rakuten.Test.Web.UserService.DeleteUserRequest request);
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/DeleteUser", ReplyAction="*")]
System.Threading.Tasks.Task<Rakuten.Test.Web.UserService.DeleteUserResponse> DeleteUserAsync(Rakuten.Test.Web.UserService.DeleteUserRequest request);
// CODEGEN: Generating message contract since element name email from namespace http://tempuri.org/ is not marked nillable
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/EmailExists", ReplyAction="*")]
Rakuten.Test.Web.UserService.EmailExistsResponse EmailExists(Rakuten.Test.Web.UserService.EmailExistsRequest request);
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/EmailExists", ReplyAction="*")]
System.Threading.Tasks.Task<Rakuten.Test.Web.UserService.EmailExistsResponse> EmailExistsAsync(Rakuten.Test.Web.UserService.EmailExistsRequest request);
// CODEGEN: Generating message contract since element name documentId from namespace http://tempuri.org/ is not marked nillable
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/DocumentExists", ReplyAction="*")]
Rakuten.Test.Web.UserService.DocumentExistsResponse DocumentExists(Rakuten.Test.Web.UserService.DocumentExistsRequest request);
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/DocumentExists", ReplyAction="*")]
System.Threading.Tasks.Task<Rakuten.Test.Web.UserService.DocumentExistsResponse> DocumentExistsAsync(Rakuten.Test.Web.UserService.DocumentExistsRequest request);
// CODEGEN: Generating message contract since element name rg from namespace http://tempuri.org/ is not marked nillable
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/RgExists", ReplyAction="*")]
Rakuten.Test.Web.UserService.RgExistsResponse RgExists(Rakuten.Test.Web.UserService.RgExistsRequest request);
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/RgExists", ReplyAction="*")]
System.Threading.Tasks.Task<Rakuten.Test.Web.UserService.RgExistsResponse> RgExistsAsync(Rakuten.Test.Web.UserService.RgExistsRequest request);
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.ServiceModel.MessageContractAttribute(IsWrapped=false)]
public partial class GetUserRequest {
[System.ServiceModel.MessageBodyMemberAttribute(Name="GetUser", Namespace="http://tempuri.org/", Order=0)]
public Rakuten.Test.Web.UserService.GetUserRequestBody Body;
public GetUserRequest() {
}
public GetUserRequest(Rakuten.Test.Web.UserService.GetUserRequestBody Body) {
this.Body = Body;
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.Runtime.Serialization.DataContractAttribute(Namespace="http://tempuri.org/")]
public partial class GetUserRequestBody {
[System.Runtime.Serialization.DataMemberAttribute(Order=0)]
public int id;
public GetUserRequestBody() {
}
public GetUserRequestBody(int id) {
this.id = id;
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.ServiceModel.MessageContractAttribute(IsWrapped=false)]
public partial class GetUserResponse {
[System.ServiceModel.MessageBodyMemberAttribute(Name="GetUserResponse", Namespace="http://tempuri.org/", Order=0)]
public Rakuten.Test.Web.UserService.GetUserResponseBody Body;
public GetUserResponse() {
}
public GetUserResponse(Rakuten.Test.Web.UserService.GetUserResponseBody Body) {
this.Body = Body;
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.Runtime.Serialization.DataContractAttribute(Namespace="http://tempuri.org/")]
public partial class GetUserResponseBody {
[System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=0)]
public Rakuten.Test.Web.UserService.ServiceResultOfUser GetUserResult;
public GetUserResponseBody() {
}
public GetUserResponseBody(Rakuten.Test.Web.UserService.ServiceResultOfUser GetUserResult) {
this.GetUserResult = GetUserResult;
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.ServiceModel.MessageContractAttribute(IsWrapped=false)]
public partial class GetUsersRequest {
[System.ServiceModel.MessageBodyMemberAttribute(Name="GetUsers", Namespace="http://tempuri.org/", Order=0)]
public Rakuten.Test.Web.UserService.GetUsersRequestBody Body;
public GetUsersRequest() {
}
public GetUsersRequest(Rakuten.Test.Web.UserService.GetUsersRequestBody Body) {
this.Body = Body;
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.Runtime.Serialization.DataContractAttribute()]
public partial class GetUsersRequestBody {
public GetUsersRequestBody() {
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.ServiceModel.MessageContractAttribute(IsWrapped=false)]
public partial class GetUsersResponse {
[System.ServiceModel.MessageBodyMemberAttribute(Name="GetUsersResponse", Namespace="http://tempuri.org/", Order=0)]
public Rakuten.Test.Web.UserService.GetUsersResponseBody Body;
public GetUsersResponse() {
}
public GetUsersResponse(Rakuten.Test.Web.UserService.GetUsersResponseBody Body) {
this.Body = Body;
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.Runtime.Serialization.DataContractAttribute(Namespace="http://tempuri.org/")]
public partial class GetUsersResponseBody {
[System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=0)]
public Rakuten.Test.Web.UserService.ServiceResultOfListOfUser GetUsersResult;
public GetUsersResponseBody() {
}
public GetUsersResponseBody(Rakuten.Test.Web.UserService.ServiceResultOfListOfUser GetUsersResult) {
this.GetUsersResult = GetUsersResult;
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.ServiceModel.MessageContractAttribute(IsWrapped=false)]
public partial class AddUserRequest {
[System.ServiceModel.MessageBodyMemberAttribute(Name="AddUser", Namespace="http://tempuri.org/", Order=0)]
public Rakuten.Test.Web.UserService.AddUserRequestBody Body;
public AddUserRequest() {
}
public AddUserRequest(Rakuten.Test.Web.UserService.AddUserRequestBody Body) {
this.Body = Body;
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.Runtime.Serialization.DataContractAttribute(Namespace="http://tempuri.org/")]
public partial class AddUserRequestBody {
[System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=0)]
public Rakuten.Test.Web.UserService.User user;
public AddUserRequestBody() {
}
public AddUserRequestBody(Rakuten.Test.Web.UserService.User user) {
this.user = user;
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.ServiceModel.MessageContractAttribute(IsWrapped=false)]
public partial class AddUserResponse {
[System.ServiceModel.MessageBodyMemberAttribute(Name="AddUserResponse", Namespace="http://tempuri.org/", Order=0)]
public Rakuten.Test.Web.UserService.AddUserResponseBody Body;
public AddUserResponse() {
}
public AddUserResponse(Rakuten.Test.Web.UserService.AddUserResponseBody Body) {
this.Body = Body;
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.Runtime.Serialization.DataContractAttribute(Namespace="http://tempuri.org/")]
public partial class AddUserResponseBody {
[System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=0)]
public Rakuten.Test.Web.UserService.ServiceResultOfUser AddUserResult;
public AddUserResponseBody() {
}
public AddUserResponseBody(Rakuten.Test.Web.UserService.ServiceResultOfUser AddUserResult) {
this.AddUserResult = AddUserResult;
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.ServiceModel.MessageContractAttribute(IsWrapped=false)]
public partial class UpdateUserRequest {
[System.ServiceModel.MessageBodyMemberAttribute(Name="UpdateUser", Namespace="http://tempuri.org/", Order=0)]
public Rakuten.Test.Web.UserService.UpdateUserRequestBody Body;
public UpdateUserRequest() {
}
public UpdateUserRequest(Rakuten.Test.Web.UserService.UpdateUserRequestBody Body) {
this.Body = Body;
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.Runtime.Serialization.DataContractAttribute(Namespace="http://tempuri.org/")]
public partial class UpdateUserRequestBody {
[System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=0)]
public Rakuten.Test.Web.UserService.User user;
public UpdateUserRequestBody() {
}
public UpdateUserRequestBody(Rakuten.Test.Web.UserService.User user) {
this.user = user;
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.ServiceModel.MessageContractAttribute(IsWrapped=false)]
public partial class UpdateUserResponse {
[System.ServiceModel.MessageBodyMemberAttribute(Name="UpdateUserResponse", Namespace="http://tempuri.org/", Order=0)]
public Rakuten.Test.Web.UserService.UpdateUserResponseBody Body;
public UpdateUserResponse() {
}
public UpdateUserResponse(Rakuten.Test.Web.UserService.UpdateUserResponseBody Body) {
this.Body = Body;
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.Runtime.Serialization.DataContractAttribute(Namespace="http://tempuri.org/")]
public partial class UpdateUserResponseBody {
[System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=0)]
public Rakuten.Test.Web.UserService.ServiceResultOfUser UpdateUserResult;
public UpdateUserResponseBody() {
}
public UpdateUserResponseBody(Rakuten.Test.Web.UserService.ServiceResultOfUser UpdateUserResult) {
this.UpdateUserResult = UpdateUserResult;
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.ServiceModel.MessageContractAttribute(IsWrapped=false)]
public partial class DeleteUserRequest {
[System.ServiceModel.MessageBodyMemberAttribute(Name="DeleteUser", Namespace="http://tempuri.org/", Order=0)]
public Rakuten.Test.Web.UserService.DeleteUserRequestBody Body;
public DeleteUserRequest() {
}
public DeleteUserRequest(Rakuten.Test.Web.UserService.DeleteUserRequestBody Body) {
this.Body = Body;
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.Runtime.Serialization.DataContractAttribute(Namespace="http://tempuri.org/")]
public partial class DeleteUserRequestBody {
[System.Runtime.Serialization.DataMemberAttribute(Order=0)]
public int id;
public DeleteUserRequestBody() {
}
public DeleteUserRequestBody(int id) {
this.id = id;
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.ServiceModel.MessageContractAttribute(IsWrapped=false)]
public partial class DeleteUserResponse {
[System.ServiceModel.MessageBodyMemberAttribute(Name="DeleteUserResponse", Namespace="http://tempuri.org/", Order=0)]
public Rakuten.Test.Web.UserService.DeleteUserResponseBody Body;
public DeleteUserResponse() {
}
public DeleteUserResponse(Rakuten.Test.Web.UserService.DeleteUserResponseBody Body) {
this.Body = Body;
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.Runtime.Serialization.DataContractAttribute(Namespace="http://tempuri.org/")]
public partial class DeleteUserResponseBody {
[System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=0)]
public Rakuten.Test.Web.UserService.ServiceResultOfServiceResponse DeleteUserResult;
public DeleteUserResponseBody() {
}
public DeleteUserResponseBody(Rakuten.Test.Web.UserService.ServiceResultOfServiceResponse DeleteUserResult) {
this.DeleteUserResult = DeleteUserResult;
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.ServiceModel.MessageContractAttribute(IsWrapped=false)]
public partial class EmailExistsRequest {
[System.ServiceModel.MessageBodyMemberAttribute(Name="EmailExists", Namespace="http://tempuri.org/", Order=0)]
public Rakuten.Test.Web.UserService.EmailExistsRequestBody Body;
public EmailExistsRequest() {
}
public EmailExistsRequest(Rakuten.Test.Web.UserService.EmailExistsRequestBody Body) {
this.Body = Body;
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.Runtime.Serialization.DataContractAttribute(Namespace="http://tempuri.org/")]
public partial class EmailExistsRequestBody {
[System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=0)]
public string email;
public EmailExistsRequestBody() {
}
public EmailExistsRequestBody(string email) {
this.email = email;
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.ServiceModel.MessageContractAttribute(IsWrapped=false)]
public partial class EmailExistsResponse {
[System.ServiceModel.MessageBodyMemberAttribute(Name="EmailExistsResponse", Namespace="http://tempuri.org/", Order=0)]
public Rakuten.Test.Web.UserService.EmailExistsResponseBody Body;
public EmailExistsResponse() {
}
public EmailExistsResponse(Rakuten.Test.Web.UserService.EmailExistsResponseBody Body) {
this.Body = Body;
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.Runtime.Serialization.DataContractAttribute(Namespace="http://tempuri.org/")]
public partial class EmailExistsResponseBody {
[System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=0)]
public Rakuten.Test.Web.UserService.ServiceResultOfServiceResponse EmailExistsResult;
public EmailExistsResponseBody() {
}
public EmailExistsResponseBody(Rakuten.Test.Web.UserService.ServiceResultOfServiceResponse EmailExistsResult) {
this.EmailExistsResult = EmailExistsResult;
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.ServiceModel.MessageContractAttribute(IsWrapped=false)]
public partial class DocumentExistsRequest {
[System.ServiceModel.MessageBodyMemberAttribute(Name="DocumentExists", Namespace="http://tempuri.org/", Order=0)]
public Rakuten.Test.Web.UserService.DocumentExistsRequestBody Body;
public DocumentExistsRequest() {
}
public DocumentExistsRequest(Rakuten.Test.Web.UserService.DocumentExistsRequestBody Body) {
this.Body = Body;
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.Runtime.Serialization.DataContractAttribute(Namespace="http://tempuri.org/")]
public partial class DocumentExistsRequestBody {
[System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=0)]
public string documentId;
public DocumentExistsRequestBody() {
}
public DocumentExistsRequestBody(string documentId) {
this.documentId = documentId;
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.ServiceModel.MessageContractAttribute(IsWrapped=false)]
public partial class DocumentExistsResponse {
[System.ServiceModel.MessageBodyMemberAttribute(Name="DocumentExistsResponse", Namespace="http://tempuri.org/", Order=0)]
public Rakuten.Test.Web.UserService.DocumentExistsResponseBody Body;
public DocumentExistsResponse() {
}
public DocumentExistsResponse(Rakuten.Test.Web.UserService.DocumentExistsResponseBody Body) {
this.Body = Body;
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.Runtime.Serialization.DataContractAttribute(Namespace="http://tempuri.org/")]
public partial class DocumentExistsResponseBody {
[System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=0)]
public Rakuten.Test.Web.UserService.ServiceResultOfServiceResponse DocumentExistsResult;
public DocumentExistsResponseBody() {
}
public DocumentExistsResponseBody(Rakuten.Test.Web.UserService.ServiceResultOfServiceResponse DocumentExistsResult) {
this.DocumentExistsResult = DocumentExistsResult;
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.ServiceModel.MessageContractAttribute(IsWrapped=false)]
public partial class RgExistsRequest {
[System.ServiceModel.MessageBodyMemberAttribute(Name="RgExists", Namespace="http://tempuri.org/", Order=0)]
public Rakuten.Test.Web.UserService.RgExistsRequestBody Body;
public RgExistsRequest() {
}
public RgExistsRequest(Rakuten.Test.Web.UserService.RgExistsRequestBody Body) {
this.Body = Body;
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.Runtime.Serialization.DataContractAttribute(Namespace="http://tempuri.org/")]
public partial class RgExistsRequestBody {
[System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=0)]
public string rg;
public RgExistsRequestBody() {
}
public RgExistsRequestBody(string rg) {
this.rg = rg;
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.ServiceModel.MessageContractAttribute(IsWrapped=false)]
public partial class RgExistsResponse {
[System.ServiceModel.MessageBodyMemberAttribute(Name="RgExistsResponse", Namespace="http://tempuri.org/", Order=0)]
public Rakuten.Test.Web.UserService.RgExistsResponseBody Body;
public RgExistsResponse() {
}
public RgExistsResponse(Rakuten.Test.Web.UserService.RgExistsResponseBody Body) {
this.Body = Body;
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.Runtime.Serialization.DataContractAttribute(Namespace="http://tempuri.org/")]
public partial class RgExistsResponseBody {
[System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=0)]
public Rakuten.Test.Web.UserService.ServiceResultOfServiceResponse RgExistsResult;
public RgExistsResponseBody() {
}
public RgExistsResponseBody(Rakuten.Test.Web.UserService.ServiceResultOfServiceResponse RgExistsResult) {
this.RgExistsResult = RgExistsResult;
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public interface UserSoapChannel : Rakuten.Test.Web.UserService.UserSoap, System.ServiceModel.IClientChannel {
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public partial class UserSoapClient : System.ServiceModel.ClientBase<Rakuten.Test.Web.UserService.UserSoap>, Rakuten.Test.Web.UserService.UserSoap {
public UserSoapClient() {
}
public UserSoapClient(string endpointConfigurationName) :
base(endpointConfigurationName) {
}
public UserSoapClient(string endpointConfigurationName, string remoteAddress) :
base(endpointConfigurationName, remoteAddress) {
}
public UserSoapClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) :
base(endpointConfigurationName, remoteAddress) {
}
public UserSoapClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) :
base(binding, remoteAddress) {
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
Rakuten.Test.Web.UserService.GetUserResponse Rakuten.Test.Web.UserService.UserSoap.GetUser(Rakuten.Test.Web.UserService.GetUserRequest request) {
return base.Channel.GetUser(request);
}
public Rakuten.Test.Web.UserService.ServiceResultOfUser GetUser(int id) {
Rakuten.Test.Web.UserService.GetUserRequest inValue = new Rakuten.Test.Web.UserService.GetUserRequest();
inValue.Body = new Rakuten.Test.Web.UserService.GetUserRequestBody();
inValue.Body.id = id;
Rakuten.Test.Web.UserService.GetUserResponse retVal = ((Rakuten.Test.Web.UserService.UserSoap)(this)).GetUser(inValue);
return retVal.Body.GetUserResult;
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
System.Threading.Tasks.Task<Rakuten.Test.Web.UserService.GetUserResponse> Rakuten.Test.Web.UserService.UserSoap.GetUserAsync(Rakuten.Test.Web.UserService.GetUserRequest request) {
return base.Channel.GetUserAsync(request);
}
public System.Threading.Tasks.Task<Rakuten.Test.Web.UserService.GetUserResponse> GetUserAsync(int id) {
Rakuten.Test.Web.UserService.GetUserRequest inValue = new Rakuten.Test.Web.UserService.GetUserRequest();
inValue.Body = new Rakuten.Test.Web.UserService.GetUserRequestBody();
inValue.Body.id = id;
return ((Rakuten.Test.Web.UserService.UserSoap)(this)).GetUserAsync(inValue);
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
Rakuten.Test.Web.UserService.GetUsersResponse Rakuten.Test.Web.UserService.UserSoap.GetUsers(Rakuten.Test.Web.UserService.GetUsersRequest request) {
return base.Channel.GetUsers(request);
}
public Rakuten.Test.Web.UserService.ServiceResultOfListOfUser GetUsers() {
Rakuten.Test.Web.UserService.GetUsersRequest inValue = new Rakuten.Test.Web.UserService.GetUsersRequest();
inValue.Body = new Rakuten.Test.Web.UserService.GetUsersRequestBody();
Rakuten.Test.Web.UserService.GetUsersResponse retVal = ((Rakuten.Test.Web.UserService.UserSoap)(this)).GetUsers(inValue);
return retVal.Body.GetUsersResult;
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
System.Threading.Tasks.Task<Rakuten.Test.Web.UserService.GetUsersResponse> Rakuten.Test.Web.UserService.UserSoap.GetUsersAsync(Rakuten.Test.Web.UserService.GetUsersRequest request) {
return base.Channel.GetUsersAsync(request);
}
public System.Threading.Tasks.Task<Rakuten.Test.Web.UserService.GetUsersResponse> GetUsersAsync() {
Rakuten.Test.Web.UserService.GetUsersRequest inValue = new Rakuten.Test.Web.UserService.GetUsersRequest();
inValue.Body = new Rakuten.Test.Web.UserService.GetUsersRequestBody();
return ((Rakuten.Test.Web.UserService.UserSoap)(this)).GetUsersAsync(inValue);
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
Rakuten.Test.Web.UserService.AddUserResponse Rakuten.Test.Web.UserService.UserSoap.AddUser(Rakuten.Test.Web.UserService.AddUserRequest request) {
return base.Channel.AddUser(request);
}
public Rakuten.Test.Web.UserService.ServiceResultOfUser AddUser(Rakuten.Test.Web.UserService.User user) {
Rakuten.Test.Web.UserService.AddUserRequest inValue = new Rakuten.Test.Web.UserService.AddUserRequest();
inValue.Body = new Rakuten.Test.Web.UserService.AddUserRequestBody();
inValue.Body.user = user;
Rakuten.Test.Web.UserService.AddUserResponse retVal = ((Rakuten.Test.Web.UserService.UserSoap)(this)).AddUser(inValue);
return retVal.Body.AddUserResult;
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
System.Threading.Tasks.Task<Rakuten.Test.Web.UserService.AddUserResponse> Rakuten.Test.Web.UserService.UserSoap.AddUserAsync(Rakuten.Test.Web.UserService.AddUserRequest request) {
return base.Channel.AddUserAsync(request);
}
public System.Threading.Tasks.Task<Rakuten.Test.Web.UserService.AddUserResponse> AddUserAsync(Rakuten.Test.Web.UserService.User user) {
Rakuten.Test.Web.UserService.AddUserRequest inValue = new Rakuten.Test.Web.UserService.AddUserRequest();
inValue.Body = new Rakuten.Test.Web.UserService.AddUserRequestBody();
inValue.Body.user = user;
return ((Rakuten.Test.Web.UserService.UserSoap)(this)).AddUserAsync(inValue);
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
Rakuten.Test.Web.UserService.UpdateUserResponse Rakuten.Test.Web.UserService.UserSoap.UpdateUser(Rakuten.Test.Web.UserService.UpdateUserRequest request) {
return base.Channel.UpdateUser(request);
}
public Rakuten.Test.Web.UserService.ServiceResultOfUser UpdateUser(Rakuten.Test.Web.UserService.User user) {
Rakuten.Test.Web.UserService.UpdateUserRequest inValue = new Rakuten.Test.Web.UserService.UpdateUserRequest();
inValue.Body = new Rakuten.Test.Web.UserService.UpdateUserRequestBody();
inValue.Body.user = user;
Rakuten.Test.Web.UserService.UpdateUserResponse retVal = ((Rakuten.Test.Web.UserService.UserSoap)(this)).UpdateUser(inValue);
return retVal.Body.UpdateUserResult;
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
System.Threading.Tasks.Task<Rakuten.Test.Web.UserService.UpdateUserResponse> Rakuten.Test.Web.UserService.UserSoap.UpdateUserAsync(Rakuten.Test.Web.UserService.UpdateUserRequest request) {
return base.Channel.UpdateUserAsync(request);
}
public System.Threading.Tasks.Task<Rakuten.Test.Web.UserService.UpdateUserResponse> UpdateUserAsync(Rakuten.Test.Web.UserService.User user) {
Rakuten.Test.Web.UserService.UpdateUserRequest inValue = new Rakuten.Test.Web.UserService.UpdateUserRequest();
inValue.Body = new Rakuten.Test.Web.UserService.UpdateUserRequestBody();
inValue.Body.user = user;
return ((Rakuten.Test.Web.UserService.UserSoap)(this)).UpdateUserAsync(inValue);
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
Rakuten.Test.Web.UserService.DeleteUserResponse Rakuten.Test.Web.UserService.UserSoap.DeleteUser(Rakuten.Test.Web.UserService.DeleteUserRequest request) {
return base.Channel.DeleteUser(request);
}
public Rakuten.Test.Web.UserService.ServiceResultOfServiceResponse DeleteUser(int id) {
Rakuten.Test.Web.UserService.DeleteUserRequest inValue = new Rakuten.Test.Web.UserService.DeleteUserRequest();
inValue.Body = new Rakuten.Test.Web.UserService.DeleteUserRequestBody();
inValue.Body.id = id;
Rakuten.Test.Web.UserService.DeleteUserResponse retVal = ((Rakuten.Test.Web.UserService.UserSoap)(this)).DeleteUser(inValue);
return retVal.Body.DeleteUserResult;
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
System.Threading.Tasks.Task<Rakuten.Test.Web.UserService.DeleteUserResponse> Rakuten.Test.Web.UserService.UserSoap.DeleteUserAsync(Rakuten.Test.Web.UserService.DeleteUserRequest request) {
return base.Channel.DeleteUserAsync(request);
}
public System.Threading.Tasks.Task<Rakuten.Test.Web.UserService.DeleteUserResponse> DeleteUserAsync(int id) {
Rakuten.Test.Web.UserService.DeleteUserRequest inValue = new Rakuten.Test.Web.UserService.DeleteUserRequest();
inValue.Body = new Rakuten.Test.Web.UserService.DeleteUserRequestBody();
inValue.Body.id = id;
return ((Rakuten.Test.Web.UserService.UserSoap)(this)).DeleteUserAsync(inValue);
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
Rakuten.Test.Web.UserService.EmailExistsResponse Rakuten.Test.Web.UserService.UserSoap.EmailExists(Rakuten.Test.Web.UserService.EmailExistsRequest request) {
return base.Channel.EmailExists(request);
}
public Rakuten.Test.Web.UserService.ServiceResultOfServiceResponse EmailExists(string email) {
Rakuten.Test.Web.UserService.EmailExistsRequest inValue = new Rakuten.Test.Web.UserService.EmailExistsRequest();
inValue.Body = new Rakuten.Test.Web.UserService.EmailExistsRequestBody();
inValue.Body.email = email;
Rakuten.Test.Web.UserService.EmailExistsResponse retVal = ((Rakuten.Test.Web.UserService.UserSoap)(this)).EmailExists(inValue);
return retVal.Body.EmailExistsResult;
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
System.Threading.Tasks.Task<Rakuten.Test.Web.UserService.EmailExistsResponse> Rakuten.Test.Web.UserService.UserSoap.EmailExistsAsync(Rakuten.Test.Web.UserService.EmailExistsRequest request) {
return base.Channel.EmailExistsAsync(request);
}
public System.Threading.Tasks.Task<Rakuten.Test.Web.UserService.EmailExistsResponse> EmailExistsAsync(string email) {
Rakuten.Test.Web.UserService.EmailExistsRequest inValue = new Rakuten.Test.Web.UserService.EmailExistsRequest();
inValue.Body = new Rakuten.Test.Web.UserService.EmailExistsRequestBody();
inValue.Body.email = email;
return ((Rakuten.Test.Web.UserService.UserSoap)(this)).EmailExistsAsync(inValue);
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
Rakuten.Test.Web.UserService.DocumentExistsResponse Rakuten.Test.Web.UserService.UserSoap.DocumentExists(Rakuten.Test.Web.UserService.DocumentExistsRequest request) {
return base.Channel.DocumentExists(request);
}
public Rakuten.Test.Web.UserService.ServiceResultOfServiceResponse DocumentExists(string documentId) {
Rakuten.Test.Web.UserService.DocumentExistsRequest inValue = new Rakuten.Test.Web.UserService.DocumentExistsRequest();
inValue.Body = new Rakuten.Test.Web.UserService.DocumentExistsRequestBody();
inValue.Body.documentId = documentId;
Rakuten.Test.Web.UserService.DocumentExistsResponse retVal = ((Rakuten.Test.Web.UserService.UserSoap)(this)).DocumentExists(inValue);
return retVal.Body.DocumentExistsResult;
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
System.Threading.Tasks.Task<Rakuten.Test.Web.UserService.DocumentExistsResponse> Rakuten.Test.Web.UserService.UserSoap.DocumentExistsAsync(Rakuten.Test.Web.UserService.DocumentExistsRequest request) {
return base.Channel.DocumentExistsAsync(request);
}
public System.Threading.Tasks.Task<Rakuten.Test.Web.UserService.DocumentExistsResponse> DocumentExistsAsync(string documentId) {
Rakuten.Test.Web.UserService.DocumentExistsRequest inValue = new Rakuten.Test.Web.UserService.DocumentExistsRequest();
inValue.Body = new Rakuten.Test.Web.UserService.DocumentExistsRequestBody();
inValue.Body.documentId = documentId;
return ((Rakuten.Test.Web.UserService.UserSoap)(this)).DocumentExistsAsync(inValue);
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
Rakuten.Test.Web.UserService.RgExistsResponse Rakuten.Test.Web.UserService.UserSoap.RgExists(Rakuten.Test.Web.UserService.RgExistsRequest request) {
return base.Channel.RgExists(request);
}
public Rakuten.Test.Web.UserService.ServiceResultOfServiceResponse RgExists(string rg) {
Rakuten.Test.Web.UserService.RgExistsRequest inValue = new Rakuten.Test.Web.UserService.RgExistsRequest();
inValue.Body = new Rakuten.Test.Web.UserService.RgExistsRequestBody();
inValue.Body.rg = rg;
Rakuten.Test.Web.UserService.RgExistsResponse retVal = ((Rakuten.Test.Web.UserService.UserSoap)(this)).RgExists(inValue);
return retVal.Body.RgExistsResult;
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
System.Threading.Tasks.Task<Rakuten.Test.Web.UserService.RgExistsResponse> Rakuten.Test.Web.UserService.UserSoap.RgExistsAsync(Rakuten.Test.Web.UserService.RgExistsRequest request) {
return base.Channel.RgExistsAsync(request);
}
public System.Threading.Tasks.Task<Rakuten.Test.Web.UserService.RgExistsResponse> RgExistsAsync(string rg) {
Rakuten.Test.Web.UserService.RgExistsRequest inValue = new Rakuten.Test.Web.UserService.RgExistsRequest();
inValue.Body = new Rakuten.Test.Web.UserService.RgExistsRequestBody();
inValue.Body.rg = rg;
return ((Rakuten.Test.Web.UserService.UserSoap)(this)).RgExistsAsync(inValue);
}
}
}
| 46.561205 | 208 | 0.660384 | [
"MIT"
] | fernandonobrega89/backend-developer-test | Rakuten.Test/Rakuten.Test.Web/Service References/UserService/Reference.cs | 74,174 | 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 swf-2012-01-25.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.SimpleWorkflow.Model
{
/// <summary>
/// Provides details of the <code>CompleteWorkflowExecution</code> decision.
///
///
/// <para>
/// <b>Access Control</b>
/// </para>
///
/// <para>
/// You can use IAM policies to control this decision's access to Amazon SWF in much the
/// same way as for the regular API:
/// </para>
/// <ul> <li>Use a <code>Resource</code> element with the domain name to limit the decision
/// to only specified domains.</li> <li>Use an <code>Action</code> element to allow or
/// deny permission to specify this decision.</li> <li>You cannot use an IAM policy to
/// constrain this action's parameters.</li> </ul>
/// <para>
/// If the caller does not have sufficient permissions to invoke the action, or the parameter
/// values fall outside the specified constraints, the action fails. The associated event
/// attribute's <b>cause</b> parameter will be set to OPERATION_NOT_PERMITTED. For details
/// and example IAM policies, see <a href="http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using
/// IAM to Manage Access to Amazon SWF Workflows</a>.
/// </para>
/// </summary>
public partial class CompleteWorkflowExecutionDecisionAttributes
{
private string _result;
/// <summary>
/// Gets and sets the property Result.
/// <para>
/// The result of the workflow execution. The form of the result is implementation defined.
///
/// </para>
/// </summary>
public string Result
{
get { return this._result; }
set { this._result = value; }
}
// Check to see if Result property is set
internal bool IsSetResult()
{
return this._result != null;
}
}
} | 35.474359 | 129 | 0.64944 | [
"Apache-2.0"
] | ermshiperete/aws-sdk-net | AWSSDK_DotNet35/Amazon.SimpleWorkflow/Model/CompleteWorkflowExecutionDecisionAttributes.cs | 2,767 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
namespace System.Reactive
{
using System.Reactive.Concurrency;
/// <summary>
/// Contract for demiltiplexors providing sequences of events of specific types.
/// </summary>
public interface IObservableDemultiplexor
{
/// <summary>
/// Call this to get just the events of given type
/// </summary>
/// <typeparam name="T">The type of interest</typeparam>
IObservable<T> GetObservable<T>();
}
public interface IPlayback : IObservableDemultiplexor, IPlaybackConfiguration
{
IScheduler Scheduler { get; }
void Run();
void Start();
}
}
| 27.785714 | 133 | 0.645244 | [
"Apache-2.0"
] | Microsoft/Tx | Source/Tx.Core/IPlayback.cs | 780 | C# |
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2015, MPL Ali Taheri Moghaddar ali.taheri.m@gmail.com
*/
using System.Collections.Generic;
using System.Linq;
namespace Pablo.Graphics
{
/// <summary>
/// Displays a rectangle described by a <see cref="PolygonGeometry"/>.
/// </summary>
public sealed class Rectangle : Shape<PolygonGeometry>
{
/// <summary>
/// Gets the <see cref="Point"/>s that describe this <see cref="Rectangle"/>.
/// </summary>
public IEnumerable<Point> Points => Geometry.Points;
/// <summary>
/// Initialized a new instance of <see cref="Rectangle"/>.
/// </summary>
public Rectangle()
{
Geometry = new PolygonGeometry
{
Points = Enumerable.Repeat(new Point(), 4),
IsReadOnly = true,
};
}
/// <summary>
/// Initialized a new instance of <see cref="Rectangle"/> from the provided <see cref="Box"/>.
/// </summary>
public Rectangle(Box box)
{
Geometry = new PolygonGeometry
{
Points = box.Points,
IsReadOnly = true,
};
}
/// <summary>
/// Initialized a new instance of <see cref="Rectangle"/> from the provided sides.
/// </summary>
public Rectangle(double left, double top, double right, double bottom)
: this(new Box(left, top, right, bottom))
{ }
}
}
| 29.37931 | 102 | 0.55223 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | pabloengine/pablo | Pablo/Graphics/Shape/Rectangle.cs | 1,706 | C# |
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
namespace RestClient
{
public class Singleton<T> : MonoBehaviour where T: MonoBehaviour{
private static T _instance;
public static T Instance
{
get
{
if (_instance == null)
{
if (_instance == null)
{
GameObject obj = new GameObject();
_instance = obj.AddComponent<T>();
obj.name = typeof(T).Name;
}
}
return _instance;
}
}
}
public class HttpClient : Singleton<HttpClient>
{
/// <summary>
/// start a coroutine to Get json payload from an url
/// </summary>
/// <param name="url">the url for the get request</param>
/// <param name="response">Callback action to handle coroutine string response</param>
public void Get<T>(string url, Action<T> response) where T: class
{
StartCoroutine(GetCoroutine(url, response));
}
/// <summary>
/// IEnumerator used by Get coroutine to execute the webrequest asynchronoussly
/// </summary>
/// <param name="url">the url for the get request</param>
/// <param name="response">Callback action to handle coroutine string response</param>
private IEnumerator GetCoroutine<T>(string url, Action<T> response) where T: class
{
if (Application.internetReachability == NetworkReachability.NotReachable)
{
Debug.LogError("Network is not Reachable.");
}
using(UnityWebRequest webRequest = UnityWebRequestTexture.GetTexture(url))
{
yield return webRequest.SendWebRequest();
string contentType = webRequest.GetResponseHeader("Content-Type");
switch (webRequest.result)
{
case UnityWebRequest.Result.ConnectionError:
case UnityWebRequest.Result.DataProcessingError:
break;
case UnityWebRequest.Result.ProtocolError:
Debug.LogError(url + ": HTTP Error: " + webRequest.error);
break;
case UnityWebRequest.Result.Success:
if (typeof(T).Equals(typeof(string))) {
if (contentType == "application/json") {
response(webRequest.downloadHandler.text as T);
} else {
Debug.LogError("received data was not in JSON format for URL: " + url);
}
} else if (typeof(T).Equals(typeof(Texture2D))) {
if (contentType == "image/png" || contentType == "image/jpeg")
response(((DownloadHandlerTexture)webRequest.downloadHandler).texture as T);
} else {
Debug.LogError("received texture was not in JPEG or PNG format for URL: " + url);
}
break;
}
}
}
}
}
| 37.755556 | 109 | 0.49588 | [
"MIT"
] | sebastien6/UnityFullStackSample | unity/Assets/Scripts/Runtime/RestClient/RestClient.cs | 3,398 | C# |
using BookmarkManager.Application.Common;
using BookmarkManager.Domain.Entities;
namespace BookmarkManager.Application.Dto
{
public class CategoryDto: IMapFrom<Category>
{
public int Id { get; set; }
public string Title { get; set; }
}
}
| 22.333333 | 48 | 0.697761 | [
"MIT"
] | uthmanrahimi/BookmarkManager | src/BookmarkManager.Application/Dto/Category/CategoryDto.cs | 270 | C# |
//----------------------
// <auto-generated>
// Generated by stidgen
// </auto-generated>
//----------------------
using System;
using System.CodeDom.Compiler;
using System.Diagnostics;
using System.Runtime.CompilerServices;
[DebuggerDisplay("{value,nq}")]
public partial struct UserId : IEquatable<UserId>, IComparable<UserId>, IConvertible
{
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
private string value;
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public string Value
{
get
{
return value;
}
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public UserId(string value)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
this.value = string.Intern(value);
CheckValue(this.value);
}
partial void CheckValue(string value);
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public override string ToString()
{
return value;
}
/// <summary>Serves as the default hash function.</summary>
/// <returns>A hash code for the current object.</returns>
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public override int GetHashCode()
{
return RuntimeHelpers.GetHashCode(value);
}
/// <summary>
/// Determines whether the specified object is equal to the current object.
/// <param name="other">The object to compare with the current object.</param>
/// </summary>
/// <returns>
/// true if the specified object is equal to the current object;
/// otherwise, false.
/// </returns>
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public override bool Equals(object other)
{
Debug.Assert(value == null || string.IsInterned(value) == null, "Value should always be interned if interning is enabled");
if (!(other is UserId))
{
return false;
}
return object.ReferenceEquals(value, ((UserId)other).value);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public bool Equals(UserId other)
{
Debug.Assert(value == null || string.IsInterned(value) == null, "Value should always be interned if interning is enabled");
Debug.Assert(other.value == null || string.IsInterned(other.value) == null, "Value should always be interned if interning is enabled");
return object.ReferenceEquals(value, other.value);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public static bool Equals(UserId a, UserId b)
{
Debug.Assert(a.value == null || string.IsInterned(a.value) == null, "Value should always be interned if interning is enabled");
Debug.Assert(b.value == null || string.IsInterned(b.value) == null, "Value should always be interned if interning is enabled");
return object.ReferenceEquals(a.value, b.value);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public static bool operator ==(UserId left, UserId right)
{
Debug.Assert(left.value == null || string.IsInterned(left.value) == null, "Value should always be interned if interning is enabled");
Debug.Assert(right.value == null || string.IsInterned(right.value) == null, "Value should always be interned if interning is enabled");
return object.ReferenceEquals(left.value, right.value);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public static bool operator !=(UserId left, UserId right)
{
Debug.Assert(left.value == null || string.IsInterned(left.value) == null, "Value should always be interned if interning is enabled");
Debug.Assert(right.value == null || string.IsInterned(right.value) == null, "Value should always be interned if interning is enabled");
return !object.ReferenceEquals(left.value, right.value);
}
/// <summary>
/// Compares the current instance with another object of the same type and
/// returns an integer that indicates whether the current instance precedes,
/// follows, or occurs in the same position in the sort order as the other
/// object.
/// </summary>
/// <param name="other">An object to compare with this instance.</param>
/// <returns>
/// A value that indicates the relative order of the objects being compared.
/// The return value has these meanings: Value Meaning Less than zero This
/// instance precedes <paramref name="other" /> in the sort order. Zero This
/// instance occurs in the same position in the sort order as
/// <paramref name="other" />. Greater than zero This instance follows
/// <paramref name="other" /> in the sort order.
/// </returns>
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public int CompareTo(UserId other)
{
if (value == null)
if (other.value == null)
return 0;
else
return -1;
return this.value.CompareTo(other.value);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public static explicit operator string(UserId x)
{
return x.value;
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public static explicit operator UserId(string x)
{
return new UserId(x);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public static explicit operator string(UserId? x)
{
return !x.HasValue || x.Value.value == null ? null : x.Value.value;
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public static explicit operator UserId? (string x)
{
return x == null ? (UserId?)null : new UserId(x);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
TypeCode IConvertible.GetTypeCode()
{
if (value == null)
{
return Convert.GetTypeCode(null);
}
return this.value.GetTypeCode();
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
bool IConvertible.ToBoolean(IFormatProvider provider)
{
if (value == null)
{
return Convert.ToBoolean(null);
}
return ((IConvertible)value).ToBoolean(provider);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
char IConvertible.ToChar(IFormatProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
return ((IConvertible)value).ToChar(provider);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
if (value == null)
{
return Convert.ToSByte(null);
}
return ((IConvertible)value).ToSByte(provider);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
byte IConvertible.ToByte(IFormatProvider provider)
{
if (value == null)
{
return Convert.ToByte(null);
}
return ((IConvertible)value).ToByte(provider);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
short IConvertible.ToInt16(IFormatProvider provider)
{
if (value == null)
{
return Convert.ToInt16(null);
}
return ((IConvertible)value).ToInt16(provider);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
if (value == null)
{
return Convert.ToUInt16(null);
}
return ((IConvertible)value).ToUInt16(provider);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
int IConvertible.ToInt32(IFormatProvider provider)
{
if (value == null)
{
return Convert.ToInt32(null);
}
return ((IConvertible)value).ToInt32(provider);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
uint IConvertible.ToUInt32(IFormatProvider provider)
{
if (value == null)
{
return Convert.ToUInt32(null);
}
return ((IConvertible)value).ToUInt32(provider);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
long IConvertible.ToInt64(IFormatProvider provider)
{
if (value == null)
{
return Convert.ToInt64(null);
}
return ((IConvertible)value).ToInt64(provider);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
if (value == null)
{
return Convert.ToUInt64(null);
}
return ((IConvertible)value).ToUInt64(provider);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
float IConvertible.ToSingle(IFormatProvider provider)
{
if (value == null)
{
return Convert.ToSingle(null);
}
return ((IConvertible)value).ToSingle(provider);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
double IConvertible.ToDouble(IFormatProvider provider)
{
if (value == null)
{
return Convert.ToDouble(null);
}
return ((IConvertible)value).ToDouble(provider);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
decimal IConvertible.ToDecimal(IFormatProvider provider)
{
if (value == null)
{
return Convert.ToDecimal(null);
}
return ((IConvertible)value).ToDecimal(provider);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
if (value == null)
{
return Convert.ToDateTime(null);
}
return ((IConvertible)value).ToDateTime(provider);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
string IConvertible.ToString(IFormatProvider provider)
{
if (value == null)
{
return Convert.ToString(null);
}
return this.value.ToString(provider);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
object IConvertible.ToType(Type conversionType, IFormatProvider provider)
{
if (value == null)
{
return Convert.ChangeType(null, conversionType);
}
return ((IConvertible)value).ToType(conversionType, provider);
}
}
[DebuggerDisplay("{value,nq}")]
public partial struct CompanyId : IEquatable<CompanyId>, IComparable<CompanyId>, IConvertible
{
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
private string value;
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public string Value
{
get
{
return value;
}
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public CompanyId(string value)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
this.value = string.Intern(value);
CheckValue(this.value);
}
partial void CheckValue(string value);
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public override string ToString()
{
return value;
}
/// <summary>Serves as the default hash function.</summary>
/// <returns>A hash code for the current object.</returns>
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public override int GetHashCode()
{
return RuntimeHelpers.GetHashCode(value);
}
/// <summary>
/// Determines whether the specified object is equal to the current object.
/// <param name="other">The object to compare with the current object.</param>
/// </summary>
/// <returns>
/// true if the specified object is equal to the current object;
/// otherwise, false.
/// </returns>
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public override bool Equals(object other)
{
Debug.Assert(value == null || string.IsInterned(value) == null, "Value should always be interned if interning is enabled");
if (!(other is CompanyId))
{
return false;
}
return object.ReferenceEquals(value, ((CompanyId)other).value);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public bool Equals(CompanyId other)
{
Debug.Assert(value == null || string.IsInterned(value) == null, "Value should always be interned if interning is enabled");
Debug.Assert(other.value == null || string.IsInterned(other.value) == null, "Value should always be interned if interning is enabled");
return object.ReferenceEquals(value, other.value);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public static bool Equals(CompanyId a, CompanyId b)
{
Debug.Assert(a.value == null || string.IsInterned(a.value) == null, "Value should always be interned if interning is enabled");
Debug.Assert(b.value == null || string.IsInterned(b.value) == null, "Value should always be interned if interning is enabled");
return object.ReferenceEquals(a.value, b.value);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public static bool operator ==(CompanyId left, CompanyId right)
{
Debug.Assert(left.value == null || string.IsInterned(left.value) == null, "Value should always be interned if interning is enabled");
Debug.Assert(right.value == null || string.IsInterned(right.value) == null, "Value should always be interned if interning is enabled");
return object.ReferenceEquals(left.value, right.value);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public static bool operator !=(CompanyId left, CompanyId right)
{
Debug.Assert(left.value == null || string.IsInterned(left.value) == null, "Value should always be interned if interning is enabled");
Debug.Assert(right.value == null || string.IsInterned(right.value) == null, "Value should always be interned if interning is enabled");
return !object.ReferenceEquals(left.value, right.value);
}
/// <summary>
/// Compares the current instance with another object of the same type and
/// returns an integer that indicates whether the current instance precedes,
/// follows, or occurs in the same position in the sort order as the other
/// object.
/// </summary>
/// <param name="other">An object to compare with this instance.</param>
/// <returns>
/// A value that indicates the relative order of the objects being compared.
/// The return value has these meanings: Value Meaning Less than zero This
/// instance precedes <paramref name="other" /> in the sort order. Zero This
/// instance occurs in the same position in the sort order as
/// <paramref name="other" />. Greater than zero This instance follows
/// <paramref name="other" /> in the sort order.
/// </returns>
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public int CompareTo(CompanyId other)
{
if (value == null)
if (other.value == null)
return 0;
else
return -1;
return this.value.CompareTo(other.value);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public static explicit operator string(CompanyId x)
{
return x.value;
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public static explicit operator CompanyId(string x)
{
return new CompanyId(x);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public static explicit operator string(CompanyId? x)
{
return !x.HasValue || x.Value.value == null ? null : x.Value.value;
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public static explicit operator CompanyId? (string x)
{
return x == null ? (CompanyId?)null : new CompanyId(x);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
TypeCode IConvertible.GetTypeCode()
{
if (value == null)
{
return Convert.GetTypeCode(null);
}
return this.value.GetTypeCode();
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
bool IConvertible.ToBoolean(IFormatProvider provider)
{
if (value == null)
{
return Convert.ToBoolean(null);
}
return ((IConvertible)value).ToBoolean(provider);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
char IConvertible.ToChar(IFormatProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
return ((IConvertible)value).ToChar(provider);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
if (value == null)
{
return Convert.ToSByte(null);
}
return ((IConvertible)value).ToSByte(provider);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
byte IConvertible.ToByte(IFormatProvider provider)
{
if (value == null)
{
return Convert.ToByte(null);
}
return ((IConvertible)value).ToByte(provider);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
short IConvertible.ToInt16(IFormatProvider provider)
{
if (value == null)
{
return Convert.ToInt16(null);
}
return ((IConvertible)value).ToInt16(provider);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
if (value == null)
{
return Convert.ToUInt16(null);
}
return ((IConvertible)value).ToUInt16(provider);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
int IConvertible.ToInt32(IFormatProvider provider)
{
if (value == null)
{
return Convert.ToInt32(null);
}
return ((IConvertible)value).ToInt32(provider);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
uint IConvertible.ToUInt32(IFormatProvider provider)
{
if (value == null)
{
return Convert.ToUInt32(null);
}
return ((IConvertible)value).ToUInt32(provider);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
long IConvertible.ToInt64(IFormatProvider provider)
{
if (value == null)
{
return Convert.ToInt64(null);
}
return ((IConvertible)value).ToInt64(provider);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
if (value == null)
{
return Convert.ToUInt64(null);
}
return ((IConvertible)value).ToUInt64(provider);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
float IConvertible.ToSingle(IFormatProvider provider)
{
if (value == null)
{
return Convert.ToSingle(null);
}
return ((IConvertible)value).ToSingle(provider);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
double IConvertible.ToDouble(IFormatProvider provider)
{
if (value == null)
{
return Convert.ToDouble(null);
}
return ((IConvertible)value).ToDouble(provider);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
decimal IConvertible.ToDecimal(IFormatProvider provider)
{
if (value == null)
{
return Convert.ToDecimal(null);
}
return ((IConvertible)value).ToDecimal(provider);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
if (value == null)
{
return Convert.ToDateTime(null);
}
return ((IConvertible)value).ToDateTime(provider);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
string IConvertible.ToString(IFormatProvider provider)
{
if (value == null)
{
return Convert.ToString(null);
}
return this.value.ToString(provider);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
object IConvertible.ToType(Type conversionType, IFormatProvider provider)
{
if (value == null)
{
return Convert.ChangeType(null, conversionType);
}
return ((IConvertible)value).ToType(conversionType, provider);
}
}
[DebuggerDisplay("{value,nq}")]
public partial struct UploadedFileId : IEquatable<UploadedFileId>, IComparable<UploadedFileId>, IFormattable
{
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
private Guid value;
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public Guid Value
{
get
{
return value;
}
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public UploadedFileId(Guid value)
{
this.value = value;
CheckValue(this.value);
}
partial void CheckValue(Guid value);
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public override string ToString()
{
return value.ToString();
}
/// <summary>Serves as the default hash function.</summary>
/// <returns>A hash code for the current object.</returns>
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public override int GetHashCode()
{
return value.GetHashCode();
}
/// <summary>
/// Determines whether the specified object is equal to the current object.
/// <param name="other">The object to compare with the current object.</param>
/// </summary>
/// <returns>
/// true if the specified object is equal to the current object;
/// otherwise, false.
/// </returns>
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public override bool Equals(object other)
{
if (!(other is UploadedFileId))
{
return false;
}
return value == ((UploadedFileId)other).value;
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public bool Equals(UploadedFileId other)
{
return value == other.value;
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public static bool Equals(UploadedFileId a, UploadedFileId b)
{
return a.value == b.value;
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public static bool operator ==(UploadedFileId left, UploadedFileId right)
{
return left.value == right.value;
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public static bool operator !=(UploadedFileId left, UploadedFileId right)
{
return left.value != right.value;
}
/// <summary>
/// Compares the current instance with another object of the same type and
/// returns an integer that indicates whether the current instance precedes,
/// follows, or occurs in the same position in the sort order as the other
/// object.
/// </summary>
/// <param name="other">An object to compare with this instance.</param>
/// <returns>
/// A value that indicates the relative order of the objects being compared.
/// The return value has these meanings: Value Meaning Less than zero This
/// instance precedes <paramref name="other" /> in the sort order. Zero This
/// instance occurs in the same position in the sort order as
/// <paramref name="other" />. Greater than zero This instance follows
/// <paramref name="other" /> in the sort order.
/// </returns>
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public int CompareTo(UploadedFileId other)
{
return ((IComparable<Guid>)value).CompareTo(other.value);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public static explicit operator Guid(UploadedFileId x)
{
return x.value;
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public static explicit operator UploadedFileId(Guid x)
{
return new UploadedFileId(x);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public static explicit operator Guid? (UploadedFileId? x)
{
return !x.HasValue ? (Guid?)null : x.Value.value;
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public static explicit operator UploadedFileId? (Guid? x)
{
return !x.HasValue ? (UploadedFileId?)null : new UploadedFileId(x.Value);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public static UploadedFileId Parse(string input)
{
return new UploadedFileId(Guid.Parse(input));
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public static bool TryParse(string input, out UploadedFileId result)
{
Guid parsed;
bool isValid = Guid.TryParse(input, out parsed);
result = isValid ? new UploadedFileId(parsed) : default(UploadedFileId);
return isValid;
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public static UploadedFileId? TryParse(string input)
{
Guid parsed;
bool isValid = Guid.TryParse(input, out parsed);
return isValid ? new UploadedFileId(parsed) : (UploadedFileId?)null;
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public string ToString(string format, IFormatProvider formatProvider)
{
return ((IFormattable)value).ToString(format, formatProvider);
}
[GeneratedCode("BlackFox.Stidgen", "1.1.0")]
public string ToString(string format)
{
return value.ToString(format, System.Globalization.CultureInfo.CurrentCulture);
}
} | 30.195938 | 143 | 0.613753 | [
"MIT"
] | pirrmann/stidgen | samples/Simple.Generated.cs | 25,274 | C# |
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
namespace SchoolBusAPI.Seeders
{
public abstract class Seeder<T> where T : DbContext
{
public const string AllProfiles = "all";
private IHostingEnvironment _env;
protected ILogger _logger;
internal Seeder(IConfiguration configuration, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
_env = env;
_logger = loggerFactory.CreateLogger(typeof(Seeder<T>));
Configuration = configuration;
}
protected bool IsEnvironment(string environmentName)
{
return _env.IsEnvironment(environmentName);
}
protected bool IsDevelopmentEnvironment { get { return _env.IsDevelopment(); } }
protected bool IsTestEnvironment { get { return _env.IsEnvironment("Test"); } }
protected bool IsStagingEnvironment { get { return _env.IsStaging(); } }
protected bool IsProductionEnvironment { get { return _env.IsProduction(); } }
protected IConfiguration Configuration { get; private set; }
public virtual Type InvokeAfter { get { return null; } }
protected abstract IEnumerable<string> TriggerProfiles { get; }
protected abstract void Invoke(T context);
public void Seed(T context)
{
if (this.TriggerProfiles.Contains(_env.EnvironmentName, StringComparer.OrdinalIgnoreCase) || this.TriggerProfiles.Contains(AllProfiles, StringComparer.OrdinalIgnoreCase))
{
_logger.LogDebug("The trigger for {0} ({1}) matches the deployment profile ({2}); executing...", this.GetType().Name, string.Join(", ", this.TriggerProfiles), AllProfiles);
this.Invoke(context);
}
else
{
_logger.LogDebug("Trigger profile(s) for {0} ({1}), do not match the deployment profile ({2}); skipping...", this.GetType().Name, string.Join(", ", this.TriggerProfiles), _env.EnvironmentName);
}
}
}
}
| 40.163636 | 209 | 0.66048 | [
"Apache-2.0"
] | BcGovBrian/schoolbus | Server/src/SchoolBusAPI/Seeders/Seeder.cs | 2,211 | C# |
namespace digitalClock
{
partial class clock
{
/// <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.label1 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// label1
//
this.label1.Font = new System.Drawing.Font("Onyx", 180F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.ForeColor = System.Drawing.SystemColors.ControlLightLight;
this.label1.Location = new System.Drawing.Point(219, 85);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(868, 331);
this.label1.TabIndex = 0;
this.label1.Text = "00:00:00";
//
// clock
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.ActiveCaptionText;
this.ClientSize = new System.Drawing.Size(1191, 521);
this.Controls.Add(this.label1);
this.MaximizeBox = false;
this.Name = "clock";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Digital clock";
this.Load += new System.EventHandler(this.clock_Load);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Label label1;
}
}
| 36.439394 | 149 | 0.55343 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | gabboraron/CSharp_alapok | GUI-apps/first-v2/digitalClock/digitalClock/Form1.Designer.cs | 2,407 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DotJEM.Json.Storage.Queries.Builders
{
public static class Tester
{
public static void Testing()
{
SqlDatabaseBuilder db = new SqlDatabaseBuilder("nsw");
dynamic builder = db.Table("content");
builder
.AddColumn("Id", SqlDbType.UniqueIdentifier).NotNull()
.AddColumn("Reference", SqlDbType.VarChar)
.AddColumn("Version", SqlDbType.Int).NotNull()
.AddColumn("ContentType", SqlDbType.Int).NotNull()
.AddColumn("Created", SqlDbType.Int).NotNull()
.AddColumn("Updated", SqlDbType.Int).NotNull()
.AddColumn("Data", SqlDbType.Int).NotNull();
//command.CommandText = area.Commands["InsertHistory"];
//command.Parameters.Add(new SqlParameter(HistoryField.Fid.ToString(), SqlDbType.UniqueIdentifier)).Value = guid;
//command.Parameters.Add(new SqlParameter(StorageField.Version.ToString(), SqlDbType.Int)).Value = version;
//command.Parameters.Add(new SqlParameter(StorageField.ContentType.ToString(), SqlDbType.VarChar)).Value = contentType;
//command.Parameters.Add(new SqlParameter(HistoryField.Deleted.ToString(), SqlDbType.Bit)).Value = deleted;
//command.Parameters.Add(new SqlParameter(StorageField.Created.ToString(), SqlDbType.DateTime)).Value = created;
//command.Parameters.Add(new SqlParameter(StorageField.Updated.ToString(), SqlDbType.DateTime)).Value = updated;
//command.Parameters.Add(new SqlParameter(StorageField.Data.ToString(), SqlDbType.VarBinary)).Value = context.Serializer.Serialize(json);
}
}
public class SqlServerTableBuilder
{
private readonly SqlDatabaseBuilder db;
private readonly string name;
private readonly string schema;
public SqlServerTableBuilder(SqlDatabaseBuilder db, string name, string schema = "dbo")
{
this.db = db;
this.name = name;
this.schema = schema;
}
public SqlServerTableBuilder Column()
{
return this;
}
}
public class SqlDatabaseBuilder
{
private readonly string nsw;
private readonly string schema;
public SqlDatabaseBuilder(string nsw, string schema = "dbo")
{
this.nsw = nsw;
this.schema = schema;
}
public SqlServerTableBuilder Table(string name)
{
return Table(name, schema);
}
public SqlServerTableBuilder Table(string name, string tableSchema)
{
return new SqlServerTableBuilder(this, name, tableSchema);
}
}
}
| 35.617284 | 149 | 0.631889 | [
"MIT"
] | dotJEM/json-storage | DotJEM.Json.Storage/Queries/Builders/TableBuilder.cs | 2,887 | 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.Runtime.CompilerServices;
namespace System.Reflection
{
internal partial class ConstructorInvoker
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private unsafe object? InterpretedInvoke(object? obj, Span<object?> args, BindingFlags invokeAttr)
{
Exception exc;
object? o;
if ((invokeAttr & BindingFlags.DoNotWrapExceptions) == 0)
{
try
{
o = _method.InternalInvoke(obj, args, out exc);
}
catch (MethodAccessException)
{
throw;
}
catch (OverflowException)
{
throw;
}
catch (Exception e)
{
throw new TargetInvocationException(e);
}
}
else
{
o = _method.InternalInvoke(obj, args, out exc);
}
if (exc != null)
throw exc;
return obj == null ? o : null;
}
}
}
| 27.319149 | 106 | 0.475078 | [
"MIT"
] | ChaseKnowlden/runtime | src/mono/System.Private.CoreLib/src/System/Reflection/ConstructorInvoker.Mono.cs | 1,286 | C# |
using System.Collections.Generic;
using FSharp.Compiler.SourceCodeServices;
using JetBrains.Annotations;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.Pointers;
namespace JetBrains.ReSharper.Plugins.FSharp.Psi
{
public interface IFSharpTypeMember : IFSharpTypeParametersOwner, ITypeMember
{
[CanBeNull] FSharpSymbol Symbol { get; }
bool IsVisibleFromFSharp { get; }
bool CanNavigateTo { get; }
bool IsExtensionMember { get; }
bool IsFSharpMember { get; }
}
public interface IFSharpMember : IFSharpTypeMember
{
[CanBeNull] FSharpMemberOrFunctionOrValue Mfv { get; }
}
public interface IFSharpTypeParametersOwner : IFSharpDeclaredElement
{
IList<ITypeParameter> AllTypeParameters { get; }
}
public interface IFSharpGeneratedFromOtherElement : IFSharpDeclaredElement
{
[NotNull] IClrDeclaredElement OriginElement { get; }
IDeclaredElementPointer<IFSharpGeneratedFromOtherElement> CreatePointer();
}
}
| 27.277778 | 78 | 0.767821 | [
"Apache-2.0"
] | mcon/fsharp-support | ReSharper.FSharp/src/FSharp.Psi/src/IFSharpTypeMember.cs | 984 | C# |
using CmdLine;
using Microsoft.Diagnostics.Runtime;
using Microsoft.Diagnostics.Runtime.Interop;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace msos
{
class TriageInformation
{
public int ModuleCount { get; set; }
public ulong CommittedMemoryBytes { get; set; }
public ulong ReservedMemoryBytes { get; set; }
public ulong GCHeapMemoryBytes { get; set; }
public int ManagedThreadCount { get; set; }
public int TotalThreadCount { get; set; }
public uint FaultingThreadOSID { get; set; }
public bool IsFaultingThreadManaged { get; set; }
public string EventDescription { get; set; }
public uint ExceptionCode { get; set; }
public string ManagedExceptionType { get; set; }
public string FaultingModule { get; set; }
public string FaultingMethod { get; set; }
public string GetEventDisplayString()
{
return ManagedExceptionType ?? EventDescription.Replace(" (first/second chance not available)", "");
}
}
[Verb("triage", HelpText = "Performs basic triage of the dump file and displays results in a condensed form.")]
[SupportedTargets(TargetType.DumpFile, TargetType.DumpFileNoHeap)]
class Triage : ICommand
{
private static readonly HashSet<string> WellKnownMicrosoftModules = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase)
{
/* Windows */ "ntdll", "kernelbase", "advapi32", "gdi32", "kernel32",
/* CLR */ "clr", "mscorlib", "clrjit", "protojit", "mscorwks", "mscorsvr",
/* BCL */ "System", "System.Core"
// TODO Add more
};
private DataTarget _dbgEngTarget;
private TriageInformation _triageInformation = new TriageInformation();
[Option('s', Required = false, HelpText = "Show the faulting call stack if available.")]
public bool ShowFaultingStack { get; set; }
public void Execute(CommandExecutionContext context)
{
TriageInformation triageInformation = GetTriageInformation(context);
PrintTriageInformation(context, triageInformation);
}
private void PrintTriageInformation(CommandExecutionContext context, TriageInformation triageInformation)
{
context.WriteLine("MODULES {0} modules loaded", triageInformation.ModuleCount);
context.WriteLine("THREADS {0} total threads, {1} managed threads", triageInformation.TotalThreadCount, triageInformation.ManagedThreadCount);
context.WriteLine("MEMORY {0} committed, {1} reserved, {2} GC heap",
triageInformation.CommittedMemoryBytes.ToMemoryUnits(),
triageInformation.ReservedMemoryBytes.ToMemoryUnits(),
triageInformation.GCHeapMemoryBytes.ToMemoryUnits());
context.WriteLine("EVENT Last event in thread OSID = {0}, managed = {1}",
_triageInformation.FaultingThreadOSID, _triageInformation.IsFaultingThreadManaged);
context.WriteLine("EVENT {0}", _triageInformation.EventDescription);
if (_triageInformation.ExceptionCode != 0)
context.WriteLine("EVENT Exception {0:X8}", _triageInformation.ExceptionCode);
if (!String.IsNullOrEmpty(_triageInformation.ManagedExceptionType))
context.WriteLine("EVENT Managed exception {0}", _triageInformation.ManagedExceptionType);
context.WriteLine("EVENT Faulting module {0}, method {1}", _triageInformation.FaultingModule, _triageInformation.FaultingMethod);
}
public TriageInformation GetTriageInformation(CommandExecutionContext context)
{
using (_dbgEngTarget = context.CreateTemporaryDbgEngTarget())
{
FillModuleInformation();
FillMemoryUsageInformation(context);
FillFaultingThreadAndModuleInformation(context);
}
return _triageInformation;
}
private void FillFaultingThreadAndModuleInformation(CommandExecutionContext context)
{
UnifiedStackTraces stackTrace = new UnifiedStackTraces(_dbgEngTarget.DebuggerInterface, context);
_triageInformation.TotalThreadCount = (int)stackTrace.NumThreads;
_triageInformation.ManagedThreadCount = stackTrace.Threads.Count(t => t.IsManagedThread);
LastEventInformation lastEventInformation = _dbgEngTarget.GetLastEventInformation();
if (lastEventInformation == null)
return;
ThreadInformation faultingThread = stackTrace.Threads.SingleOrDefault(t => t.OSThreadId == lastEventInformation.OSThreadId);
if (faultingThread == null)
return;
_triageInformation.FaultingThreadOSID = faultingThread.OSThreadId;
_triageInformation.IsFaultingThreadManaged = faultingThread.IsManagedThread;
_triageInformation.EventDescription = lastEventInformation.EventDescription;
if (lastEventInformation.ExceptionRecord.HasValue)
{
_triageInformation.ExceptionCode = lastEventInformation.ExceptionRecord.Value.ExceptionCode;
}
if (faultingThread.IsManagedThread && faultingThread.ManagedThread.CurrentException != null)
{
_triageInformation.ManagedExceptionType = faultingThread.ManagedThread.CurrentException.Type.Name;
}
var frames = stackTrace.GetStackTrace(faultingThread.Index);
UnifiedStackFrame faultingFrame = frames.FirstOrDefault(f => f.Module != null && !WellKnownMicrosoftModules.Contains(f.Module));
if (faultingFrame != null)
{
_triageInformation.FaultingModule = faultingFrame.Module;
_triageInformation.FaultingMethod = faultingFrame.Method;
}
if (ShowFaultingStack)
{
context.WriteLine("Faulting call stack:");
stackTrace.PrintStackTrace(context, frames);
}
}
private void FillMemoryUsageInformation(CommandExecutionContext context)
{
var vmRegions = _dbgEngTarget.EnumerateVMRegions().ToList();
_triageInformation.CommittedMemoryBytes = (ulong)vmRegions.Sum(r => r.State == MEM.COMMIT ? (long)r.RegionSize : 0L);
_triageInformation.ReservedMemoryBytes = (ulong)vmRegions.Sum(r => r.State == MEM.RESERVE ? (long)r.RegionSize : 0L);
_triageInformation.GCHeapMemoryBytes = context.Heap.TotalHeapSize;
}
private void FillModuleInformation()
{
_triageInformation.ModuleCount = _dbgEngTarget.EnumerateModules().Count();
}
}
}
| 47.554795 | 155 | 0.664842 | [
"MIT"
] | goldshtn/msos | msos/Triage.cs | 6,945 | 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("Magical.Trevor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Magical.Trevor")]
[assembly: AssemblyCopyright("Copyright © Mike Minutillo 2011")]
[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("f9a75839-7e9b-436b-b3d8-32b9105e7400")]
// 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.*")]
[assembly: AssemblyFileVersion("1.0.*")]
| 38.135135 | 84 | 0.745571 | [
"BSD-3-Clause"
] | mikeminutillo/magicaltrevor | Magical.Trevor/Properties/AssemblyInfo.cs | 1,414 | C# |
/*
* Generated code file by Il2CppInspector - http://www.djkaty.com - https://github.com/djkaty
*/
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
// Image 46: Assembly-CSharp.dll - Assembly: Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null - Types 4339-9572
public class UISelectorWarehouse : UISelectorBase // TypeDefIndex: 8011
{
// Fields
protected static string[] faceTokensWarehouse; // 0x00
// Constructors
public UISelectorWarehouse() {} // 0x00DFE090-0x00DFE100
static UISelectorWarehouse() {} // 0x00DFE100-0x00DFE300
// Methods
public override void UpdateFace() {} // 0x00DFDAA0-0x00DFDB70
protected new void FaceNormal() {} // 0x00DFDB70-0x00DFDCB0
protected new bool FaceFocus() => default; // 0x00DFDCB0-0x00DFDDF0
protected new bool FaceSelect() => default; // 0x00DFDDF0-0x00DFDF30
protected new bool FaceDisable() => default; // 0x00DFDF30-0x00DFE070
public override float GetPrefferdWidth() => default; // 0x00DFE070-0x00DFE080
public override void ChangeWidth(float width) {} // 0x00DFE080-0x00DFE090
}
| 36.566667 | 133 | 0.758432 | [
"Unlicense"
] | tech-ticks/RTDXTools | Assets/Scripts/Stubs/Generated/Assembly-CSharp/UISelectorWarehouse.cs | 1,099 | C# |
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
namespace System.Fabric.Query
{
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Fabric.Common;
using System.Fabric.Interop;
/// <summary>
/// <para>Represents the list of <see cref="System.Fabric.Query.Application" /> retrieved by calling
/// <see cref="System.Fabric.FabricClient.QueryClient.GetApplicationListAsync(System.Uri)" />.</para>
/// </summary>
public sealed class ApplicationList : PagedList<Application>
{
/// <summary>
/// <para> Creates an application list. </para>
/// </summary>
public ApplicationList() : base()
{
}
internal ApplicationList(IList<Application> list) : base(list)
{
}
[SuppressMessage(FxCop.Category.Reliability, FxCop.Rule.RemoveCallsToGCKeepAlive, Justification = FxCop.Justification.EnsureNativeBuffersLifetime)]
internal static unsafe ApplicationList CreateFromNativeListResult(
NativeClient.IFabricGetApplicationListResult2 result)
{
var nativeList = (NativeTypes.FABRIC_APPLICATION_QUERY_RESULT_LIST*)result.get_ApplicationList();
var nativePagingStatus = (NativeTypes.FABRIC_PAGING_STATUS*)result.get_PagingStatus();
var retval = CreateFromNativeList(nativeList, nativePagingStatus);
GC.KeepAlive(result);
return retval;
}
internal static unsafe ApplicationList CreateFromNativeList(
NativeTypes.FABRIC_APPLICATION_QUERY_RESULT_LIST* nativeList,
NativeTypes.FABRIC_PAGING_STATUS* nativePagingStatus)
{
var retval = new ApplicationList();
if (nativeList != null)
{
var nativeItemArray = (NativeTypes.FABRIC_APPLICATION_QUERY_RESULT_ITEM*)nativeList->Items;
for (int i = 0; i < nativeList->Count; ++i)
{
var nativeItem = *(nativeItemArray + i);
retval.Add(Application.CreateFromNative(nativeItem));
}
}
if (nativePagingStatus != null)
{
retval.ContinuationToken = NativeTypes.FromNativeString(nativePagingStatus->ContinuationToken);
}
return retval;
}
}
} | 39.014925 | 155 | 0.609028 | [
"MIT"
] | AlkisFortuneFish/service-fabric | src/prod/src/managed/Api/src/System/Fabric/query/ApplicationList.cs | 2,614 | C# |
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using MS.Core;
namespace System.Reflection
{
public static class __AssemblyAlgorithmIdAttribute
{
public static IObservable<System.UInt32> get_AlgorithmId(
this IObservable<System.Reflection.AssemblyAlgorithmIdAttribute> AssemblyAlgorithmIdAttributeValue)
{
return Observable.Select(AssemblyAlgorithmIdAttributeValue,
(AssemblyAlgorithmIdAttributeValueLambda) => AssemblyAlgorithmIdAttributeValueLambda.AlgorithmId);
}
}
} | 34.111111 | 114 | 0.757329 | [
"MIT"
] | RixianOpenTech/RxWrappers | Source/Wrappers/mscorlib/System.Reflection.AssemblyAlgorithmIdAttribute.cs | 614 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading;
namespace EasyTest
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
Assert.IsTrue(true);
//Assert.AreEqual(ApartmentState.STA, Thread.CurrentThread.GetApartmentState());
}
}
}
| 20.941176 | 92 | 0.634831 | [
"MIT"
] | diginsight/telemetry | Tests/EasyTest/UnitTest1.cs | 356 | C# |
using Project2D.Control;
using Project2D.Core;
using UnityEngine;
namespace Project2D.Interactables
{
public class Coin : MonoBehaviour
{
[Header("Coin Values")]
[SerializeField] private AudioClip pickupSound;
[SerializeField] private int coinValue;
[SerializeField] private GameManager gameManager;
[SerializeField] private AudioManager audioManager;
private void Start()
{
gameManager = FindObjectOfType<GameManager>();
audioManager = FindObjectOfType<AudioManager>();
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.GetComponent<PlayerController>())
{
Destroy(gameObject);
audioManager.Play(pickupSound);
gameManager.AddCoins(coinValue);
}
}
}
} | 27.71875 | 60 | 0.612176 | [
"MIT"
] | theADAMJR/PROJECT-2D | Assets/Scripts/Interactables/Coin.cs | 889 | C# |
using System;
using System.Collections.Generic;
namespace ET
{
//枚举值一定要对应界面表(UIConfig)中的id!!!!!
public enum UIType
{
UILogin = 1,
UILobby = 2,
}
} | 14.75 | 36 | 0.59887 | [
"MIT"
] | benboerbadebaboerben/GEFramework | Unity/Codes/ModelView/Module/UI/UIType.cs | 219 | 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 codedeploy-2014-10-06.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.CodeDeploy.Model
{
/// <summary>
/// Information about minimum healthy instance.
/// </summary>
public partial class MinimumHealthyHosts
{
private MinimumHealthyHostsType _type;
private int? _value;
/// <summary>
/// Gets and sets the property Type.
/// <para>
/// The minimum healthy instance type:
/// </para>
/// <ul> <li>HOST_COUNT: The minimum number of healthy instance as an absolute value.</li>
/// <li>FLEET_PERCENT: The minimum number of healthy instance as a percentage of the total
/// number of instance in the deployment.</li> </ul>
/// <para>
/// In an example of nine instance, if a HOST_COUNT of six is specified, deploy to up
/// to three instances at a time. The deployment will be successful if six or more instances
/// are deployed to successfully; otherwise, the deployment fails. If a FLEET_PERCENT
/// of 40 is specified, deploy to up to five instance at a time. The deployment will be
/// successful if four or more instance are deployed to successfully; otherwise, the deployment
/// fails.
/// </para>
/// <note>In a call to the get deployment configuration operation, CodeDeployDefault.OneAtATime
/// will return a minimum healthy instance type of MOST_CONCURRENCY and a value of 1.
/// This means a deployment to only one instance at a time. (You cannot set the type to
/// MOST_CONCURRENCY, only to HOST_COUNT or FLEET_PERCENT.) In addition, with CodeDeployDefault.OneAtATime,
/// AWS CodeDeploy will try to ensure that all instances but one are kept in a healthy
/// state during the deployment. Although this allows one instance at a time to be taken
/// offline for a new deployment, it also means that if the deployment to the last instance
/// fails, the overall deployment still succeeds.</note>
/// </summary>
public MinimumHealthyHostsType Type
{
get { return this._type; }
set { this._type = value; }
}
// Check to see if Type property is set
internal bool IsSetType()
{
return this._type != null;
}
/// <summary>
/// Gets and sets the property Value.
/// <para>
/// The minimum healthy instance value.
/// </para>
/// </summary>
public int Value
{
get { return this._value.GetValueOrDefault(); }
set { this._value = value; }
}
// Check to see if Value property is set
internal bool IsSetValue()
{
return this._value.HasValue;
}
}
} | 38.808511 | 115 | 0.640899 | [
"Apache-2.0"
] | SaschaHaertel/AmazonAWS | sdk/src/Services/CodeDeploy/Generated/Model/MinimumHealthyHosts.cs | 3,648 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Windows.UI.Xaml.Media;
using Windows.UI;
#if XAMARIN_IOS_UNIFIED
using GenericColor = UIKit.UIColor;
using UIKit;
#elif XAMARIN_IOS
using GenericColor = MonoTouch.UIKit.UIColor;
using MonoTouch.UIKit;
#elif XAMARIN_ANDROID
using GenericColor = Android.Graphics.Color;
#elif NETFX_CORE
using Windows.UI.Xaml.Media;
using GenericColor = Windows.UI.Color;
using Windows.UI;
#elif __MACOS__
using GenericColor = Windows.UI.Color;
#else
using GenericColor = System.Drawing.Color;
#endif
namespace Windows.UI.Xaml
{
public static class SolidColorBrushHelper
{
#if XAMARIN_IOS
public static SolidColorBrush FromARGB(byte a, byte r, byte g, byte b)
{
return new SolidColorBrush(UIColor.FromRGBA(r, g, b, a));
}
#elif XAMARIN_ANDROID
public static SolidColorBrush FromARGB(byte a, byte r, byte g, byte b)
{
return new SolidColorBrush(Android.Graphics.Color.Argb(a, r, g, b));
}
#else
public static SolidColorBrush FromARGB(byte a, byte r, byte g, byte b)
{
return new SolidColorBrush(Windows.UI.Color.FromArgb(a, r, g, b));
}
#endif
/// <summary>
/// Takes a color code as an ARGB or RGB string and returns a solid color brush.
///
/// Remark: if single digits are used to define the color, they will
/// be duplicated (example: FFD8 will become FFFFDD88)
/// </summary>
public static SolidColorBrush FromARGB(string colorCode)
{
return new SolidColorBrush(Colors.Parse(colorCode));
}
/// <summary>
/// Takes a color code as an ARGB or RGB, or textual string from <see cref="Colors"/> string and returns a solid color brush.
///
/// Remark: if single digits are used to define the color, they will
/// be duplicated (example: FFD8 will become FFFFDD88)
/// </summary>
public static SolidColorBrush Parse(string colorCode)
{
return new SolidColorBrush(Colors.Parse(colorCode));
}
/// <summary>
/// Takes a standard color name (E.G. White) and returns a solid color brush
/// </summary>
public static SolidColorBrush FromName(string colorName)
{
// I know, I don't like it either. Need to check for perf.
switch (colorName)
{
case "Transparent":
return Transparent;
case "AliceBlue":
return AliceBlue;
case "AntiqueWhite":
return AntiqueWhite;
case "Aqua":
return Aqua;
case "Aquamarine":
return Aquamarine;
case "Azure":
return Azure;
case "Beige":
return Beige;
case "Bisque":
return Bisque;
case "Black":
return Black;
case "BlanchedAlmond":
return BlanchedAlmond;
case "Blue":
return Blue;
case "BlueViolet":
return BlueViolet;
case "Brown":
return Brown;
case "BurlyWood":
return BurlyWood;
case "CadetBlue":
return CadetBlue;
case "Chartreuse":
return Chartreuse;
case "Chocolate":
return Chocolate;
case "Coral":
return Coral;
case "CornflowerBlue":
return CornflowerBlue;
case "Cornsilk":
return Cornsilk;
case "Crimson":
return Crimson;
case "Cyan":
return Cyan;
case "DarkBlue":
return DarkBlue;
case "DarkCyan":
return DarkCyan;
case "DarkGoldenrod":
case "DarkGoldenRod":
return DarkGoldenrod;
case "DarkGray":
return DarkGray;
case "DarkGreen":
return DarkGreen;
case "DarkKhaki":
return DarkKhaki;
case "DarkMagenta":
return DarkMagenta;
case "DarkOliveGreen":
return DarkOliveGreen;
case "DarkOrange":
return DarkOrange;
case "DarkOrchid":
return DarkOrchid;
case "DarkRed":
return DarkRed;
case "DarkSalmon":
return DarkSalmon;
case "DarkSeaGreen":
return DarkSeaGreen;
case "DarkSlateBlue":
return DarkSlateBlue;
case "DarkSlateGray":
return DarkSlateGray;
case "DarkTurquoise":
return DarkTurquoise;
case "DarkViolet":
return DarkViolet;
case "DeepPink":
return DeepPink;
case "DeepSkyBlue":
return DeepSkyBlue;
case "DimGray":
return DimGray;
case "DodgerBlue":
return DodgerBlue;
case "Firebrick":
return Firebrick;
case "FloralWhite":
return FloralWhite;
case "ForestGreen":
return ForestGreen;
case "Fuchsia":
return Fuchsia;
case "Gainsboro":
return Gainsboro;
case "GhostWhite":
return GhostWhite;
case "Gold":
return Gold;
case "Goldenrod":
case "GoldenRod":
return Goldenrod;
case "Gray":
return Gray;
case "Green":
return Green;
case "GreenYellow":
return GreenYellow;
case "Honeydew":
return Honeydew;
case "HotPink":
return HotPink;
case "IndianRed":
return IndianRed;
case "Indigo":
return Indigo;
case "Ivory":
return Ivory;
case "Khaki":
return Khaki;
case "Lavender":
return Lavender;
case "LavenderBlush":
return LavenderBlush;
case "LawnGreen":
return LawnGreen;
case "LemonChiffon":
return LemonChiffon;
case "LightBlue":
return LightBlue;
case "LightCoral":
return LightCoral;
case "LightCyan":
return LightCyan;
case "LightGoldenrodYellow":
case "LightGoldenRodYellow":
return LightGoldenrodYellow;
case "LightGray":
return LightGray;
case "LightGreen":
return LightGreen;
case "LightPink":
return LightPink;
case "LightSalmon":
return LightSalmon;
case "LightSeaGreen":
return LightSeaGreen;
case "LightSkyBlue":
return LightSkyBlue;
case "LightSlateGray":
return LightSlateGray;
case "LightSteelBlue":
return LightSteelBlue;
case "LightYellow":
return LightYellow;
case "Lime":
return Lime;
case "LimeGreen":
return LimeGreen;
case "Linen":
return Linen;
case "Magenta":
return Magenta;
case "Maroon":
return Maroon;
case "MediumAquamarine":
return MediumAquamarine;
case "MediumBlue":
return MediumBlue;
case "MediumOrchid":
return MediumOrchid;
case "MediumPurple":
return MediumPurple;
case "MediumSeaGreen":
return MediumSeaGreen;
case "MediumSlateBlue":
return MediumSlateBlue;
case "MediumSpringGreen":
return MediumSpringGreen;
case "MediumTurquoise":
return MediumTurquoise;
case "MediumVioletRed":
return MediumVioletRed;
case "MidnightBlue":
return MidnightBlue;
case "MintCream":
return MintCream;
case "MistyRose":
return MistyRose;
case "Moccasin":
return Moccasin;
case "NavajoWhite":
return NavajoWhite;
case "Navy":
return Navy;
case "OldLace":
return OldLace;
case "Olive":
return Olive;
case "OliveDrab":
return OliveDrab;
case "Orange":
return Orange;
case "OrangeRed":
return OrangeRed;
case "Orchid":
return Orchid;
case "PaleGoldenrod":
case "PaleGoldenRod":
return PaleGoldenrod;
case "PaleGreen":
return PaleGreen;
case "PaleTurquoise":
return PaleTurquoise;
case "PaleVioletRed":
return PaleVioletRed;
case "PapayaWhip":
return PapayaWhip;
case "PeachPuff":
return PeachPuff;
case "Peru":
return Peru;
case "Pink":
return Pink;
case "Plum":
return Plum;
case "PowderBlue":
return PowderBlue;
case "Purple":
return Purple;
case "Red":
return Red;
case "RosyBrown":
return RosyBrown;
case "RoyalBlue":
return RoyalBlue;
case "SaddleBrown":
return SaddleBrown;
case "Salmon":
return Salmon;
case "SandyBrown":
return SandyBrown;
case "SeaGreen":
return SeaGreen;
case "SeaShell":
return SeaShell;
case "Sienna":
return Sienna;
case "Silver":
return Silver;
case "SkyBlue":
return SkyBlue;
case "SlateBlue":
return SlateBlue;
case "SlateGray":
return SlateGray;
case "Snow":
return Snow;
case "SpringGreen":
return SpringGreen;
case "SteelBlue":
return SteelBlue;
case "Tan":
return Tan;
case "Teal":
return Teal;
case "Thistle":
return Thistle;
case "Tomato":
return Tomato;
case "Turquoise":
return Turquoise;
case "Violet":
return Violet;
case "Wheat":
return Wheat;
case "White":
return White;
case "WhiteSmoke":
return WhiteSmoke;
case "Yellow":
return Yellow;
case "YellowGreen":
return YellowGreen;
default:
throw new ArgumentOutOfRangeException("There is no default Brush with the name " + colorName);
};
}
public static SolidColorBrush Transparent => new SolidColorBrush(Colors.Transparent);
public static SolidColorBrush AliceBlue => new SolidColorBrush(Colors.AliceBlue);
public static SolidColorBrush AntiqueWhite => new SolidColorBrush(Colors.AntiqueWhite);
public static SolidColorBrush Aqua => new SolidColorBrush(Colors.Aqua);
public static SolidColorBrush Aquamarine => new SolidColorBrush(Colors.Aquamarine);
public static SolidColorBrush Azure => new SolidColorBrush(Colors.Azure);
public static SolidColorBrush Beige => new SolidColorBrush(Colors.Beige);
public static SolidColorBrush Bisque => new SolidColorBrush(Colors.Bisque);
public static SolidColorBrush Black => new SolidColorBrush(Colors.Black);
public static SolidColorBrush BlanchedAlmond => new SolidColorBrush(Colors.BlanchedAlmond);
public static SolidColorBrush Blue => new SolidColorBrush(Colors.Blue);
public static SolidColorBrush BlueViolet => new SolidColorBrush(Colors.BlueViolet);
public static SolidColorBrush Brown => new SolidColorBrush(Colors.Brown);
public static SolidColorBrush BurlyWood => new SolidColorBrush(Colors.BurlyWood);
public static SolidColorBrush CadetBlue => new SolidColorBrush(Colors.CadetBlue);
public static SolidColorBrush Chartreuse => new SolidColorBrush(Colors.Chartreuse);
public static SolidColorBrush Chocolate => new SolidColorBrush(Colors.Chocolate);
public static SolidColorBrush Coral => new SolidColorBrush(Colors.Coral);
public static SolidColorBrush CornflowerBlue => new SolidColorBrush(Colors.CornflowerBlue);
public static SolidColorBrush Cornsilk => new SolidColorBrush(Colors.Cornsilk);
public static SolidColorBrush Crimson => new SolidColorBrush(Colors.Crimson);
public static SolidColorBrush Cyan => new SolidColorBrush(Colors.Cyan);
public static SolidColorBrush DarkBlue => new SolidColorBrush(Colors.DarkBlue);
public static SolidColorBrush DarkCyan => new SolidColorBrush(Colors.DarkCyan);
public static SolidColorBrush DarkGoldenrod => new SolidColorBrush(Colors.DarkGoldenrod);
public static SolidColorBrush DarkGray => new SolidColorBrush(Colors.DarkGray);
public static SolidColorBrush DarkGreen => new SolidColorBrush(Colors.DarkGreen);
public static SolidColorBrush DarkKhaki => new SolidColorBrush(Colors.DarkKhaki);
public static SolidColorBrush DarkMagenta => new SolidColorBrush(Colors.DarkMagenta);
public static SolidColorBrush DarkOliveGreen => new SolidColorBrush(Colors.DarkOliveGreen);
public static SolidColorBrush DarkOrange => new SolidColorBrush(Colors.DarkOrange);
public static SolidColorBrush DarkOrchid => new SolidColorBrush(Colors.DarkOrchid);
public static SolidColorBrush DarkRed => new SolidColorBrush(Colors.DarkRed);
public static SolidColorBrush DarkSalmon => new SolidColorBrush(Colors.DarkSalmon);
public static SolidColorBrush DarkSeaGreen => new SolidColorBrush(Colors.DarkSeaGreen);
public static SolidColorBrush DarkSlateBlue => new SolidColorBrush(Colors.DarkSlateBlue);
public static SolidColorBrush DarkSlateGray => new SolidColorBrush(Colors.DarkSlateGray);
public static SolidColorBrush DarkTurquoise => new SolidColorBrush(Colors.DarkTurquoise);
public static SolidColorBrush DarkViolet => new SolidColorBrush(Colors.DarkViolet);
public static SolidColorBrush DeepPink => new SolidColorBrush(Colors.DeepPink);
public static SolidColorBrush DeepSkyBlue => new SolidColorBrush(Colors.DeepSkyBlue);
public static SolidColorBrush DimGray => new SolidColorBrush(Colors.DimGray);
public static SolidColorBrush DodgerBlue => new SolidColorBrush(Colors.DodgerBlue);
public static SolidColorBrush Firebrick => new SolidColorBrush(Colors.Firebrick);
public static SolidColorBrush FloralWhite => new SolidColorBrush(Colors.FloralWhite);
public static SolidColorBrush ForestGreen => new SolidColorBrush(Colors.ForestGreen);
public static SolidColorBrush Fuchsia => new SolidColorBrush(Colors.Fuchsia);
public static SolidColorBrush Gainsboro => new SolidColorBrush(Colors.Gainsboro);
public static SolidColorBrush GhostWhite => new SolidColorBrush(Colors.GhostWhite);
public static SolidColorBrush Gold => new SolidColorBrush(Colors.Gold);
public static SolidColorBrush Goldenrod => new SolidColorBrush(Colors.Goldenrod);
public static SolidColorBrush Gray => new SolidColorBrush(Colors.Gray);
public static SolidColorBrush Green => new SolidColorBrush(Colors.Green);
public static SolidColorBrush GreenYellow => new SolidColorBrush(Colors.GreenYellow);
public static SolidColorBrush Honeydew => new SolidColorBrush(Colors.Honeydew);
public static SolidColorBrush HotPink => new SolidColorBrush(Colors.HotPink);
public static SolidColorBrush IndianRed => new SolidColorBrush(Colors.IndianRed);
public static SolidColorBrush Indigo => new SolidColorBrush(Colors.Indigo);
public static SolidColorBrush Ivory => new SolidColorBrush(Colors.Ivory);
public static SolidColorBrush Khaki => new SolidColorBrush(Colors.Khaki);
public static SolidColorBrush Lavender => new SolidColorBrush(Colors.Lavender);
public static SolidColorBrush LavenderBlush => new SolidColorBrush(Colors.LavenderBlush);
public static SolidColorBrush LawnGreen => new SolidColorBrush(Colors.LawnGreen);
public static SolidColorBrush LemonChiffon => new SolidColorBrush(Colors.LemonChiffon);
public static SolidColorBrush LightBlue => new SolidColorBrush(Colors.LightBlue);
public static SolidColorBrush LightCoral => new SolidColorBrush(Colors.LightCoral);
public static SolidColorBrush LightCyan => new SolidColorBrush(Colors.LightCyan);
public static SolidColorBrush LightGoldenrodYellow => new SolidColorBrush(Colors.LightGoldenrodYellow);
public static SolidColorBrush LightGray => new SolidColorBrush(Colors.LightGray);
public static SolidColorBrush LightGreen => new SolidColorBrush(Colors.LightGreen);
public static SolidColorBrush LightPink => new SolidColorBrush(Colors.LightPink);
public static SolidColorBrush LightSalmon => new SolidColorBrush(Colors.LightSalmon);
public static SolidColorBrush LightSeaGreen => new SolidColorBrush(Colors.LightSeaGreen);
public static SolidColorBrush LightSkyBlue => new SolidColorBrush(Colors.LightSkyBlue);
public static SolidColorBrush LightSlateGray => new SolidColorBrush(Colors.LightSlateGray);
public static SolidColorBrush LightSteelBlue => new SolidColorBrush(Colors.LightSteelBlue);
public static SolidColorBrush LightYellow => new SolidColorBrush(Colors.LightYellow);
public static SolidColorBrush Lime => new SolidColorBrush(Colors.Lime);
public static SolidColorBrush LimeGreen => new SolidColorBrush(Colors.LimeGreen);
public static SolidColorBrush Linen => new SolidColorBrush(Colors.Linen);
public static SolidColorBrush Magenta => new SolidColorBrush(Colors.Magenta);
public static SolidColorBrush Maroon => new SolidColorBrush(Colors.Maroon);
public static SolidColorBrush MediumAquamarine => new SolidColorBrush(Colors.MediumAquamarine);
public static SolidColorBrush MediumBlue => new SolidColorBrush(Colors.MediumBlue);
public static SolidColorBrush MediumOrchid => new SolidColorBrush(Colors.MediumOrchid);
public static SolidColorBrush MediumPurple => new SolidColorBrush(Colors.MediumPurple);
public static SolidColorBrush MediumSeaGreen => new SolidColorBrush(Colors.MediumSeaGreen);
public static SolidColorBrush MediumSlateBlue => new SolidColorBrush(Colors.MediumSlateBlue);
public static SolidColorBrush MediumSpringGreen => new SolidColorBrush(Colors.MediumSpringGreen);
public static SolidColorBrush MediumTurquoise => new SolidColorBrush(Colors.MediumTurquoise);
public static SolidColorBrush MediumVioletRed => new SolidColorBrush(Colors.MediumVioletRed);
public static SolidColorBrush MidnightBlue => new SolidColorBrush(Colors.MidnightBlue);
public static SolidColorBrush MintCream => new SolidColorBrush(Colors.MintCream);
public static SolidColorBrush MistyRose => new SolidColorBrush(Colors.MistyRose);
public static SolidColorBrush Moccasin => new SolidColorBrush(Colors.Moccasin);
public static SolidColorBrush NavajoWhite => new SolidColorBrush(Colors.NavajoWhite);
public static SolidColorBrush Navy => new SolidColorBrush(Colors.Navy);
public static SolidColorBrush OldLace => new SolidColorBrush(Colors.OldLace);
public static SolidColorBrush Olive => new SolidColorBrush(Colors.Olive);
public static SolidColorBrush OliveDrab => new SolidColorBrush(Colors.OliveDrab);
public static SolidColorBrush Orange => new SolidColorBrush(Colors.Orange);
public static SolidColorBrush OrangeRed => new SolidColorBrush(Colors.OrangeRed);
public static SolidColorBrush Orchid => new SolidColorBrush(Colors.Orchid);
public static SolidColorBrush PaleGoldenrod => new SolidColorBrush(Colors.PaleGoldenrod);
public static SolidColorBrush PaleGreen => new SolidColorBrush(Colors.PaleGreen);
public static SolidColorBrush PaleTurquoise => new SolidColorBrush(Colors.PaleTurquoise);
public static SolidColorBrush PaleVioletRed => new SolidColorBrush(Colors.PaleVioletRed);
public static SolidColorBrush PapayaWhip => new SolidColorBrush(Colors.PapayaWhip);
public static SolidColorBrush PeachPuff => new SolidColorBrush(Colors.PeachPuff);
public static SolidColorBrush Peru => new SolidColorBrush(Colors.Peru);
public static SolidColorBrush Pink => new SolidColorBrush(Colors.Pink);
public static SolidColorBrush Plum => new SolidColorBrush(Colors.Plum);
public static SolidColorBrush PowderBlue => new SolidColorBrush(Colors.PowderBlue);
public static SolidColorBrush Purple => new SolidColorBrush(Colors.Purple);
public static SolidColorBrush Red => new SolidColorBrush(Colors.Red);
public static SolidColorBrush RosyBrown => new SolidColorBrush(Colors.RosyBrown);
public static SolidColorBrush RoyalBlue => new SolidColorBrush(Colors.RoyalBlue);
public static SolidColorBrush SaddleBrown => new SolidColorBrush(Colors.SaddleBrown);
public static SolidColorBrush Salmon => new SolidColorBrush(Colors.Salmon);
public static SolidColorBrush SandyBrown => new SolidColorBrush(Colors.SandyBrown);
public static SolidColorBrush SeaGreen => new SolidColorBrush(Colors.SeaGreen);
public static SolidColorBrush SeaShell => new SolidColorBrush(Colors.SeaShell);
public static SolidColorBrush Sienna => new SolidColorBrush(Colors.Sienna);
public static SolidColorBrush Silver => new SolidColorBrush(Colors.Silver);
public static SolidColorBrush SkyBlue => new SolidColorBrush(Colors.SkyBlue);
public static SolidColorBrush SlateBlue => new SolidColorBrush(Colors.SlateBlue);
public static SolidColorBrush SlateGray => new SolidColorBrush(Colors.SlateGray);
public static SolidColorBrush Snow => new SolidColorBrush(Colors.Snow);
public static SolidColorBrush SpringGreen => new SolidColorBrush(Colors.SpringGreen);
public static SolidColorBrush SteelBlue => new SolidColorBrush(Colors.SteelBlue);
public static SolidColorBrush Tan => new SolidColorBrush(Colors.Tan);
public static SolidColorBrush Teal => new SolidColorBrush(Colors.Teal);
public static SolidColorBrush Thistle => new SolidColorBrush(Colors.Thistle);
public static SolidColorBrush Tomato => new SolidColorBrush(Colors.Tomato);
public static SolidColorBrush Turquoise => new SolidColorBrush(Colors.Turquoise);
public static SolidColorBrush Violet => new SolidColorBrush(Colors.Violet);
public static SolidColorBrush Wheat => new SolidColorBrush(Colors.Wheat);
public static SolidColorBrush White => new SolidColorBrush(Colors.White);
public static SolidColorBrush WhiteSmoke => new SolidColorBrush(Colors.WhiteSmoke);
public static SolidColorBrush Yellow => new SolidColorBrush(Colors.Yellow);
public static SolidColorBrush YellowGreen => new SolidColorBrush(Colors.YellowGreen);
}
}
| 40.482353 | 128 | 0.744164 | [
"Apache-2.0"
] | AbdalaMask/uno | src/Uno.UI/UI/Xaml/SolidColorBrushHelper.cs | 20,648 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ElectronicObserver.Data
{
/// <summary>
/// 基地航空隊のデータを扱います。
/// </summary>
public class BaseAirCorpsData : APIWrapper, IIdentifiable
{
/// <summary>
/// 飛行場が存在する海域ID
/// </summary>
public int MapAreaID => RawData.api_area_id() ? (int)RawData.api_area_id : -1;
/// <summary>
/// 航空隊ID
/// </summary>
public int AirCorpsID => (int)RawData.api_rid;
/// <summary>
/// 航空隊名
/// </summary>
public string Name { get; private set; }
/// <summary>
/// 戦闘行動半径
/// </summary>
public int Distance { get; private set; }
/// <summary>
/// 行動指示
/// 0=待機, 1=出撃, 2=防空, 3=退避, 4=休息
/// </summary>
public int ActionKind { get; private set; }
/// <summary>
/// 航空中隊情報
/// </summary>
public IDDictionary<BaseAirCorpsSquadron> Squadrons { get; private set; }
public BaseAirCorpsSquadron this[int i] => Squadrons[i];
public BaseAirCorpsData()
{
Squadrons = new IDDictionary<BaseAirCorpsSquadron>();
}
public override void LoadFromRequest(string apiname, Dictionary<string, string> data)
{
base.LoadFromRequest(apiname, data);
switch (apiname)
{
case "api_req_air_corps/change_name":
Name = data["api_name"];
break;
case "api_req_air_corps/set_action":
{
int[] ids = data["api_base_id"].Split(",".ToCharArray()).Select(s => int.Parse(s)).ToArray();
int[] actions = data["api_action_kind"].Split(",".ToCharArray()).Select(s => int.Parse(s)).ToArray();
int index = Array.IndexOf(ids, AirCorpsID);
if (index >= 0)
{
ActionKind = actions[index];
}
}
break;
}
}
public override void LoadFromResponse(string apiname, dynamic data)
{
switch (apiname)
{
case "api_get_member/base_air_corps":
default:
base.LoadFromResponse(apiname, (object)data);
Name = (string)data.api_name;
Distance = (int)data.api_distance.api_base + (int)data.api_distance.api_bonus;
ActionKind = (int)data.api_action_kind;
SetSquadrons(apiname, data.api_plane_info);
break;
case "api_req_air_corps/set_plane":
{
var prev = Squadrons.Values.Select(sq => sq != null && sq.State == 1 ? sq.EquipmentMasterID : 0).ToArray();
SetSquadrons(apiname, data.api_plane_info);
foreach (var deleted in prev.Except(Squadrons.Values.Select(sq => sq != null && sq.State == 1 ? sq.EquipmentMasterID : 0)))
{
var eq = KCDatabase.Instance.Equipments[deleted];
if (eq != null)
{
KCDatabase.Instance.RelocatedEquipments.Add(new RelocationData(deleted, DateTime.Now));
}
}
Distance = (int)data.api_distance.api_base + (int)data.api_distance.api_bonus;
}
break;
case "api_req_air_corps/supply":
SetSquadrons(apiname, data.api_plane_info);
break;
}
}
private void SetSquadrons(string apiname, dynamic data)
{
foreach (var elem in data)
{
int id = (int)elem.api_squadron_id;
if (!Squadrons.ContainsKey(id))
{
var a = new BaseAirCorpsSquadron();
a.LoadFromResponse(apiname, elem);
Squadrons.Add(a);
}
else
{
Squadrons[id].LoadFromResponse(apiname, elem);
}
}
}
public override string ToString() => $"[{MapAreaID}:{AirCorpsID}] {Name}";
public int ID => GetID(RawData);
public static int GetID(int mapAreaID, int airCorpsID) => mapAreaID * 10 + airCorpsID;
public static int GetID(Dictionary<string, string> request)
=> GetID(int.Parse(request["api_area_id"]), int.Parse(request["api_base_id"]));
public static int GetID(dynamic response)
=> GetID(response.api_area_id() ? (int)response.api_area_id : -1, (int)response.api_rid);
}
}
| 22.2 | 129 | 0.645817 | [
"MIT"
] | SkywalkerJi/ElectronicObserver | ElectronicObserver/Data/BaseAirCorpsData.cs | 4,003 | C# |
namespace EnvironmentMapDemo
{
using System;
using System.Windows.Controls;
using System.Windows.Data;
using HelixToolkit.Wpf.SharpDX;
/// <summary>
/// Interaction logic for MaterialControl.xaml
/// </summary>
public partial class MaterialControl : UserControl
{
public MaterialControl()
{
InitializeComponent();
}
}
public class ColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var c = (global::SharpDX.Color4)value;
return c.ToColor();
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var c = (System.Windows.Media.Color)value;
return c.ToColor4();
}
}
}
| 27.8 | 125 | 0.589928 | [
"MIT"
] | smallholexu/helix-toolkit | Source/Examples/WPF.SharpDX/EnvironmentMapDemo/MaterialControl.xaml.cs | 975 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Net;
namespace Contoso.GameNetCore.Proto.Features
{
public class ProtoConnectionFeature : IProtoConnectionFeature
{
public string ConnectionId { get; set; }
public IPAddress LocalIpAddress { get; set; }
public int LocalPort { get; set; }
public IPAddress RemoteIpAddress { get; set; }
public int RemotePort { get; set; }
}
} | 29.05 | 112 | 0.667814 | [
"Apache-2.0"
] | bclnet/GameNetCore | src/Proto/Proto/src/Features/HttpConnectionFeature.cs | 581 | C# |
using System;
using BashIm;
namespace BashImExample2
{
class Program
{
static void Main(string[] args)
{
while (true)
{
Console.Write("Введите номер цитаты, чтобы загрузить её: ");
var quoteIdStr = Console.ReadLine();
int quoteId;
if (!int.TryParse(quoteIdStr, out quoteId))
{
Console.WriteLine("Не удаётся распознать номер.");
continue;
}
var quote = Quote.GetQuoteById(quoteId);
if (quote == null)
{
Console.WriteLine("Не удалось найти цитату.");
continue;
}
Console.WriteLine($"#{quote.Id}");
Console.WriteLine($"Рейтинг {quote.Rating}");
Console.WriteLine($"Создана {quote.CreatedAt}");
Console.WriteLine(" ");
Console.WriteLine(quote.Text);
}
}
}
} | 30.111111 | 77 | 0.440037 | [
"MIT"
] | CrazyHackGUT/bashim | BashImExample2/Program.cs | 1,178 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Text2 : MonoBehaviour {
//进入宿主后的颜色变化
private GUIText m_GUIText;
private Transform m_Transform;
private Color m_Color;
void Start()
{
m_GUIText = gameObject.GetComponent<GUIText>();
m_Transform = gameObject.GetComponent<Transform>();
m_Color = m_GUIText.color;
}
private void OnMouseEnter()
{
m_GUIText.color = Color.green;
}
private void OnMouseExit()
{
m_GUIText.color = m_Color;
}
private void OnMouseDown()
{
m_GUIText.color = Color.black;
}
private void OnMouseDrag()
{
// m_Transform.position(0, 0, 0);
}
}
| 21.2 | 59 | 0.626685 | [
"MIT"
] | zzf/ShaderProgramProj | Assets/Scripts/Text2.cs | 764 | 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 swf-2012-01-25.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.SimpleWorkflow.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.SimpleWorkflow.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for TimerFiredEventAttributes Object
/// </summary>
public class TimerFiredEventAttributesUnmarshaller : IUnmarshaller<TimerFiredEventAttributes, XmlUnmarshallerContext>, IUnmarshaller<TimerFiredEventAttributes, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
TimerFiredEventAttributes IUnmarshaller<TimerFiredEventAttributes, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
{
throw new NotImplementedException();
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public TimerFiredEventAttributes Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
if (context.CurrentTokenType == JsonToken.Null)
return null;
TimerFiredEventAttributes unmarshalledObject = new TimerFiredEventAttributes();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("startedEventId", targetDepth))
{
var unmarshaller = LongUnmarshaller.Instance;
unmarshalledObject.StartedEventId = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("timerId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.TimerId = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static TimerFiredEventAttributesUnmarshaller _instance = new TimerFiredEventAttributesUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static TimerFiredEventAttributesUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 35.77551 | 188 | 0.644039 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/SimpleWorkflow/Generated/Model/Internal/MarshallTransformations/TimerFiredEventAttributesUnmarshaller.cs | 3,506 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace LessPaper.Shared.Enums
{
public enum TagSource
{
User,
Auto,
}
}
| 13.230769 | 33 | 0.645349 | [
"MIT"
] | ChristianHellwig/LessPaper.Shared | LessPaper.Shared/Enums/TagSource.cs | 174 | C# |
using System.Net.Http;
using System.Web.Http;
namespace MvcRouteTester.Test.ApiControllers
{
public class WithNullableController : ApiController
{
public HttpResponseMessage Get(int? id)
{
return new HttpResponseMessage();
}
}
}
| 17.357143 | 52 | 0.757202 | [
"Apache-2.0"
] | AnthonySteele/MvcRouteTester | src/MvcRouteTester.Test/ApiControllers/WithNullableController.cs | 245 | C# |
namespace CohesionAndCoupling
{
using System;
public static class FileUtils
{
public static string GetFileExtension(string fileName)
{
int indexOfLastDot = fileName.LastIndexOf(".", StringComparison.Ordinal);
if (indexOfLastDot == -1)
{
return "No extension";
}
string extension = fileName.Substring(indexOfLastDot + 1);
return extension;
}
public static string GetFileNameWithoutExtension(string fileName)
{
int indexOfLastDot = fileName.LastIndexOf(".", StringComparison.Ordinal);
if (indexOfLastDot == -1)
{
return fileName;
}
string nameOfFile = fileName.Substring(0, indexOfLastDot);
return nameOfFile;
}
}
}
| 24.055556 | 85 | 0.555427 | [
"MIT"
] | jsdelivrbot/Telerik-Academy-Homeworks | Module 2/01_High Quality Code/08. High-quality Classes/Cohesion-and-Coupling/FileUtils.cs | 868 | C# |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using PureCloudPlatform.Client.V2.Client;
namespace PureCloudPlatform.Client.V2.Model
{
/// <summary>
/// AuditChange
/// </summary>
[DataContract]
public partial class AuditChange : IEquatable<AuditChange>
{
/// <summary>
/// Initializes a new instance of the <see cref="AuditChange" /> class.
/// </summary>
/// <param name="Property">Property.</param>
/// <param name="Entity">Entity.</param>
/// <param name="OldValues">OldValues.</param>
/// <param name="NewValues">NewValues.</param>
public AuditChange(string Property = null, AuditEntityReference Entity = null, List<string> OldValues = null, List<string> NewValues = null)
{
this.Property = Property;
this.Entity = Entity;
this.OldValues = OldValues;
this.NewValues = NewValues;
}
/// <summary>
/// Gets or Sets Property
/// </summary>
[DataMember(Name="property", EmitDefaultValue=false)]
public string Property { get; set; }
/// <summary>
/// Gets or Sets Entity
/// </summary>
[DataMember(Name="entity", EmitDefaultValue=false)]
public AuditEntityReference Entity { get; set; }
/// <summary>
/// Gets or Sets OldValues
/// </summary>
[DataMember(Name="oldValues", EmitDefaultValue=false)]
public List<string> OldValues { get; set; }
/// <summary>
/// Gets or Sets NewValues
/// </summary>
[DataMember(Name="newValues", EmitDefaultValue=false)]
public List<string> NewValues { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class AuditChange {\n");
sb.Append(" Property: ").Append(Property).Append("\n");
sb.Append(" Entity: ").Append(Entity).Append("\n");
sb.Append(" OldValues: ").Append(OldValues).Append("\n");
sb.Append(" NewValues: ").Append(NewValues).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
Formatting = Formatting.Indented
});
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as AuditChange);
}
/// <summary>
/// Returns true if AuditChange instances are equal
/// </summary>
/// <param name="other">Instance of AuditChange to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(AuditChange other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return true &&
(
this.Property == other.Property ||
this.Property != null &&
this.Property.Equals(other.Property)
) &&
(
this.Entity == other.Entity ||
this.Entity != null &&
this.Entity.Equals(other.Entity)
) &&
(
this.OldValues == other.OldValues ||
this.OldValues != null &&
this.OldValues.SequenceEqual(other.OldValues)
) &&
(
this.NewValues == other.NewValues ||
this.NewValues != null &&
this.NewValues.SequenceEqual(other.NewValues)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Property != null)
hash = hash * 59 + this.Property.GetHashCode();
if (this.Entity != null)
hash = hash * 59 + this.Entity.GetHashCode();
if (this.OldValues != null)
hash = hash * 59 + this.OldValues.GetHashCode();
if (this.NewValues != null)
hash = hash * 59 + this.NewValues.GetHashCode();
return hash;
}
}
}
}
| 30.338384 | 148 | 0.488097 | [
"MIT"
] | F-V-L/platform-client-sdk-dotnet | build/src/PureCloudPlatform.Client.V2/Model/AuditChange.cs | 6,007 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Spectre.Console.Cli;
namespace Cake.Tests.Fakes
{
public sealed class FakeRemainingArguments : IRemainingArguments
{
public ILookup<string, string> Parsed { get; }
public IReadOnlyList<string> Raw => throw new NotImplementedException();
public FakeRemainingArguments(IDictionary<string, string> arguments)
{
Parsed = (arguments ?? new Dictionary<string, string>())
.ToLookup(x => x.Key, x => x.Value, StringComparer.OrdinalIgnoreCase);
}
}
}
| 28.52381 | 86 | 0.671119 | [
"MIT"
] | AdaskoTheBeAsT/cake | src/Cake.Tests/Fakes/FakeRemainingArguments.cs | 601 | C# |
using Discord.Commands;
using DEA.Extensions.Discord;
using System;
using System.Threading.Tasks;
namespace DEA.Preconditions.Parameter
{
public sealed class MinimumHoursAttribute : ParameterPreconditionAttribute
{
private readonly double _minimumHours;
public MinimumHoursAttribute(double minimumHours)
{
_minimumHours = minimumHours;
}
public override Task<PreconditionResult> CheckPermissionsAsync(ICommandContext context, ParameterInfo parameter, object value,
IServiceProvider services)
{
if (value is TimeSpan length && length.TotalHours < _minimumHours)
return Task.FromResult(PreconditionResult.FromError($"The minimum {parameter.Format()} is {_minimumHours}h."));
return Task.FromResult(PreconditionResult.FromSuccess());
}
}
}
| 32.333333 | 134 | 0.701031 | [
"MIT"
] | Lunerr/dea2cs | src/Preconditions/Parameter/MinimumHours.cs | 873 | C# |
using System;
namespace RockSweeper.Attributes
{
/// <summary>
/// Defines the user friendly name of the object.
/// </summary>
/// <seealso cref="System.Attribute" />
public class TitleAttribute : Attribute
{
/// <summary>
/// Gets or sets the title.
/// </summary>
/// <value>
/// The title.
/// </value>
public string Title { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="TitleAttribute"/> class.
/// </summary>
/// <param name="title">The title.</param>
public TitleAttribute( string title )
{
Title = title;
}
}
}
| 24.241379 | 81 | 0.513514 | [
"MIT"
] | cabal95/RockSweeper | RockSweeper/Attributes/TitleAttribute.cs | 705 | 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("Hello.Windows")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Hello.Windows")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("504a36f5-9c20-4de5-9cf3-4bacd184b3d0")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.810811 | 84 | 0.744103 | [
"CC0-1.0"
] | Jorch72/CS-StartingWithAstrid | Hello/Hello.Windows/Properties/AssemblyInfo.cs | 1,402 | C# |
/*
* Notes
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SpatialSlur.Meshes;
using SpatialSlur.Meshes.Impl;
namespace SpatialSlur
{
/// <summary>
///
/// </summary>
public static partial class Matrix
{
/// <summary>
/// Returns the entries of the incidence matrix in row-major order.
/// </summary>
/// <returns></returns>
public static void GetVertexIncidence<V, E>(this HeStructure<V, E> graph, double[] result)
where V : HeStructure<V, E>.Vertex
where E : HeStructure<V, E>.Halfedge
{
var verts = graph.Vertices;
int nv = verts.Count;
int ne = graph.Edges.Count;
Array.Clear(result, 0, nv * ne);
for (int i = 0; i < nv; i++)
{
var v = verts[i];
if (v.IsUnused) continue;
int offset = i * ne;
foreach (var he in v.OutgoingHalfedges)
result[offset + he.EdgeIndex] = 1.0;
}
}
/// <summary>
/// Returns the entries of the adjacency matrix.
/// </summary>
/// <returns></returns>
public static void GetVertexAdjacency<V, E>(this HeStructure<V, E> graph, double[] result)
where V : HeStructure<V, E>.Vertex
where E : HeStructure<V, E>.Halfedge
{
var verts = graph.Vertices;
int nv = verts.Count;
Array.Clear(result, 0, nv * nv);
for (int i = 0; i < nv; i++)
{
var v0 = verts[i];
if (v0.IsUnused) continue;
int offset = i * nv;
foreach (var v1 in v0.ConnectedVertices)
result[offset + v1.Index] = 1.0;
}
}
/// <summary>
/// Returns the entries of the Laplacian matrix.
/// </summary>
public static void GetVertexLaplacian<V, E>(this HeStructure<V, E> graph, double[] result)
where V : HeStructure<V, E>.Vertex
where E : HeStructure<V, E>.Halfedge
{
var verts = graph.Vertices;
int nv = verts.Count;
Array.Clear(result, 0, nv * nv);
for (int i = 0; i < nv; i++)
{
var v = verts[i];
if (v.IsUnused) continue;
double wsum = 0.0;
int offset = i * nv;
foreach (var he in v.OutgoingHalfedges)
{
result[offset + he.End.Index] = 1.0;
wsum++;
}
result[offset + i] = -wsum;
}
}
/// <summary>
/// Returns the entries of the Laplacian matrix.
/// </summary>
public static void GetVertexLaplacian<V, E>(this HeStructure<V, E> graph, Func<E, double> getWeight, double[] result)
where V : HeStructure<V, E>.Vertex
where E : HeStructure<V, E>.Halfedge
{
var verts = graph.Vertices;
int nv = verts.Count;
Array.Clear(result, 0, nv * nv);
for (int i = 0; i < nv; i++)
{
var v = verts[i];
if (v.IsUnused) continue;
double wsum = 0.0;
int offset = i * nv;
foreach (var he in v.OutgoingHalfedges)
{
double w = getWeight(he);
result[offset + he.End.Index] = w;
wsum += w;
}
result[offset + i] = -wsum;
}
}
/// <summary>
/// Returns the entries of the Laplacian matrix in row-major order.
/// </summary>
private static void GetVertexLaplacian<V, E>(this HeStructure<V, E> graph, Func<E, double> getWeight, Func<V, double> getMass, double[] result)
where V : HeStructure<V, E>.Vertex
where E : HeStructure<V, E>.Halfedge
{
var verts = graph.Vertices;
int nv = verts.Count;
Array.Clear(result, 0, nv * nv);
for (int i = 0; i < nv; i++)
{
var v = verts[i];
if (v.IsUnused) continue;
var aInv = 1.0 / getMass(v);
double wsum = 0.0;
int offset = i * nv;
foreach (var he in v.OutgoingHalfedges)
{
double w = getWeight(he) * aInv;
result[offset + he.End.Index] = w;
wsum += w;
}
result[offset + i] = -wsum;
}
}
/// <summary>
/// Returns the entries of the Laplacian matrix.
/// </summary>
private static void GetVertexLaplacianSymmetric<V, E>(this HeStructure<V, E> graph, Func<E, double> getWeight, Func<V, double> getMass, double[] result)
where V : HeStructure<V, E>.Vertex
where E : HeStructure<V, E>.Halfedge
{
// impl ref
// http://reuter.mit.edu/papers/reuter-smi09.pdf
var verts = graph.Vertices;
int nv = verts.Count;
Array.Clear(result, 0, nv * nv);
for (int i = 0; i < nv; i++)
{
var v0 = verts[i];
if (v0.IsUnused) continue;
var a0 = getMass(v0);
double wsum = 0.0;
int offset = i * nv;
foreach (var he in v0.OutgoingHalfedges)
{
double w = getWeight(he) / Math.Sqrt(a0 * getMass(he.End));
result[offset + he.End.Index] = w;
wsum += w;
}
result[offset + i] = -wsum;
}
}
/// <summary>
/// Returns the entries of the incidence matrix in row-major order.
/// </summary>
/// <returns></returns>
public static void GetFaceIncidence<V, E, F>(this HeStructure<V, E, F> mesh, double[] result)
where V : HeStructure<V, E, F>.Vertex
where E : HeStructure<V, E, F>.Halfedge
where F : HeStructure<V, E, F>.Face
{
var faces = mesh.Faces;
int nf = faces.Count;
int ne = mesh.Edges.Count;
Array.Clear(result, 0, nf * ne);
for (int i = 0; i < nf; i++)
{
var f = faces[i];
if (f.IsUnused) continue;
int offset = i * ne;
foreach (var he in f.Halfedges)
result[offset + he.EdgeIndex] = 1.0;
}
}
/// <summary>
/// Returns the entries of the adjacency matrix.
/// </summary>
/// <returns></returns>
public static void GetFaceAdjacency<V, E, F>(this HeStructure<V, E, F> mesh, double[] result)
where V : HeStructure<V, E, F>.Vertex
where E : HeStructure<V, E, F>.Halfedge
where F : HeStructure<V, E, F>.Face
{
var faces = mesh.Faces;
int nf = faces.Count;
Array.Clear(result, 0, nf * nf);
for (int i = 0; i < nf; i++)
{
var f0 = faces[i];
if (f0.IsUnused) continue;
var offset = i * nf;
foreach (var f1 in f0.AdjacentFaces)
result[offset + f1.Index] = 1.0;
}
}
/// <summary>
/// Returns the entries of the Laplacian matrix.
/// </summary>
public static void GetFaceLaplacian<V, E, F>(this HeStructure<V, E, F> mesh, double[] result)
where V : HeStructure<V, E, F>.Vertex
where E : HeStructure<V, E, F>.Halfedge
where F : HeStructure<V, E, F>.Face
{
var faces = mesh.Faces;
int nf = faces.Count;
Array.Clear(result, 0, nf * nf);
for (int i = 0; i < nf; i++)
{
var f = faces[i];
if (f.IsUnused) continue;
double wsum = 0.0;
var offset = i * nf;
foreach (var he in f.Halfedges)
{
result[offset + he.End.Index] = 1.0;
wsum++;
}
result[offset + i] = -wsum;
}
}
/// <summary>
/// Returns the entries of the Laplacian matrix.
/// </summary>
public static void GetFaceLaplacian<V, E, F>(this HeStructure<V, E, F> mesh, Func<E, double> getWeight, double[] result)
where V : HeStructure<V, E, F>.Vertex
where E : HeStructure<V, E, F>.Halfedge
where F : HeStructure<V, E, F>.Face
{
var faces = mesh.Faces;
int nf = faces.Count;
Array.Clear(result, 0, nf * nf);
for (int i = 0; i < nf; i++)
{
var f = faces[i];
if (f.IsUnused) continue;
double wsum = 0.0;
var offset = i * nf;
foreach (var he in f.Halfedges)
{
double w = getWeight(he);
result[offset + he.End.Index] = w;
wsum += w;
}
result[offset + i] = -wsum;
}
}
}
}
| 30.423567 | 160 | 0.45012 | [
"MIT"
] | daveReeves/SpatialSlur | SpatialSlur/Meshes/Matrix.cs | 9,555 | C# |
using System;
namespace KCSystem.Api.Extensions
{
public class BirthdayHelper
{
public static BirthdayAgeSex GetBirthdayAgeSex(string identityCard)
{
if (string.IsNullOrEmpty(identityCard))
{
return null;
}
else
{
if (identityCard.Length != 15 && identityCard.Length != 18)//身份证号码只能为15位或18位其它不合法
{
return null;
}
}
try
{
BirthdayAgeSex entity = new BirthdayAgeSex();
string strSex = string.Empty;
if (identityCard.Length == 18)//处理18位的身份证号码从号码中得到生日和性别代码
{
entity.Birthday = identityCard.Substring(6, 4) + "-" + identityCard.Substring(10, 2) + "-" + identityCard.Substring(12, 2);
strSex = identityCard.Substring(14, 3);
}
if (identityCard.Length == 15)
{
entity.Birthday = "19" + identityCard.Substring(6, 2) + "-" + identityCard.Substring(8, 2) + "-" + identityCard.Substring(10, 2);
strSex = identityCard.Substring(12, 3);
}
entity.Age = CalculateAge(entity.Birthday);//根据生日计算年龄
if (int.Parse(strSex) % 2 == 0)//性别代码为偶数是女性奇数为男性
{
entity.Sex = "女";
}
else
{
entity.Sex = "男";
}
return entity;
}
catch
{
return null;
}
}
/// <summary>
/// 根据出生日期,计算精确的年龄
/// </summary>
/// <param name="birthDate">生日</param>
/// <returns></returns>
public static int CalculateAge(string birthDay)
{
DateTime birthDate = DateTime.Parse(birthDay);
DateTime nowDateTime = DateTime.Now;
int age = nowDateTime.Year - birthDate.Year;
//再考虑月、天的因素
if (nowDateTime.Month < birthDate.Month || (nowDateTime.Month == birthDate.Month && nowDateTime.Day < birthDate.Day))
{
age--;
}
return age;
}
/// <summary>
/// 求两个日期时间差
/// </summary>
/// <param name="dateStart"></param>
/// <param name="dateEnd"></param>
/// <returns></returns>
public static int DateDiff(DateTime dateStart, DateTime dateEnd)
{
DateTime start = Convert.ToDateTime(dateStart.ToShortDateString());
DateTime end = Convert.ToDateTime(dateEnd.ToShortDateString());
TimeSpan sp = end.Subtract(start);
return sp.Days;
}
/// <summary>
/// 判断日期
/// </summary>
/// <param name="DateStr"></param>
/// <returns></returns>
public static string IsDate(string DateStr)
{
try
{
if (Convert.ToInt32(DateStr) > 0)
{
DateStr = DateTime.FromOADate(double.Parse(DateStr)).ToString("yyyy年M月d日", System.Globalization.DateTimeFormatInfo.InvariantInfo);
}
return DateStr;
}
catch
{
return DateStr;
}
}
/// <summary>
/// 将字段首字母变为大写
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string TitleToUpper(string str)
{
if (string.IsNullOrWhiteSpace(str))
return string.Empty;
char[] s = str.ToCharArray();
char c = s[0];
if ('a' <= c && c <= 'z')
c = (char)(c & ~0x20);
s[0] = c;
return new string(s);
}
}
/// <summary>
/// 定义 生日年龄性别 实体
/// </summary>
public class BirthdayAgeSex
{
public string Birthday { get; set; }
public int Age { get; set; }
public string Sex { get; set; }
}
}
| 30.065217 | 150 | 0.459388 | [
"MIT"
] | kcomking1/KCON | KCSystem.Api/Extensions/BirthdayHelper.cs | 4,397 | C# |
using UniRx;
using UnityEngine;
using UnityEngine.UI;
namespace UniRxSample.MVRP
{
// ModelとView(uGUI)を繋ぐオブジェクト
public class Presenter : MonoBehaviour
{
// Modelオブジェクト
[SerializeField] private Model _model;
// 各UI要素
[SerializeField] private Text _text;
[SerializeField] private Button _upButton;
[SerializeField] private Button _downButton;
private void Start()
{
// Modelの値の変化をTextに反映
_model.Score
.Subscribe(x => _text.text = x.ToString())
.AddTo(this);
// Upが押されたら加算
_upButton
.OnClickAsObservable()
.Subscribe(_ => _model.Score.Value++)
.AddTo(this);
// Downが押されたら減算
_downButton
.OnClickAsObservable()
.Subscribe(_ => _model.Score.Value--)
.AddTo(this);
}
}
}
| 24.538462 | 58 | 0.530825 | [
"Unlicense",
"CC0-1.0",
"MIT"
] | Itu-tree/ProgrammingBible_UniRxSampleGame | Assets/UniRxSample/MVRP/Presenter.cs | 1,045 | C# |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.OsConfig.V1.Snippets
{
// [START osconfig_v1_generated_OsConfigZonalService_ListVulnerabilityReports_async_flattened_resourceNames]
using Google.Api.Gax;
using Google.Cloud.OsConfig.V1;
using System;
using System.Linq;
using System.Threading.Tasks;
public sealed partial class GeneratedOsConfigZonalServiceClientSnippets
{
/// <summary>Snippet for ListVulnerabilityReportsAsync</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public async Task ListVulnerabilityReportsResourceNamesAsync()
{
// Create client
OsConfigZonalServiceClient osConfigZonalServiceClient = await OsConfigZonalServiceClient.CreateAsync();
// Initialize request argument(s)
InstanceName parent = InstanceName.FromProjectZoneInstance("[PROJECT]", "[ZONE]", "[INSTANCE]");
// Make the request
PagedAsyncEnumerable<ListVulnerabilityReportsResponse, VulnerabilityReport> response = osConfigZonalServiceClient.ListVulnerabilityReportsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((VulnerabilityReport item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListVulnerabilityReportsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (VulnerabilityReport item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<VulnerabilityReport> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (VulnerabilityReport item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
}
}
// [END osconfig_v1_generated_OsConfigZonalService_ListVulnerabilityReports_async_flattened_resourceNames]
}
| 45.233766 | 164 | 0.661499 | [
"Apache-2.0"
] | AlexandrTrf/google-cloud-dotnet | apis/Google.Cloud.OsConfig.V1/Google.Cloud.OsConfig.V1.GeneratedSnippets/OsConfigZonalServiceClient.ListVulnerabilityReportsResourceNamesAsyncSnippet.g.cs | 3,483 | C# |
/**
* $File: JCS_EchoGamePadButton.cs $
* $Date: 2017-10-23 15:23:06 $
* $Revision: $
* $Creator: Jen-Chieh Shen $
* $Notice: See LICENSE.txt for modification and distribution information
* Copyright (c) 2017 by Shen, Jen-Chieh $
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace JCSUnity
{
/// <summary>
/// Echo out with game pad button
/// </summary>
public class JCS_EchoGamePadButton
: JCS_GamePadButton
{
[Header("** Runtime Variables (JCS_EchoGamePadButton) **")]
[Tooltip("String to echo out on the console window.")]
public string echoString = "echo Hello World!~";
public override void JCS_OnClickCallback()
{
JCS_Debug.Log(echoString);
}
}
}
| 24.727273 | 74 | 0.623775 | [
"MIT"
] | edwin-channel/JCSUnity | Assets/JCSUnity/Scripts/GUI/Button/JCS_EchoGamePadButton.cs | 816 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Azure.WebJobs.Script.Description;
using Microsoft.Azure.WebJobs.Script.Diagnostics;
using Microsoft.Azure.WebJobs.Script.Eventing;
using Microsoft.Azure.WebJobs.Script.ManagedDependencies;
using Microsoft.Azure.WebJobs.Script.Workers;
using Microsoft.Azure.WebJobs.Script.Workers.Rpc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.WebJobs.Script.Tests;
using Moq;
using Xunit;
using FunctionMetadata = Microsoft.Azure.WebJobs.Script.Description.FunctionMetadata;
namespace Microsoft.Azure.WebJobs.Script.Tests.Workers.Rpc
{
public class RpcFunctionInvocationDispatcherTests
{
private static TestRpcWorkerChannel _javaTestChannel;
private static ILogger _testLogger;
private static TestLoggerProvider _testLoggerProvider;
private static LoggerFactory _testLoggerFactory;
public RpcFunctionInvocationDispatcherTests()
{
_testLoggerProvider = new TestLoggerProvider();
_testLoggerFactory = new LoggerFactory();
_testLoggerFactory.AddProvider(_testLoggerProvider);
_testLogger = _testLoggerProvider.CreateLogger("FunctionDispatcherTests");
}
[Fact]
public async Task GetWorkerStatusesAsync_ReturnsExpectedResult()
{
int expectedProcessCount = 3;
var functionDispatcher = GetTestFunctionDispatcher(expectedProcessCount);
await functionDispatcher.InitializeAsync(GetTestFunctionsList(RpcWorkerConstants.NodeLanguageWorkerName));
var finalChannelCount = await WaitForJobhostWorkerChannelsToStartup(functionDispatcher, expectedProcessCount);
Assert.Equal(expectedProcessCount, finalChannelCount);
var result = await functionDispatcher.GetWorkerStatusesAsync();
Assert.Equal(expectedProcessCount, result.Count);
foreach (var status in result.Values)
{
Assert.Equal(TimeSpan.FromMilliseconds(10), status.Latency);
Assert.Equal(26, status.ProcessStats.CpuLoadHistory.Average());
}
}
[Fact]
public async Task Starting_MultipleJobhostChannels_Succeeds()
{
_testLoggerProvider.ClearAllLogMessages();
int expectedProcessCount = 3;
RpcFunctionInvocationDispatcher functionDispatcher = GetTestFunctionDispatcher(expectedProcessCount);
await functionDispatcher.InitializeAsync(GetTestFunctionsList(RpcWorkerConstants.NodeLanguageWorkerName));
var finalChannelCount = await WaitForJobhostWorkerChannelsToStartup(functionDispatcher, expectedProcessCount);
Assert.Equal(expectedProcessCount, finalChannelCount);
VerifyStartIntervals(TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(15));
}
[Fact]
public async Task Starting_MultipleWebhostChannels_Succeeds()
{
_testLoggerProvider.ClearAllLogMessages();
int expectedProcessCount = 3;
RpcFunctionInvocationDispatcher functionDispatcher = GetTestFunctionDispatcher(expectedProcessCount, true);
await functionDispatcher.InitializeAsync(GetTestFunctionsList(RpcWorkerConstants.JavaLanguageWorkerName));
var finalWebhostChannelCount = await WaitForWebhostWorkerChannelsToStartup(functionDispatcher.WebHostLanguageWorkerChannelManager, expectedProcessCount, "java");
Assert.Equal(expectedProcessCount, finalWebhostChannelCount);
var finalJobhostChannelCount = functionDispatcher.JobHostLanguageWorkerChannelManager.GetChannels().Count();
Assert.Equal(0, finalJobhostChannelCount);
// ignore first start as we added a WebhostChannel on GetTestFunctionDispatcher call
VerifyStartIntervals(TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(15), true);
}
[Fact]
public async Task Starting_MultipleJobhostChannels_Failed()
{
_testLoggerProvider.ClearAllLogMessages();
int expectedProcessCount = 3;
RpcFunctionInvocationDispatcher functionDispatcher = GetTestFunctionDispatcher(expectedProcessCount, throwOnProcessStartUp: true);
await functionDispatcher.InitializeAsync(GetTestFunctionsList(RpcWorkerConstants.NodeLanguageWorkerName));
var finalChannelCount = await WaitForJobhostWorkerChannelsToStartup(functionDispatcher, expectedProcessCount, false);
Assert.Equal(expectedProcessCount, finalChannelCount);
var logMessages = _testLoggerProvider.GetAllLogMessages().ToList();
Assert.Equal(logMessages.Where(x => x.FormattedMessage
.Contains("Failed to start a new language worker")).Count(), 3);
}
[Fact]
public async Task SuccessiveRestarts_WorkerCountsStayTheSame()
{
int expectedProcessCount = 3;
List<Task> restartTasks = new List<Task>();
RpcFunctionInvocationDispatcher functionDispatcher = GetTestFunctionDispatcher(expectedProcessCount);
await functionDispatcher.InitializeAsync(GetTestFunctionsList(RpcWorkerConstants.NodeLanguageWorkerName));
await WaitForJobhostWorkerChannelsToStartup(functionDispatcher, expectedProcessCount);
Guid[] invocationIds = new Guid[] { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };
List<TestRpcWorkerChannel> workerChannels = functionDispatcher.JobHostLanguageWorkerChannelManager.GetChannels().Cast<TestRpcWorkerChannel>().ToList();
for (int i = 0; i < invocationIds.Length; ++i)
{
workerChannels[i % 3].SendInvocationRequest(new ScriptInvocationContext
{
ExecutionContext = new ExecutionContext
{
InvocationId = invocationIds[i]
}
});
}
foreach (var invocationId in invocationIds)
{
restartTasks.Add(functionDispatcher.RestartWorkerWithInvocationIdAsync(invocationId.ToString()));
}
await Task.WhenAll(restartTasks);
Assert.Equal(expectedProcessCount, functionDispatcher.JobHostLanguageWorkerChannelManager.GetChannels().Count()); // Ensure count always stays at the initial count
}
[Fact]
public async Task Restart_ParticularWorkerChannel_Succeeds_OnlyThatIsDisposed()
{
int expectedProcessCount = 3;
RpcFunctionInvocationDispatcher functionDispatcher = GetTestFunctionDispatcher(expectedProcessCount);
await functionDispatcher.InitializeAsync(GetTestFunctionsList(RpcWorkerConstants.NodeLanguageWorkerName));
await WaitForJobhostWorkerChannelsToStartup(functionDispatcher, expectedProcessCount);
Guid invocationId = Guid.NewGuid();
List<TestRpcWorkerChannel> workerChannels = functionDispatcher.JobHostLanguageWorkerChannelManager.GetChannels().Cast<TestRpcWorkerChannel>().ToList();
workerChannels[0].SendInvocationRequest(new ScriptInvocationContext
{
ExecutionContext = new ExecutionContext
{
InvocationId = invocationId
}
});
await functionDispatcher.RestartWorkerWithInvocationIdAsync(invocationId.ToString());
Assert.True(workerChannels[0].IsDisposed);
for (int i = 1; i < workerChannels.Count; ++i)
{
Assert.False(workerChannels[i].IsDisposed); // Ensure no other channel is disposed
}
Assert.Equal(expectedProcessCount, functionDispatcher.JobHostLanguageWorkerChannelManager.GetChannels().Count()); // Ensure count goes back to initial count
}
[Fact]
public async Task ShutdownTests()
{
int expectedProcessCount = 2;
RpcFunctionInvocationDispatcher functionDispatcher = GetTestFunctionDispatcher(expectedProcessCount);
await functionDispatcher.InitializeAsync(GetTestFunctionsList(RpcWorkerConstants.NodeLanguageWorkerName));
await WaitForJobhostWorkerChannelsToStartup(functionDispatcher, expectedProcessCount);
foreach (var currChannel in functionDispatcher.JobHostLanguageWorkerChannelManager.GetChannels())
{
var initializedChannel = (TestRpcWorkerChannel)currChannel;
initializedChannel.ExecutionContexts.Add(Task.Factory.StartNew(() => { }));
}
await functionDispatcher.ShutdownAsync();
foreach (var currChannel in functionDispatcher.JobHostLanguageWorkerChannelManager.GetChannels())
{
Assert.True(((TestRpcWorkerChannel)currChannel).ExecutionContexts.Count == 0);
}
}
[Fact]
public async Task ShutdownTests_WithInfinitelyRunningTasks_Timesout()
{
int expectedProcessCount = 2;
RpcFunctionInvocationDispatcher functionDispatcher = GetTestFunctionDispatcher(expectedProcessCount);
await functionDispatcher.InitializeAsync(GetTestFunctionsList(RpcWorkerConstants.NodeLanguageWorkerName));
await WaitForJobhostWorkerChannelsToStartup(functionDispatcher, expectedProcessCount);
foreach (var currChannel in functionDispatcher.JobHostLanguageWorkerChannelManager.GetChannels())
{
var initializedChannel = (TestRpcWorkerChannel)currChannel;
initializedChannel.ExecutionContexts.Add(new Task<bool>(() => true)); // A task that never starts and therefore never runs to completion
}
await functionDispatcher.ShutdownAsync();
foreach (var currChannel in functionDispatcher.JobHostLanguageWorkerChannelManager.GetChannels())
{
Assert.True(((TestRpcWorkerChannel)currChannel).ExecutionContexts.Count > 0);
}
}
[Fact]
public async Task FunctionDispatcherState_Default_DotNetFunctions()
{
RpcFunctionInvocationDispatcher functionDispatcher = GetTestFunctionDispatcher();
Assert.Equal(FunctionInvocationDispatcherState.Default, functionDispatcher.State);
FunctionMetadata func1 = new FunctionMetadata()
{
Name = "func1",
Language = "dotnet"
};
var functions = new List<FunctionMetadata>()
{
func1
};
await functionDispatcher.InitializeAsync(functions);
Assert.Equal(FunctionInvocationDispatcherState.Default, functionDispatcher.State);
await functionDispatcher.InitializeAsync(functions);
Assert.Equal(FunctionInvocationDispatcherState.Default, functionDispatcher.State);
await functionDispatcher.InitializeAsync(functions);
Assert.Equal(FunctionInvocationDispatcherState.Default, functionDispatcher.State);
}
[Fact]
public async Task FunctionDispatcherState_Default_NoFunctions()
{
RpcFunctionInvocationDispatcher functionDispatcher = GetTestFunctionDispatcher();
Assert.Equal(FunctionInvocationDispatcherState.Default, functionDispatcher.State);
await functionDispatcher.InitializeAsync(new List<FunctionMetadata>());
}
[Fact]
public async Task ShutdownChannels_NoFunctions()
{
var mockLanguageWorkerChannelManager = new Mock<IWebHostRpcWorkerChannelManager>();
mockLanguageWorkerChannelManager.Setup(m => m.ShutdownChannelsAsync()).Returns(Task.CompletedTask);
RpcFunctionInvocationDispatcher functionDispatcher = GetTestFunctionDispatcher(mockwebHostLanguageWorkerChannelManager: mockLanguageWorkerChannelManager);
Assert.Equal(FunctionInvocationDispatcherState.Default, functionDispatcher.State);
await functionDispatcher.InitializeAsync(new List<FunctionMetadata>());
// Wait longer than debouce action.
await Task.Delay(6000);
mockLanguageWorkerChannelManager.Verify(m => m.ShutdownChannelsAsync(), Times.Once);
}
[Fact]
public async Task ShutdownChannels_DotNetFunctions()
{
FunctionMetadata func1 = new FunctionMetadata()
{
Name = "func1",
Language = "dotnet"
};
var functions = new List<FunctionMetadata>()
{
func1
};
var mockLanguageWorkerChannelManager = new Mock<IWebHostRpcWorkerChannelManager>();
RpcFunctionInvocationDispatcher functionDispatcher = GetTestFunctionDispatcher(mockwebHostLanguageWorkerChannelManager: mockLanguageWorkerChannelManager);
Assert.Equal(FunctionInvocationDispatcherState.Default, functionDispatcher.State);
await functionDispatcher.InitializeAsync(functions);
// Wait longer than debouce action.
await Task.Delay(6000);
mockLanguageWorkerChannelManager.Verify(m => m.ShutdownChannelsAsync(), Times.Once);
}
[Fact]
public async Task FunctionDispatcherState_Transitions_From_Starting_To_Initialized()
{
RpcFunctionInvocationDispatcher functionDispatcher = GetTestFunctionDispatcher();
FunctionMetadata func1 = new FunctionMetadata()
{
Name = "func1",
Language = "node"
};
var functions = new List<FunctionMetadata>()
{
func1
};
await functionDispatcher.InitializeAsync(functions);
Assert.Equal(FunctionInvocationDispatcherState.Initializing, functionDispatcher.State);
await WaitForFunctionDispactherStateInitialized(functionDispatcher);
Assert.Equal(FunctionInvocationDispatcherState.Initialized, functionDispatcher.State);
}
[Fact]
public async Task FunctionDispatcherState_Transitions_From_Default_To_Initialized_To_Disposing()
{
RpcFunctionInvocationDispatcher functionDispatcher = GetTestFunctionDispatcher();
Assert.Equal(FunctionInvocationDispatcherState.Default, functionDispatcher.State);
FunctionMetadata func1 = new FunctionMetadata()
{
Name = "func1",
Language = "node"
};
var functions = new List<FunctionMetadata>()
{
func1
};
await functionDispatcher.InitializeAsync(functions);
Assert.Equal(FunctionInvocationDispatcherState.Initializing, functionDispatcher.State);
await WaitForFunctionDispactherStateInitialized(functionDispatcher);
Assert.Equal(FunctionInvocationDispatcherState.Initialized, functionDispatcher.State);
functionDispatcher.Dispose();
Assert.True(functionDispatcher == null || functionDispatcher.State == FunctionInvocationDispatcherState.Disposing || functionDispatcher.State == FunctionInvocationDispatcherState.Disposed);
}
[Fact]
public async Task FunctionDispatcher_Restart_ErroredChannels_Succeeds()
{
int expectedProcessCount = 2;
RpcFunctionInvocationDispatcher functionDispatcher = GetTestFunctionDispatcher(expectedProcessCount);
await functionDispatcher.InitializeAsync(GetTestFunctionsList(RpcWorkerConstants.NodeLanguageWorkerName));
await WaitForJobhostWorkerChannelsToStartup(functionDispatcher, expectedProcessCount);
int finalChannelCount = 0;
for (int restartCount = 0; restartCount < expectedProcessCount * 3; restartCount++)
{
TestRpcWorkerChannel testWorkerChannel = (TestRpcWorkerChannel)functionDispatcher.JobHostLanguageWorkerChannelManager.GetChannels().FirstOrDefault();
if (functionDispatcher.LanguageWorkerErrors.Count < (expectedProcessCount * 3) - 1)
{
testWorkerChannel.RaiseWorkerError();
}
finalChannelCount = await WaitForJobhostWorkerChannelsToStartup(functionDispatcher, expectedProcessCount);
}
Assert.Equal(expectedProcessCount, finalChannelCount);
}
[Fact]
public async Task FunctionDispatcher_Restart_ErroredChannels_And_Changes_State()
{
int expectedProcessCount = 1;
RpcFunctionInvocationDispatcher functionDispatcher = GetTestFunctionDispatcher(expectedProcessCount);
Assert.Equal(FunctionInvocationDispatcherState.Default, functionDispatcher.State);
// Add worker
await functionDispatcher.InitializeAsync(GetTestFunctionsList(RpcWorkerConstants.NodeLanguageWorkerName));
await WaitForJobhostWorkerChannelsToStartup(functionDispatcher, expectedProcessCount);
TestRpcWorkerChannel testWorkerChannel = (TestRpcWorkerChannel)functionDispatcher.JobHostLanguageWorkerChannelManager.GetChannels().FirstOrDefault();
// Restart this channel
testWorkerChannel.RaiseWorkerRestart();
await TestHelpers.Await(() =>
{
return functionDispatcher.State == FunctionInvocationDispatcherState.WorkerProcessRestarting;
}, 3000);
await WaitForJobhostWorkerChannelsToStartup(functionDispatcher, expectedProcessCount);
Assert.Equal(FunctionInvocationDispatcherState.Initialized, functionDispatcher.State);
}
[Fact]
public async Task FunctionDispatcher_Restart_ErroredChannels_And_DoesNot_Change_State()
{
int expectedProcessCount = 2;
RpcFunctionInvocationDispatcher functionDispatcher = GetTestFunctionDispatcher(expectedProcessCount);
Assert.Equal(FunctionInvocationDispatcherState.Default, functionDispatcher.State);
// Add worker
await functionDispatcher.InitializeAsync(GetTestFunctionsList(RpcWorkerConstants.NodeLanguageWorkerName));
await WaitForJobhostWorkerChannelsToStartup(functionDispatcher, expectedProcessCount);
TestRpcWorkerChannel testWorkerChannel = (TestRpcWorkerChannel)functionDispatcher.JobHostLanguageWorkerChannelManager.GetChannels().FirstOrDefault();
// Restart one channel
testWorkerChannel.RaiseWorkerRestart();
Assert.Equal(FunctionInvocationDispatcherState.Initialized, functionDispatcher.State);
await WaitForJobhostWorkerChannelsToStartup(functionDispatcher, expectedProcessCount);
Assert.Equal(FunctionInvocationDispatcherState.Initialized, functionDispatcher.State);
}
[Fact]
public async Task FunctionDispatcher_Restart_ErroredChannels_ExceedsLimit()
{
int expectedProcessCount = 2;
RpcFunctionInvocationDispatcher functionDispatcher = GetTestFunctionDispatcher(expectedProcessCount);
await functionDispatcher.InitializeAsync(GetTestFunctionsList(RpcWorkerConstants.NodeLanguageWorkerName));
await WaitForJobhostWorkerChannelsToStartup(functionDispatcher, expectedProcessCount);
for (int restartCount = 0; restartCount < expectedProcessCount * 3; restartCount++)
{
foreach (var channel in functionDispatcher.JobHostLanguageWorkerChannelManager.GetChannels())
{
TestRpcWorkerChannel testWorkerChannel = channel as TestRpcWorkerChannel;
testWorkerChannel.RaiseWorkerError();
}
}
Assert.Equal(0, functionDispatcher.JobHostLanguageWorkerChannelManager.GetChannels().Count());
}
[Fact]
public async Task FunctionDispatcher_Restart_ErroredChannels_OnWorkerRestart_NotAffectedByLimit()
{
int expectedProcessCount = 2;
RpcFunctionInvocationDispatcher functionDispatcher = GetTestFunctionDispatcher(expectedProcessCount);
await functionDispatcher.InitializeAsync(GetTestFunctionsList(RpcWorkerConstants.NodeLanguageWorkerName));
await WaitForJobhostWorkerChannelsToStartup(functionDispatcher, expectedProcessCount);
for (int restartCount = 0; restartCount < expectedProcessCount * 3; restartCount++)
{
foreach (var channel in functionDispatcher.JobHostLanguageWorkerChannelManager.GetChannels())
{
TestRpcWorkerChannel testWorkerChannel = channel as TestRpcWorkerChannel;
testWorkerChannel.RaiseWorkerRestart();
}
var finalChannelCount = await WaitForJobhostWorkerChannelsToStartup(functionDispatcher, expectedProcessCount);
Assert.Equal(expectedProcessCount, finalChannelCount);
}
}
[Fact]
public async Task FunctionDispatcher_Error_WithinThreshold_BucketFills()
{
RpcFunctionInvocationDispatcher functionDispatcher = GetTestFunctionDispatcher(1);
await functionDispatcher.InitializeAsync(GetTestFunctionsList(RpcWorkerConstants.NodeLanguageWorkerName));
await WaitForJobhostWorkerChannelsToStartup(functionDispatcher, 1);
for (int i = 0; i < 3; ++i)
{
foreach (var channel in functionDispatcher.JobHostLanguageWorkerChannelManager.GetChannels())
{
TestRpcWorkerChannel testWorkerChannel = channel as TestRpcWorkerChannel;
testWorkerChannel.RaiseWorkerError();
if (i < 2)
{
// wait for restart to complete before raising another error
await WaitForJobhostWorkerChannelsToStartup(functionDispatcher, 1);
}
}
}
Assert.Equal(3, functionDispatcher.LanguageWorkerErrors.Count);
}
[Fact]
public async Task FunctionDispatcher_Error_BeyondThreshold_BucketIsAtOne()
{
RpcFunctionInvocationDispatcher functionDispatcher = GetTestFunctionDispatcher();
await functionDispatcher.InitializeAsync(GetTestFunctionsList(RpcWorkerConstants.NodeLanguageWorkerName));
await WaitForJobhostWorkerChannelsToStartup(functionDispatcher, 1);
for (int i = 1; i < 10; ++i)
{
foreach (var channel in functionDispatcher.JobHostLanguageWorkerChannelManager.GetChannels())
{
TestRpcWorkerChannel testWorkerChannel = channel as TestRpcWorkerChannel;
testWorkerChannel.RaiseWorkerErrorWithCustomTimestamp(DateTime.UtcNow.AddHours(i));
}
}
Assert.Equal(1, functionDispatcher.LanguageWorkerErrors.Count);
}
[Fact]
public async Task FunctionDispatcher_DoNot_Restart_ErroredChannels_If_WorkerRuntime_DoesNotMatch()
{
int expectedProcessCount = 1;
RpcFunctionInvocationDispatcher functionDispatcher = GetTestFunctionDispatcher(expectedProcessCount);
await functionDispatcher.InitializeAsync(GetTestFunctionsList(RpcWorkerConstants.NodeLanguageWorkerName));
await WaitForJobhostWorkerChannelsToStartup(functionDispatcher, expectedProcessCount);
_javaTestChannel.RaiseWorkerError();
var testLogs = _testLoggerProvider.GetAllLogMessages();
Assert.False(testLogs.Any(m => m.FormattedMessage.Contains("Restarting worker channel for runtime:java")));
Assert.Equal(expectedProcessCount, functionDispatcher.JobHostLanguageWorkerChannelManager.GetChannels().Count());
}
[Theory]
[InlineData("node", "node", false, true, true)]
[InlineData("node", "node", true, false, true)]
[InlineData("node", "node", true, true, true)]
[InlineData("node", "node", false, false, false)]
[InlineData("node", "java", false, true, false)]
[InlineData("node", "", false, true, false)]
[InlineData(null, "", false, true, false)]
[InlineData(null, "node", false, true, false)]
[InlineData(null, "node", true, false, false)]
[InlineData(null, "node", true, true, false)]
[InlineData(null, "node", false, false, false)]
[InlineData(null, "java", false, true, false)]
public async Task FunctionDispatcher_ShouldRestartChannel_Returns_True(string workerRuntime, string channelLanguage, bool isWebHostChannel, bool isJobHostChannel, bool expectedResult)
{
RpcFunctionInvocationDispatcher functionDispatcher = GetTestFunctionDispatcher();
await functionDispatcher.InitializeAsync(GetTestFunctionsList(workerRuntime));
Assert.Equal(expectedResult, functionDispatcher.ShouldRestartWorkerChannel(channelLanguage, isWebHostChannel, isJobHostChannel));
}
[Fact]
public async Task FunctionDispatcher_ErroredWebHostChannel()
{
_testLoggerProvider.ClearAllLogMessages();
RpcFunctionInvocationDispatcher functionDispatcher = GetTestFunctionDispatcher(throwOnProcessStartUp: true, addWebhostChannel: true);
await functionDispatcher.InitializeAsync(GetTestFunctionsList(RpcWorkerConstants.JavaLanguageWorkerName));
var testLogs = _testLoggerProvider.GetAllLogMessages();
Assert.True(testLogs.Any(m => m.FormattedMessage.Contains("Removing errored webhost language worker channel for runtime")));
}
private static RpcFunctionInvocationDispatcher GetTestFunctionDispatcher(int maxProcessCountValue = 1, bool addWebhostChannel = false, Mock<IWebHostRpcWorkerChannelManager> mockwebHostLanguageWorkerChannelManager = null, bool throwOnProcessStartUp = false)
{
var eventManager = new ScriptEventManager();
var metricsLogger = new Mock<IMetricsLogger>();
var mockApplicationLifetime = new Mock<IApplicationLifetime>();
var testEnv = new TestEnvironment();
testEnv.SetEnvironmentVariable(RpcWorkerConstants.FunctionsWorkerProcessCountSettingName, maxProcessCountValue.ToString());
var options = new ScriptJobHostOptions
{
RootLogPath = Path.GetTempPath()
};
IOptions<ScriptJobHostOptions> scriptOptions = new OptionsManager<ScriptJobHostOptions>(new TestOptionsFactory<ScriptJobHostOptions>(options));
var workerConfigOptions = new LanguageWorkerOptions
{
WorkerConfigs = TestHelpers.GetTestWorkerConfigs(processCountValue: maxProcessCountValue)
};
IRpcWorkerChannelFactory testLanguageWorkerChannelFactory = new TestRpcWorkerChannelFactory(eventManager, _testLogger, scriptOptions.Value.RootScriptPath, throwOnProcessStartUp);
IWebHostRpcWorkerChannelManager testWebHostLanguageWorkerChannelManager = new TestRpcWorkerChannelManager(eventManager, _testLogger, scriptOptions.Value.RootScriptPath, testLanguageWorkerChannelFactory);
IJobHostRpcWorkerChannelManager jobHostLanguageWorkerChannelManager = new JobHostRpcWorkerChannelManager(_testLoggerFactory);
if (addWebhostChannel)
{
testWebHostLanguageWorkerChannelManager.InitializeChannelAsync("java");
}
if (mockwebHostLanguageWorkerChannelManager != null)
{
testWebHostLanguageWorkerChannelManager = mockwebHostLanguageWorkerChannelManager.Object;
}
var mockFunctionDispatcherLoadBalancer = new Mock<IRpcFunctionInvocationDispatcherLoadBalancer>();
_javaTestChannel = new TestRpcWorkerChannel(Guid.NewGuid().ToString(), "java", eventManager, _testLogger, false);
var optionsMonitor = TestHelpers.CreateOptionsMonitor(workerConfigOptions);
return new RpcFunctionInvocationDispatcher(scriptOptions,
metricsLogger.Object,
testEnv,
mockApplicationLifetime.Object,
eventManager,
_testLoggerFactory,
testLanguageWorkerChannelFactory,
optionsMonitor,
testWebHostLanguageWorkerChannelManager,
jobHostLanguageWorkerChannelManager,
new OptionsWrapper<ManagedDependencyOptions>(new ManagedDependencyOptions()),
mockFunctionDispatcherLoadBalancer.Object);
}
private async Task<int> WaitForJobhostWorkerChannelsToStartup(RpcFunctionInvocationDispatcher functionDispatcher, int expectedCount, bool allReadyForInvocations = true)
{
int currentChannelCount = 0;
await TestHelpers.Await(() =>
{
currentChannelCount = functionDispatcher.JobHostLanguageWorkerChannelManager.GetChannels().Count();
if (currentChannelCount == expectedCount)
{
var channels = functionDispatcher.JobHostLanguageWorkerChannelManager.GetChannels();
return allReadyForInvocations ? channels.All(ch => ch.IsChannelReadyForInvocations()) : true;
}
return false;
}, pollingInterval: expectedCount * 5 * 1000, timeout: 60 * 1000);
return currentChannelCount;
}
private async Task<int> WaitForWebhostWorkerChannelsToStartup(IWebHostRpcWorkerChannelManager channelManager, int expectedCount, string language)
{
int currentChannelCount = 0;
await TestHelpers.Await(() =>
{
currentChannelCount = channelManager.GetChannels(language).Count();
return currentChannelCount == expectedCount;
}, pollingInterval: 4 * 1000, timeout: 60 * 1000);
return currentChannelCount;
}
private async Task WaitForFunctionDispactherStateInitialized(IFunctionInvocationDispatcher functionDispatcher)
{
await TestHelpers.Await(() =>
{
return functionDispatcher.State == FunctionInvocationDispatcherState.Initialized;
}, pollingInterval: 4 * 1000, timeout: 60 * 1000);
}
private IEnumerable<FunctionMetadata> GetTestFunctionsList(string runtime)
{
if (string.IsNullOrEmpty(runtime))
{
return new List<FunctionMetadata>();
}
return new List<FunctionMetadata>()
{
new FunctionMetadata()
{
Language = runtime,
Name = "js1"
},
new FunctionMetadata()
{
Language = runtime,
Name = "js2"
}
};
}
private void VerifyStartIntervals(TimeSpan from, TimeSpan to, bool ignoreFirstStart = false)
{
var startTimestamps = _testLoggerProvider.GetAllLogMessages().Where(x => x.FormattedMessage
.Contains("RegisterFunctions called")).Select(x => x.Timestamp).ToList();
if (ignoreFirstStart)
{
startTimestamps.RemoveAt(0);
}
for (int i = 1; i < startTimestamps.Count(); i++)
{
var diff = startTimestamps[i] - startTimestamps[i - 1];
Assert.True(diff > from && diff < to);
}
}
}
} | 51.895161 | 264 | 0.680932 | [
"Apache-2.0",
"MIT"
] | ConnectionMaster/azure-functions-host | test/WebJobs.Script.Tests/Workers/Rpc/RpcFunctionInvocationDispatcherTests.cs | 32,177 | C# |
#region License
/*
Copyright © 2014-2021 European Support Limited
Licensed under the Apache License, Version 2.0 (the "License")
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Text;
namespace Amdocs.Ginger.Plugin.Core
{
// interface to be implemented by param property attribute
public interface IParamProperty
{
string PropertyName { get; } // set the property name to be written to json
}
}
| 29.451613 | 86 | 0.762322 | [
"Apache-2.0"
] | Ginger-Automation/Ginger | Ginger/GingerPluginCore/Attributes/IActionParamProperty.cs | 914 | C# |
/*
* Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Tizen.Uix.Stt
{
/// <summary>
/// This class holds information related to the EngineChanged event.
/// </summary>
/// <since_tizen> 3 </since_tizen>
public class EngineChangedEventArgs
{
internal EngineChangedEventArgs(string engineId, string language, bool supportSilence, bool needCredential)
{
this.EngineId = engineId;
this.Language = language;
this.SupportSilence = supportSilence;
this.NeedCredential = needCredential;
}
/// <summary>
/// The Engine ID.
/// </summary>
/// <since_tizen> 3 </since_tizen>
public string EngineId
{
get;
internal set;
}
/// <summary>
/// The default language.
/// </summary>
/// <since_tizen> 3 </since_tizen>
public string Language
{
get;
internal set;
}
/// <summary>
/// The necessity of the credential.
/// </summary>
/// <since_tizen> 3 </since_tizen>
public bool NeedCredential
{
get;
internal set;
}
/// <summary>
/// Whether silence detection is supported or not.
/// </summary>
/// <since_tizen> 3 </since_tizen>
public bool SupportSilence
{
get;
internal set;
}
}
}
| 27.506667 | 115 | 0.581677 | [
"Apache-2.0",
"MIT"
] | AchoWang/TizenFX | src/Tizen.Uix.Stt/Tizen.Uix.Stt/EngineChangedEventArgs.cs | 2,065 | C# |
using System.Reflection;
[assembly: AssemblyTitle("Luminous.Code.Core")]
[assembly: AssemblyDescription("Base classes, objects and extension methods for Luminous Code")]
| 34.4 | 96 | 0.796512 | [
"MIT"
] | luminous-software/luminous-code | src/core/Properties/AssemblyInfo.cs | 174 | C# |
using System;
using System.Diagnostics;
using System.Drawing;
using System.Numerics;
using System.Threading;
using Iot.Device.CpuTemperature;
using Iot.Device.SenseHat;
namespace dotnet.core.iot
{
class Program
{
static Color[] pixels = new Color[]{
Color.FromArgb(255, 0, 0), Color.FromArgb(255, 0, 0), Color.FromArgb(255, 87, 0), Color.FromArgb(255, 196, 0), Color.FromArgb(205, 255, 0), Color.FromArgb(95, 255, 0), Color.FromArgb(0, 255, 13), Color.FromArgb(0, 255, 122),
Color.FromArgb(255, 0, 0), Color.FromArgb(255, 96, 0), Color.FromArgb(255, 205, 0), Color.FromArgb(196, 255, 0), Color.FromArgb(87, 255, 0), Color.FromArgb(0, 255, 22), Color.FromArgb(0, 255, 131), Color.FromArgb(0, 255, 240),
Color.FromArgb(255, 105, 0), Color.FromArgb(255, 214, 0), Color.FromArgb(187, 255, 0), Color.FromArgb(78, 255, 0), Color.FromArgb(0, 255, 30), Color.FromArgb(0, 255, 140), Color.FromArgb(0, 255, 248), Color.FromArgb(0, 152, 255),
Color.FromArgb(255, 223, 0), Color.FromArgb(178, 255, 0), Color.FromArgb(70, 255, 0), Color.FromArgb(0, 255, 40), Color.FromArgb(0, 255, 148), Color.FromArgb(0, 253, 255), Color.FromArgb(0, 144, 255), Color.FromArgb(0, 34, 255),
Color.FromArgb(170, 255, 0), Color.FromArgb(61, 255, 0), Color.FromArgb(0, 255, 48), Color.FromArgb(0, 255, 157), Color.FromArgb(0, 243, 255), Color.FromArgb(0, 134, 255), Color.FromArgb(0, 26, 255), Color.FromArgb(83, 0, 255),
Color.FromArgb(52, 255, 0), Color.FromArgb(0, 255, 57), Color.FromArgb(0, 255, 166), Color.FromArgb(0, 235, 255), Color.FromArgb(0, 126, 255), Color.FromArgb(0, 17, 255), Color.FromArgb(92, 0, 255), Color.FromArgb(201, 0, 255),
Color.FromArgb(0, 255, 66), Color.FromArgb(0, 255, 174), Color.FromArgb(0, 226, 255), Color.FromArgb(0, 117, 255), Color.FromArgb(0, 8, 255), Color.FromArgb(100, 0, 255), Color.FromArgb(210, 0, 255), Color.FromArgb(255, 0, 192),
Color.FromArgb(0, 255, 183), Color.FromArgb(0, 217, 255), Color.FromArgb(0, 109, 255), Color.FromArgb(0, 0, 255), Color.FromArgb(110, 0, 255), Color.FromArgb(218, 0, 255), Color.FromArgb(255, 0, 183), Color.FromArgb(255, 0, 74)
};
static CpuTemperature temperature = new CpuTemperature();
static SenseHatPressureAndTemperature pt = new SenseHatPressureAndTemperature();
static Color[] colours = new Color[] { Color.Red, Color.BlueViolet, Color.Yellow, Color.Green, Color.Cyan, Color.Blue, Color.Purple, Color.Pink, Color.White, Color.Black };
static Color currentColour;
static Thread thread1 = new Thread(Rainbow);
static void Main(string[] args)
{
thread1.Start();
while (true)
{
if (temperature.IsAvailable)
{
Console.WriteLine($"The CPU temperature is {Math.Round(temperature.Temperature.DegreesCelsius, 2)}, Room temperature is {Math.Round(pt.Temperature.DegreesCelsius, 2)}");
}
Thread.Sleep(2000); // sleep for 2000 milliseconds, 2 seconds
}
}
public static void sparkle()
{
SenseHatLedMatrixI2c ledMatrix = new SenseHatLedMatrixI2c();
ledMatrix.Fill(Color.Purple);
var rand = new Random();
while (true)
{
var c = Color.FromArgb((byte)rand.Next(0, 255), (byte)rand.Next(0, 255), (byte)rand.Next(0, 255));
var x = rand.Next(0, 8);
var y = rand.Next(0, 8);
ledMatrix.SetPixel(x, y, c);
Thread.Sleep(50);
}
}
// https://github.com/pimoroni/unicorn-hat/blob/master/examples/rainbow.py
static void Rainbow()
{
const int width = 8;
const int height = 8;
Color[] data = new Color[width * height];
double i = 0.0;
double offset = 30;
SenseHatLedMatrixI2c ledMatrix = new SenseHatLedMatrixI2c();
while (true)
{
i = i + 0.3;
for (int y = 0; y < width; y++)
{
for (int x = 0; x < height; x++)
{
var r = (Math.Cos((x + i) / 2.0) + Math.Cos((y + i) / 2.0)) * 64.0 + 64.0;
var g = (Math.Sin((x + i) / 1.5) + Math.Sin((y + i) / 2.0)) * 64.0 + 64.0;
var b = (Math.Sin((x + i) / 2.0) + Math.Cos((y + i) / 1.5)) * 64.0 + 64.0;
r = Math.Max(0, Math.Min(255, r + offset));
g = Math.Max(0, Math.Min(255, g + offset));
b = Math.Max(0, Math.Min(255, b + offset));
data[x + (y * 8)] = Color.FromArgb((byte)r, (byte)g, (byte)b);
}
}
ledMatrix.Write(data);
}
}
public static void DoWork()
{
int cycle = 0;
SenseHatLedMatrixI2c ledMatrix = new SenseHatLedMatrixI2c();
Color[] data = new Color[64];
while (true)
{
cycle++;
for (int y = 0; y < 8; y++)
{
currentColour = colours[(y + cycle) % 8];
for (int x = 0; x < 8; x++)
{
data[x + (y * 8)] = currentColour;
}
}
ledMatrix.Write(data);
Thread.Sleep(100);
}
}
static void nextColor(ref Color pix)
{
byte r = pix.R;
byte g = pix.G;
byte b = pix.B;
if (r == 255 && g < 255 && b == 0)
{
g += 1;
}
if (g == 255 && r > 0 && b == 0)
{
r -= 1;
}
if (g == 255 && b < 255 && r == 0)
{
b += 1;
}
if (b == 255 && g > 0 && r == 0)
{
g -= 1;
}
if (b == 255 && r < 255 && g == 0)
{
r += 1;
}
if (r == 255 && b > 0 && g == 0)
{
b -= 1;
}
pix = Color.FromArgb(r, g, b);
}
public static void Rainbars()
{
using (var ledMatrix = new SenseHatLedMatrixI2c())
{
while (true)
{
for (int i = 0; i < pixels.Length; i++)
{
nextColor(ref pixels[i]);
}
ledMatrix.Write(pixels);
}
}
}
public static void matrix()
{
using (var magnetometer = new SenseHatMagnetometer())
using (var ledMatrix = new SenseHatLedMatrixI2c())
{
Console.WriteLine("Move SenseHat around in every direction until dot on the LED matrix stabilizes when not moving.");
ledMatrix.Fill();
Stopwatch sw = Stopwatch.StartNew();
Vector3 min = magnetometer.MagneticInduction;
Vector3 max = magnetometer.MagneticInduction;
while (min == max)
{
Vector3 sample = magnetometer.MagneticInduction;
min = Vector3.Min(min, sample);
max = Vector3.Max(max, sample);
Thread.Sleep(50);
}
const int intervals = 8;
Color[] data = new Color[64];
while (true)
{
Vector3 sample = magnetometer.MagneticInduction;
min = Vector3.Min(min, sample);
max = Vector3.Max(max, sample);
Vector3 size = max - min;
Vector3 pos = Vector3.Divide(Vector3.Multiply((sample - min), intervals - 1), size);
int x = Math.Clamp((int)pos.X, 0, intervals - 1);
// reverse y to match magnetometer coordinate system
int y = intervals - 1 - Math.Clamp((int)pos.Y, 0, intervals - 1);
int idx = SenseHatLedMatrix.PositionToIndex(x, y);
// fading
for (int i = 0; i < 64; i++)
{
data[i] = Color.FromArgb((byte)Math.Clamp(data[i].R - 1, 0, 255), data[i].G, data[i].B); ;
}
Color col = data[idx];
col = Color.FromArgb(Math.Clamp(col.R + 20, 0, 255), col.G, col.B);
Vector2 pos2 = new Vector2(sample.X, sample.Y);
Vector2 center2 = Vector2.Multiply(new Vector2(min.X + max.X, min.Y + max.Y), 0.5f);
float max2 = Math.Max(size.X, size.Y);
float distFromCenter = (pos2 - center2).Length();
data[idx] = Color.FromArgb(0, 255, (byte)Math.Clamp(255 * distFromCenter / max2, 0, 255));
ledMatrix.Write(data);
data[idx] = col;
Thread.Sleep(50);
}
}
}
}
} | 40.6 | 241 | 0.473442 | [
"MIT"
] | TheRiflesSpiral/Create-RaspberryPi-dotNET-Core-C-Sharp-IoT-Applications | samples/dotnet.core.iot.csharp.sense.hat/Program.cs | 9,340 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using DG.Tweening;
public class SlimeCard : MonoBehaviour
{
[SerializeField] SpriteRenderer character;
[SerializeField] TMP_Text valueTMP;
public SlimeItem SlimeItem;
public PRS originPRS;
public void Setup(SlimeItem EnemyItem)
{
this.SlimeItem = EnemyItem;
character.sprite = this.SlimeItem.sprite;
valueTMP.text = this.SlimeItem.value.ToString();
}
public void MoveTransform(PRS prs, bool useDotween, float dotweenTime = 0)
{
if (useDotween)
{
transform.DOMove(prs.pos, dotweenTime);
transform.DORotateQuaternion(prs.rot, dotweenTime);
transform.DOScale(prs.scale, dotweenTime);
}
else
{
transform.position = prs.pos;
transform.rotation = prs.rot;
transform.localScale = prs.scale;
}
}
}
| 24.3 | 78 | 0.638889 | [
"MIT"
] | Q-holi/CrossRoad | Assets/Scripts/Slime/SlimeCard.cs | 972 | C# |
//-----------------------------------------------------------------------
// <copyright file="LogInDialog.cs" company="Lost Signal LLC">
// Copyright (c) Lost Signal LLC. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
#if USING_PLAYFAB_SDK
namespace Lost
{
using System.Collections;
using PlayFab.ClientModels;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class LogInDialog : DialogLogic
{
#pragma warning disable 0649
[SerializeField] private LostButton closeButton;
[SerializeField] private TMP_InputField emailInputField;
[SerializeField] private TMP_InputField passwordInputField;
[SerializeField] private Toggle autoLoginToggle;
[SerializeField] private LostButton logInButton;
[SerializeField] private LostButton forgotPasswordButton;
[SerializeField] private LostButton createNewAccountButton;
[SerializeField] private string forgotEmailTemplateId;
#pragma warning restore 0649
private GetPlayerCombinedInfoRequestParams infoRequestParams;
private bool isLeaveGameCoroutineRunning;
private bool isLoginCoroutineRunning;
private bool isForgotPasswordCoroutineRunning;
public void Show(GetPlayerCombinedInfoRequestParams infoRequestParams = null, string email = "")
{
this.infoRequestParams = infoRequestParams;
this.emailInputField.text = email;
this.Dialog.Show();
}
private void OnValidate()
{
this.AssertNotNull(this.closeButton, nameof(this.closeButton));
this.AssertNotNull(this.emailInputField, nameof(this.emailInputField));
this.AssertNotNull(this.passwordInputField, nameof(this.passwordInputField));
this.AssertNotNull(this.autoLoginToggle, nameof(this.autoLoginToggle));
this.AssertNotNull(this.logInButton, nameof(this.logInButton));
this.AssertNotNull(this.forgotPasswordButton, nameof(this.forgotPasswordButton));
this.AssertNotNull(this.createNewAccountButton, nameof(this.createNewAccountButton));
}
protected override void Awake()
{
base.Awake();
this.OnValidate();
this.closeButton.onClick.AddListener(this.OnBackButtonPressed);
this.emailInputField.text = PF.Login.LastLoginEmail;
this.emailInputField.onValueChanged.AddListener(this.UpdateLogInButton);
this.passwordInputField.onValueChanged.AddListener(this.UpdateLogInButton);
this.autoLoginToggle.isOn = PF.Login.HasEverLoggedIn == false || PF.Login.AutoLoginWithDeviceId;
this.forgotPasswordButton.onClick.AddListener(this.ForgotPassword);
this.createNewAccountButton.onClick.AddListener(this.ShowSignUpDialog);
this.logInButton.interactable = false;
this.logInButton.onClick.AddListener(this.LogIn);
}
protected override void OnBackButtonPressed()
{
CoroutineRunner.Instance.StartCoroutine(LeaveGameCoroutine());
IEnumerator LeaveGameCoroutine()
{
if (this.isLeaveGameCoroutineRunning)
{
yield break;
}
this.isLeaveGameCoroutineRunning = true;
this.Dialog.Hide();
yield return WaitForUtil.Seconds(0.25f);
var leaveGamePrompt = PlayFabMessages.ShowExitAppPrompt();
yield return leaveGamePrompt;
if (leaveGamePrompt.Value == YesNoResult.Yes)
{
Platform.QuitApplication();
yield break;
}
this.Dialog.Show();
this.isLeaveGameCoroutineRunning = false;
}
}
private void UpdateLogInButton(string newValue)
{
var email = this.emailInputField.text;
var password = this.passwordInputField.text;
this.logInButton.interactable =
email.IsNullOrWhitespace() == false &&
password.IsNullOrWhitespace() == false &&
password.Length >= 6 &&
password.Length <= 100;
}
private void ShowSignUpDialog()
{
this.Dialog.Hide();
this.ExecuteDelayed(0.25f, () =>
{
DialogManager.GetDialog<SignUpDialog>().Show(this.infoRequestParams, this.emailInputField.text);
});
}
private void LogIn()
{
CoroutineRunner.Instance.StartCoroutine(LogInCoroutine());
IEnumerator LogInCoroutine()
{
if (this.isLoginCoroutineRunning)
{
yield break;
}
this.isLoginCoroutineRunning = true;
var login = PF.Login.LoginWithEmail(false, this.emailInputField.text, this.passwordInputField.text, this.infoRequestParams);
yield return login;
if (login.HasError)
{
yield return PlayFabMessages.HandleError(login.Exception);
}
else
{
PF.Login.LastLoginEmail = this.emailInputField.text;
PF.Login.AutoLoginWithDeviceId = this.autoLoginToggle.isOn;
if (PF.Login.AutoLoginWithDeviceId)
{
PF.Login.LinkDeviceId(PF.Login.DeviceId);
}
this.Dialog.Hide();
}
this.isLoginCoroutineRunning = false;
}
}
private void ForgotPassword()
{
CoroutineRunner.Instance.StartCoroutine(ForgotPasswordCoroutine());
IEnumerator ForgotPasswordCoroutine()
{
if (this.isForgotPasswordCoroutineRunning)
{
yield break;
}
this.isForgotPasswordCoroutineRunning = true;
this.Dialog.Hide();
yield return WaitForUtil.Seconds(.25f);
var forgot = PlayFabMessages.ShowForgotPasswordPrompt(this.emailInputField.text);
if (forgot.Value == YesNoResult.Yes)
{
var accountRecovery = PF.Login.SendAccountRecoveryEmail(this.emailInputField.text, this.forgotEmailTemplateId);
yield return accountRecovery;
if (accountRecovery.HasError)
{
yield return PlayFabMessages.HandleError(accountRecovery.Exception);
}
}
this.Dialog.Show();
this.isForgotPasswordCoroutineRunning = false;
}
}
}
}
#endif
| 34.121951 | 140 | 0.575554 | [
"Unlicense",
"MIT"
] | LostSignal/Lost-Library | Lost/Lost.PlayFab/Runtime/Dialogs/LogInDialog.cs | 6,997 | C# |
using Dahomey.Json.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
namespace Dahomey.Json.Serialization.Converters.DictionaryKeys
{
public class EnumDictionaryKeyConverter<T> : IDictionaryKeyConverter<T>
{
private readonly ByteBufferDictionary<T> _names2Values = new ByteBufferDictionary<T>();
private readonly Dictionary<T, ReadOnlyMemory<byte>> _values2Names = new Dictionary<T, ReadOnlyMemory<byte>>();
public EnumDictionaryKeyConverter()
{
string[] names = Enum.GetNames(typeof(T));
T[] values = Enum.GetValues(typeof(T)).Cast<T>().ToArray();
for (int i = 0; i < names.Length; i++)
{
ReadOnlyMemory<byte> name = Encoding.ASCII.GetBytes(names[i]);
T value = values[i];
_names2Values.Add(name.Span, value);
_values2Names.Add(value, name);
}
}
public T Read(ref Utf8JsonReader reader, JsonSerializerOptions options)
{
ReadOnlySpan<byte> name = reader.GetRawString();
if (!_names2Values.TryGetValue(name, out T key))
{
throw new JsonException();
}
return key;
}
public string ToString(T key)
{
if (!_values2Names.TryGetValue(key, out ReadOnlyMemory<byte> name))
{
throw new JsonException();
}
return Encoding.ASCII.GetString(name.Span);
}
public void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
{
if (!_values2Names.TryGetValue(value, out ReadOnlyMemory<byte> name))
{
throw new JsonException();
}
writer.WritePropertyName(name.Span);
}
}
}
| 30.596774 | 119 | 0.583553 | [
"MIT"
] | vova-lantsov-dev/Dahomey.Json | src/Dahomey.Json/Serialization/Converters/DictionaryKeys/EnumDictionaryKeyConverter.cs | 1,899 | C# |
using System.Web.Mvc;
using Umbraco.Web.Models;
using Umbraco.Web.Mvc;
namespace UmbracoDev.Controllers.Login
{
public class LoginPageController : RenderMvcController
{
public override ActionResult Index(ContentModel content)
{
var model = new LoginPageModel();
return CurrentTemplate(model);
}
}
} | 22.5625 | 64 | 0.66759 | [
"MIT"
] | RyanHelmn/UmbracoDev | UmbracoDev/Controllers/Login/LoginPageController.cs | 363 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace AccountTest
{
class Account
{
private string name; //instance variable
// method that sets the account name in the object
public void SetName(string accountName)
{
name = accountName; //store in name
}
//method that retrieves the account name from the object
public string GetName() //does not require any value as it gits back a value
{
return name; //returns name's value to this method's caller
}
}
}
| 24.75 | 85 | 0.622896 | [
"MIT"
] | venetsia/CSharpRevise | C#/AccountTest-master/Account.cs | 596 | 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("ProjetoTccHBSIS")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ProjetoTccHBSIS")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[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("009ce64d-3005-4a49-b24b-9632ba28d56d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.722222 | 84 | 0.752577 | [
"MIT"
] | AndersonAluiz12/GitC | ProjetoTccHBSIS/ProjetoTccHBSIS/Properties/AssemblyInfo.cs | 1,361 | 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.IO;
using System.Linq;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Options;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation
{
public class FileProviderRazorProjectFileSystemTest
{
[Fact]
public void EnumerateFiles_ReturnsEmptySequenceIfNoCshtmlFilesArePresent()
{
// Arrange
var fileProvider = new TestFileProvider("BasePath");
var file1 = fileProvider.AddFile("/File1.txt", "content");
var file2 = fileProvider.AddFile("/File2.js", "content");
fileProvider.AddDirectoryContent("/", new IFileInfo[] { file1, file2 });
var fileSystem = GetRazorProjectFileSystem(fileProvider);
// Act
var razorFiles = fileSystem.EnumerateItems("/");
// Assert
Assert.Empty(razorFiles);
}
[Fact]
public void EnumerateFiles_ReturnsCshtmlFiles()
{
// Arrange
var fileProvider = new TestFileProvider("BasePath");
var file1 = fileProvider.AddFile("/File1.cshtml", "content");
var file2 = fileProvider.AddFile("/File2.js", "content");
var file3 = fileProvider.AddFile("/File3.cshtml", "content");
fileProvider.AddDirectoryContent("/", new IFileInfo[] { file1, file2, file3 });
var fileSystem = GetRazorProjectFileSystem(fileProvider);
// Act
var razorFiles = fileSystem.EnumerateItems("/");
// Assert
Assert.Collection(
razorFiles.OrderBy(f => f.FilePath),
file =>
{
Assert.Equal("/File1.cshtml", file.FilePath);
Assert.Equal("/", file.BasePath);
Assert.Equal(Path.Combine("BasePath", "File1.cshtml"), file.PhysicalPath);
Assert.Equal("File1.cshtml", file.RelativePhysicalPath);
},
file =>
{
Assert.Equal("/File3.cshtml", file.FilePath);
Assert.Equal("/", file.BasePath);
Assert.Equal(Path.Combine("BasePath", "File3.cshtml"), file.PhysicalPath);
Assert.Equal("File3.cshtml", file.RelativePhysicalPath);
});
}
[Fact]
public void EnumerateFiles_IteratesOverAllCshtmlUnderRoot()
{
// Arrange
var fileProvider = new TestFileProvider("BasePath");
var directory1 = new TestDirectoryFileInfo
{
Name = "Level1-Dir1",
};
var file1 = fileProvider.AddFile("File1.cshtml", "content");
var directory2 = new TestDirectoryFileInfo
{
Name = "Level1-Dir2",
};
fileProvider.AddDirectoryContent("/", new IFileInfo[] { directory1, file1, directory2 });
var file2 = fileProvider.AddFile("/Level1-Dir1/File2.cshtml", "content");
var file3 = fileProvider.AddFile("/Level1-Dir1/File3.cshtml", "content");
var file4 = fileProvider.AddFile("/Level1-Dir1/File4.txt", "content");
var directory3 = new TestDirectoryFileInfo
{
Name = "Level2-Dir1"
};
fileProvider.AddDirectoryContent("/Level1-Dir1", new IFileInfo[] { file2, directory3, file3, file4 });
var file5 = fileProvider.AddFile(Path.Combine("Level1-Dir2", "File5.cshtml"), "content");
fileProvider.AddDirectoryContent("/Level1-Dir2", new IFileInfo[] { file5 });
fileProvider.AddDirectoryContent("/Level1/Level2", new IFileInfo[0]);
var fileSystem = GetRazorProjectFileSystem(fileProvider);
// Act
var razorFiles = fileSystem.EnumerateItems("/");
// Assert
Assert.Collection(razorFiles.OrderBy(f => f.FilePath),
file =>
{
Assert.Equal("/File1.cshtml", file.FilePath);
Assert.Equal("/", file.BasePath);
Assert.Equal(Path.Combine("BasePath", "File1.cshtml"), file.PhysicalPath);
Assert.Equal("File1.cshtml", file.RelativePhysicalPath);
},
file =>
{
Assert.Equal("/Level1-Dir1/File2.cshtml", file.FilePath);
Assert.Equal("/", file.BasePath);
Assert.Equal(Path.Combine("BasePath", "Level1-Dir1", "File2.cshtml"), file.PhysicalPath);
Assert.Equal(Path.Combine("Level1-Dir1", "File2.cshtml"), file.RelativePhysicalPath);
},
file =>
{
Assert.Equal("/Level1-Dir1/File3.cshtml", file.FilePath);
Assert.Equal("/", file.BasePath);
Assert.Equal(Path.Combine("BasePath", "Level1-Dir1", "File3.cshtml"), file.PhysicalPath);
Assert.Equal(Path.Combine("Level1-Dir1", "File3.cshtml"), file.RelativePhysicalPath);
},
file =>
{
Assert.Equal("/Level1-Dir2/File5.cshtml", file.FilePath);
Assert.Equal("/", file.BasePath);
Assert.Equal(Path.Combine("BasePath", "Level1-Dir2", "File5.cshtml"), file.PhysicalPath);
Assert.Equal(Path.Combine("Level1-Dir2", "File5.cshtml"), file.RelativePhysicalPath);
});
}
[Fact]
public void EnumerateFiles_IteratesOverAllCshtmlUnderPath()
{
// Arrange
var fileProvider = new TestFileProvider("BasePath");
var directory1 = new TestDirectoryFileInfo
{
Name = "Level1-Dir1",
};
var file1 = fileProvider.AddFile("/File1.cshtml", "content");
var directory2 = new TestDirectoryFileInfo
{
Name = "Level1-Dir2",
};
fileProvider.AddDirectoryContent("/", new IFileInfo[] { directory1, file1, directory2 });
var file2 = fileProvider.AddFile("/Level1-Dir1/File2.cshtml", "content");
var file3 = fileProvider.AddFile("/Level1-Dir1/File3.cshtml", "content");
var file4 = fileProvider.AddFile("/Level1-Dir1/File4.txt", "content");
var directory3 = new TestDirectoryFileInfo
{
Name = "Level2-Dir1"
};
fileProvider.AddDirectoryContent("/Level1-Dir1", new IFileInfo[] { file2, directory3, file3, file4 });
var file5 = fileProvider.AddFile(Path.Combine("Level1-Dir2", "File5.cshtml"), "content");
fileProvider.AddDirectoryContent("/Level1-Dir2", new IFileInfo[] { file5 });
fileProvider.AddDirectoryContent("/Level1/Level2", new IFileInfo[0]);
var fileSystem = GetRazorProjectFileSystem(fileProvider);
// Act
var razorFiles = fileSystem.EnumerateItems("/Level1-Dir1");
// Assert
Assert.Collection(razorFiles.OrderBy(f => f.FilePath),
file =>
{
Assert.Equal("/File2.cshtml", file.FilePath);
Assert.Equal("/Level1-Dir1", file.BasePath);
Assert.Equal(Path.Combine("BasePath", "Level1-Dir1", "File2.cshtml"), file.PhysicalPath);
Assert.Equal(Path.Combine("Level1-Dir1", "File2.cshtml"), file.RelativePhysicalPath);
},
file =>
{
Assert.Equal("/File3.cshtml", file.FilePath);
Assert.Equal("/Level1-Dir1", file.BasePath);
Assert.Equal(Path.Combine("BasePath", "Level1-Dir1", "File3.cshtml"), file.PhysicalPath);
Assert.Equal(Path.Combine("Level1-Dir1", "File3.cshtml"), file.RelativePhysicalPath);
});
}
[Fact]
public void GetItem_ReturnsFileFromDisk()
{
var fileProvider = new TestFileProvider("BasePath");
var file1 = fileProvider.AddFile("/File1.cshtml", "content");
var file2 = fileProvider.AddFile("/File2.js", "content");
var file3 = fileProvider.AddFile("/File3.cshtml", "content");
fileProvider.AddDirectoryContent("/", new IFileInfo[] { file1, file2, file3 });
var fileSystem = GetRazorProjectFileSystem(fileProvider);
// Act
var item = fileSystem.GetItem("/File3.cshtml", fileKind: null);
// Assert
Assert.True(item.Exists);
Assert.Equal("/File3.cshtml", item.FilePath);
Assert.Equal(string.Empty, item.BasePath);
Assert.Equal(Path.Combine("BasePath", "File3.cshtml"), item.PhysicalPath);
Assert.Equal("File3.cshtml", item.RelativePhysicalPath);
}
[Fact]
public void GetItem_PhysicalPathDoesNotStartWithContentRoot_ReturnsNull()
{
var fileProvider = new TestFileProvider("BasePath2");
var file1 = fileProvider.AddFile("/File1.cshtml", "content");
var file2 = fileProvider.AddFile("/File2.js", "content");
var file3 = fileProvider.AddFile("/File3.cshtml", "content");
fileProvider.AddDirectoryContent("/", new IFileInfo[] { file1, file2, file3 });
var fileSystem = GetRazorProjectFileSystem(fileProvider);
// Act
var item = fileSystem.GetItem("/File3.cshtml", fileKind: null);
// Assert
Assert.True(item.Exists);
Assert.Equal("/File3.cshtml", item.FilePath);
Assert.Equal(string.Empty, item.BasePath);
Assert.Equal(Path.Combine("BasePath2", "File3.cshtml"), item.PhysicalPath);
Assert.Null(item.RelativePhysicalPath);
}
[Fact]
public void GetItem_ReturnsNotFoundResult()
{
// Arrange
var fileProvider = new TestFileProvider("BasePath");
var file = fileProvider.AddFile("/SomeFile.cshtml", "content");
fileProvider.AddDirectoryContent("/", new IFileInfo[] { file });
var fileSystem = GetRazorProjectFileSystem(fileProvider);
// Act
var item = fileSystem.GetItem("/NotFound.cshtml", fileKind: null);
// Assert
Assert.False(item.Exists);
}
private static FileProviderRazorProjectFileSystem GetRazorProjectFileSystem(
TestFileProvider fileProvider,
string contentRootPath = "BasePath")
{
var options = Options.Create(new MvcRazorRuntimeCompilationOptions
{
FileProviders = { fileProvider }
});
var compilationFileProvider = new RuntimeCompilationFileProvider(options);
var fileSystem = new FileProviderRazorProjectFileSystem(
compilationFileProvider,
Mock.Of<IWebHostEnvironment>(e => e.ContentRootPath == contentRootPath));
return fileSystem;
}
}
} | 43.719231 | 114 | 0.567168 | [
"MIT"
] | 48355746/AspNetCore | src/Mvc/Mvc.Razor.RuntimeCompilation/test/FileProviderRazorProjectFileSystemTest.cs | 11,369 | 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.
#nullable disable
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.Venus;
using Microsoft.VisualStudio.Shell;
namespace Microsoft.VisualStudio.LanguageServices.Implementation
{
[ExportWorkspaceService(typeof(IHierarchyItemToProjectIdMap), ServiceLayer.Host), Shared]
internal class HierarchyItemToProjectIdMap : IHierarchyItemToProjectIdMap
{
private readonly VisualStudioWorkspace _workspace;
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public HierarchyItemToProjectIdMap(VisualStudioWorkspace workspace)
=> _workspace = workspace;
public bool TryGetProjectId(IVsHierarchyItem hierarchyItem, string targetFrameworkMoniker, out ProjectId projectId)
{
// A project node is represented in two different hierarchies: the solution's IVsHierarchy (where it is a leaf node)
// and the project's own IVsHierarchy (where it is the root node). The IVsHierarchyItem joins them together for the
// purpose of creating the tree displayed in Solution Explorer. The project's hierarchy is what is passed from the
// project system to the language service, so that's the one the one to query here. To do that we need to get
// the "nested" hierarchy from the IVsHierarchyItem.
var nestedHierarchy = hierarchyItem.HierarchyIdentity.NestedHierarchy;
var nestedHierarchyId = hierarchyItem.HierarchyIdentity.NestedItemID;
if (!nestedHierarchy.TryGetCanonicalName(nestedHierarchyId, out var nestedCanonicalName)
|| !nestedHierarchy.TryGetItemName(nestedHierarchyId, out var nestedName))
{
projectId = null;
return false;
}
// First filter the projects by matching up properties on the input hierarchy against properties on each
// project's hierarchy.
var candidateProjects = _workspace.CurrentSolution.Projects
.Where(p =>
{
// We're about to access various properties of the IVsHierarchy associated with the project.
// The properties supported and the interpretation of their values varies from one project system
// to another. This code is designed with C# and VB in mind, so we need to filter out everything
// else.
if (p.Language != LanguageNames.CSharp
&& p.Language != LanguageNames.VisualBasic)
{
return false;
}
// Here we try to match the hierarchy from Solution Explorer to a hierarchy from the Roslyn project.
// The canonical name of a hierarchy item must be unique _within_ an hierarchy, but since we're
// examining multiple hierarchies the canonical name could be the same. Indeed this happens when two
// project files are in the same folder--they both use the full path to the _folder_ as the canonical
// name. To distinguish them we also examine the "regular" name, which will necessarily be different
// if the two projects are in the same folder.
// Note that if a project has been loaded with Lightweight Solution Load it won't even have a
// hierarchy, so we need to check for null first.
var hierarchy = _workspace.GetHierarchy(p.Id);
if (hierarchy != null
&& hierarchy.TryGetCanonicalName((uint)VSConstants.VSITEMID.Root, out var projectCanonicalName)
&& hierarchy.TryGetItemName((uint)VSConstants.VSITEMID.Root, out var projectName)
&& projectCanonicalName.Equals(nestedCanonicalName, System.StringComparison.OrdinalIgnoreCase)
&& projectName.Equals(nestedName))
{
if (targetFrameworkMoniker == null)
{
return true;
}
return hierarchy.TryGetTargetFrameworkMoniker((uint)VSConstants.VSITEMID.Root, out var projectTargetFrameworkMoniker)
&& projectTargetFrameworkMoniker.Equals(targetFrameworkMoniker);
}
return false;
})
.ToArray();
// If we only have one candidate then no further checks are required.
if (candidateProjects.Length == 1)
{
projectId = candidateProjects[0].Id;
return true;
}
// If we have multiple candidates then we might be dealing with Web Application Projects. In this case
// there will be one main project plus one project for each open aspx/cshtml/vbhtml file, all with
// identical properties on their hierarchies. We can find the main project by taking the first project
// without a ContainedDocument.
foreach (var candidateProject in candidateProjects)
{
if (!candidateProject.DocumentIds.Any(id => ContainedDocument.TryGetContainedDocument(id) != null))
{
projectId = candidateProject.Id;
return true;
}
}
projectId = null;
return false;
}
}
}
| 53.780702 | 194 | 0.629914 | [
"MIT"
] | BrianFreemanAtlanta/roslyn | src/VisualStudio/Core/Def/Implementation/HierarchyItemToProjectIdMap.cs | 6,133 | 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 comprehend-2017-11-27.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.Comprehend.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Comprehend.Model.Internal.MarshallTransformations
{
/// <summary>
/// EntityRecognizerAnnotations Marshaller
/// </summary>
public class EntityRecognizerAnnotationsMarshaller : IRequestMarshaller<EntityRecognizerAnnotations, JsonMarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="requestObject"></param>
/// <param name="context"></param>
/// <returns></returns>
public void Marshall(EntityRecognizerAnnotations requestObject, JsonMarshallerContext context)
{
if(requestObject.IsSetS3Uri())
{
context.Writer.WritePropertyName("S3Uri");
context.Writer.Write(requestObject.S3Uri);
}
}
/// <summary>
/// Singleton Marshaller.
/// </summary>
public readonly static EntityRecognizerAnnotationsMarshaller Instance = new EntityRecognizerAnnotationsMarshaller();
}
} | 33.951613 | 128 | 0.695012 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/Comprehend/Generated/Model/Internal/MarshallTransformations/EntityRecognizerAnnotationsMarshaller.cs | 2,105 | C# |
using Microsoft.Xna.Framework;
using Nez.PhysicsShapes;
namespace Nez.Particles
{
/// <summary>
/// the internal fields are required for the ParticleEmitter to be able to render the Particle
/// </summary>
public class Particle
{
/// <summary>
/// shared Circle used for collisions checks
/// </summary>
static Circle _circleCollisionShape = new Circle(0);
internal System.Numerics.Vector2 position;
internal System.Numerics.Vector2 spawnPosition;
System.Numerics.Vector2 _direction;
internal Color color;
// stored at particle creation time and used for lerping the color
Color _startColor;
// stored at particle creation time and used for lerping the color
Color _finishColor;
internal float rotation;
float _rotationDelta;
float _radialAcceleration;
float _tangentialAcceleration;
float _radius;
float _radiusDelta;
float _angle;
float _degreesPerSecond;
internal float particleSize;
float _particleSizeDelta;
float _timeToLive;
// stored at particle creation time and used for lerping the color
float _particleLifetime;
/// <summary>
/// flag indicating if this particle has already collided so that we know not to move it in the normal fashion
/// </summary>
bool _collided;
System.Numerics.Vector2 _velocity;
public void Explode(float radAcc, float radAccVar)
{
_radialAcceleration = radAcc + Random.NextFloat() * radAccVar;
}
public void Initialize(ParticleEmitterConfig emitterConfig, System.Numerics.Vector2 spawnPosition)
{
_collided = false;
// init the position of the Particle. This is based on the source position of the particle emitter
// plus a configured variance. The Random.minusOneToOne method allows the number to be both positive
// and negative
position.X = emitterConfig.SourcePositionVariance.X * Random.MinusOneToOne();
position.Y = emitterConfig.SourcePositionVariance.Y * Random.MinusOneToOne();
this.spawnPosition = spawnPosition;
// init the direction of the The newAngle is calculated using the angle passed in and the
// angle variance.
var newAngle =
MathHelper.ToRadians(emitterConfig.Angle + emitterConfig.AngleVariance * Random.MinusOneToOne());
// create a new System.Numerics.Vector2 using the newAngle
var vector = new System.Numerics.Vector2(Mathf.Cos(newAngle), Mathf.Sin(newAngle));
// calculate the vectorSpeed using the speed and speedVariance which has been passed in
var vectorSpeed = emitterConfig.Speed + emitterConfig.SpeedVariance * Random.MinusOneToOne();
// the particles direction vector is calculated by taking the vector calculated above and
// multiplying that by the speed
_direction = vector * vectorSpeed;
// calculate the particles life span using the life span and variance passed in
_timeToLive = MathHelper.Max(0,
emitterConfig.ParticleLifespan + emitterConfig.ParticleLifespanVariance * Random.MinusOneToOne());
_particleLifetime = _timeToLive;
var startRadius = emitterConfig.MaxRadius + emitterConfig.MaxRadiusVariance * Random.MinusOneToOne();
var endRadius = emitterConfig.MinRadius + emitterConfig.MinRadiusVariance * Random.MinusOneToOne();
// set the default diameter of the particle from the source position
_radius = startRadius;
_radiusDelta = (endRadius - startRadius) / _timeToLive;
_angle = MathHelper.ToRadians(emitterConfig.Angle + emitterConfig.AngleVariance * Random.MinusOneToOne());
_degreesPerSecond = MathHelper.ToRadians(emitterConfig.RotatePerSecond +
emitterConfig.RotatePerSecondVariance * Random.MinusOneToOne());
_radialAcceleration = emitterConfig.RadialAcceleration +
emitterConfig.RadialAccelVariance * Random.MinusOneToOne();
_tangentialAcceleration = emitterConfig.TangentialAcceleration +
emitterConfig.TangentialAccelVariance * Random.MinusOneToOne();
// calculate the particle size using the start and finish particle sizes
var particleStartSize = emitterConfig.StartParticleSize +
emitterConfig.StartParticleSizeVariance * Random.MinusOneToOne();
var particleFinishSize = emitterConfig.FinishParticleSize +
emitterConfig.FinishParticleSizeVariance * Random.MinusOneToOne();
_particleSizeDelta = (particleFinishSize - particleStartSize) / _timeToLive;
particleSize = MathHelper.Max(0, particleStartSize);
// calculate the color the particle should have when it starts its life. All the elements
// of the start color passed in along with the variance are used to calculate the start color
_startColor = new Color
(
(int) (emitterConfig.StartColor.R + emitterConfig.StartColorVariance.R * Random.MinusOneToOne()),
(int) (emitterConfig.StartColor.G + emitterConfig.StartColorVariance.G * Random.MinusOneToOne()),
(int) (emitterConfig.StartColor.B + emitterConfig.StartColorVariance.B * Random.MinusOneToOne()),
(int) (emitterConfig.StartColor.A + emitterConfig.StartColorVariance.A * Random.MinusOneToOne())
);
color = _startColor;
// calculate the color the particle should be when its life is over. This is done the same
// way as the start color above
_finishColor = new Color
(
(int) (emitterConfig.FinishColor.R + emitterConfig.FinishColorVariance.R * Random.MinusOneToOne()),
(int) (emitterConfig.FinishColor.G + emitterConfig.FinishColorVariance.G * Random.MinusOneToOne()),
(int) (emitterConfig.FinishColor.B + emitterConfig.FinishColorVariance.B * Random.MinusOneToOne()),
(int) (emitterConfig.FinishColor.A + emitterConfig.FinishColorVariance.A * Random.MinusOneToOne())
);
// calculate the rotation
var startA = MathHelper.ToRadians(emitterConfig.RotationStart +
emitterConfig.RotationStartVariance * Random.MinusOneToOne());
var endA = MathHelper.ToRadians(emitterConfig.RotationEnd +
emitterConfig.RotationEndVariance * Random.MinusOneToOne());
rotation = startA;
_rotationDelta = (endA - startA) / _timeToLive;
}
/// <summary>
/// updates the particle. Returns true when the particle is no longer alive
/// </summary>
/// <param name="emitterConfig">Emitter config.</param>
public bool Update(ParticleEmitterConfig emitterConfig, ref ParticleCollisionConfig collisionConfig,
System.Numerics.Vector2 rootPosition)
{
// PART 1: reduce the life span of the particle
_timeToLive -= Time.DeltaTime;
// if the current particle is alive then update it
if (_timeToLive > 0)
{
// only update the particle position if it has not collided. If it has, physics takes over
if (!_collided)
{
// if maxRadius is greater than 0 then the particles are going to spin otherwise they are affected by speed and gravity
if (emitterConfig.EmitterType == ParticleEmitterType.Radial)
{
// PART 2: update the angle of the particle from the radius. This is only done if the particles are rotating
_angle += _degreesPerSecond * Time.DeltaTime;
_radius += _radiusDelta * Time.DeltaTime;
System.Numerics.Vector2 tmp;
tmp.X = -Mathf.Cos(_angle) * _radius;
tmp.Y = -Mathf.Sin(_angle) * _radius;
_velocity = tmp - position;
position = tmp;
}
else
{
System.Numerics.Vector2 tmp, radial, tangential;
radial = System.Numerics.Vector2.Zero;
if (position.X != 0 || position.Y != 0)
radial = System.Numerics.Vector2.Normalize(position);
tangential = radial;
radial = radial * _radialAcceleration;
var newy = tangential.X;
tangential.X = -tangential.Y;
tangential.Y = newy;
tangential = tangential * _tangentialAcceleration;
tmp = radial + tangential + emitterConfig.Gravity;
tmp = tmp * Time.DeltaTime;
_direction = _direction + tmp;
tmp = _direction * Time.DeltaTime;
_velocity = tmp / Time.DeltaTime;
position = position + tmp;
}
}
// update the particles color. we do the lerp from finish-to-start because timeToLive counts from particleLifespan to 0
var t = (_particleLifetime - _timeToLive) / _particleLifetime;
ColorExt.Lerp(ref _startColor, ref _finishColor, out color, t);
// update the particle size
particleSize += _particleSizeDelta * Time.DeltaTime;
particleSize = MathHelper.Max(0, particleSize);
// update the rotation of the particle
rotation += _rotationDelta * Time.DeltaTime;
if (collisionConfig.Enabled)
{
// if we already collided we have to handle the collision response
if (_collided)
{
// handle after collision movement. we need to track velocity for this
_velocity += collisionConfig.Gravity * Time.DeltaTime;
position += _velocity * Time.DeltaTime;
// if we move too slow we die
if (_velocity.LengthSquared() < collisionConfig.MinKillSpeedSquared)
return true;
}
// should we use our spawnPosition as a reference or the parent Transforms position?
var pos = emitterConfig.SimulateInWorldSpace ? spawnPosition : rootPosition;
_circleCollisionShape.RecalculateBounds(particleSize * 0.5f * collisionConfig.RadiusScale,
pos + position);
var neighbors = Physics.BoxcastBroadphase(ref _circleCollisionShape.bounds,
collisionConfig.CollidesWithLayers);
foreach (var neighbor in neighbors)
{
CollisionResult result;
if (_circleCollisionShape.CollidesWithShape(neighbor.Shape, out result))
{
// handle the overlap
position -= result.MinimumTranslationVector;
CalculateCollisionResponseVelocity(collisionConfig.Friction, collisionConfig.Elasticity,
ref result.MinimumTranslationVector);
// handle collision config props
_timeToLive -= _timeToLive * collisionConfig.LifetimeLoss;
_collided = true;
}
}
}
}
else
{
// timeToLive expired. were done
return true;
}
return false;
}
/// <summary>
/// given the relative velocity between the two objects and the MTV this method modifies the relativeVelocity to make it a collision
/// response.
/// </summary>
/// <param name="relativeVelocity">Relative velocity.</param>
/// <param name="minimumTranslationVector">Minimum translation vector.</param>
void CalculateCollisionResponseVelocity(float friction, float elasticity, ref System.Numerics.Vector2 minimumTranslationVector)
{
// first, we get the normalized MTV in the opposite direction: the surface normal
var inverseMTV = minimumTranslationVector * -1f;
var normal = System.Numerics.Vector2.Normalize(inverseMTV);
// the velocity is decomposed along the normal of the collision and the plane of collision.
// The elasticity will affect the response along the normal (normalVelocityComponent) and the friction will affect
// the tangential component of the velocity (tangentialVelocityComponent)
var n = System.Numerics.Vector2.Dot(_velocity, normal);
var normalVelocityComponent = normal * n;
var tangentialVelocityComponent = _velocity - normalVelocityComponent;
if (n > 0.0f)
normalVelocityComponent = System.Numerics.Vector2.Zero;
// elasticity affects the normal component of the velocity and friction affects the tangential component
var responseVelocity =
-(1.0f + elasticity) * normalVelocityComponent - friction * tangentialVelocityComponent;
_velocity += responseVelocity;
}
}
} | 40.083045 | 134 | 0.721685 | [
"Apache-2.0",
"MIT"
] | Paramecium13/Nez | Nez.Portable/ECS/Components/Renderables/Particles/Particle.cs | 11,586 | C# |
using Microsoft.EntityFrameworkCore;
using PeopleViewer.Common;
namespace PersonDataReader.SQL
{
public class PersonContext : DbContext
{
public PersonContext(DbContextOptions<PersonContext> options)
: base(options)
{ }
public DbSet<Person> People { get; set; }
}
}
| 21.133333 | 69 | 0.66877 | [
"MIT"
] | filipjohnsson1989/dependency-injection-resources | core22/module4/after/PersonDataReader.SQL/PersonContext.cs | 319 | C# |
/*
* Marketplace
*
* API Cloud Loyalty LTM - Webpremios
*
* OpenAPI spec version: 1.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace IO.Swagger.Models
{
/// <summary>
///
/// </summary>
[DataContract]
public partial class Participant : IEquatable<Participant>
{
/// <summary>
/// Tipo de pessoa
/// </summary>
/// <value>Tipo de pessoa</value>
public enum PersontypeEnum
{
/// <summary>
/// Enum INDIVIDUALEnum for "INDIVIDUAL"
/// </summary>
[EnumMember(Value = "INDIVIDUAL")]
INDIVIDUALEnum,
/// <summary>
/// Enum COMPANYEnum for "COMPANY"
/// </summary>
[EnumMember(Value = "COMPANY")]
COMPANYEnum
}
/// <summary>
/// Gênero
/// </summary>
/// <value>Gênero</value>
public enum GenderTypeEnum
{
/// <summary>
/// Enum MALEEnum for "MALE"
/// </summary>
[EnumMember(Value = "MALE")]
MALEEnum,
/// <summary>
/// Enum FEMALEEnum for "FEMALE"
/// </summary>
[EnumMember(Value = "FEMALE")]
FEMALEEnum,
/// <summary>
/// Enum UNINFORMEDEnum for "UNINFORMED"
/// </summary>
[EnumMember(Value = "UNINFORMED")]
UNINFORMEDEnum
}
/// <summary>
/// Estado civil
/// </summary>
/// <value>Estado civil</value>
public enum MaritalStatusEnum
{
/// <summary>
/// Enum MARRIEDEnum for "MARRIED"
/// </summary>
[EnumMember(Value = "MARRIED")]
MARRIEDEnum,
/// <summary>
/// Enum DIVORCEDEnum for "DIVORCED"
/// </summary>
[EnumMember(Value = "DIVORCED")]
DIVORCEDEnum,
/// <summary>
/// Enum SINGLEEnum for "SINGLE"
/// </summary>
[EnumMember(Value = "SINGLE")]
SINGLEEnum,
/// <summary>
/// Enum WIDOWEREnum for "WIDOWER"
/// </summary>
[EnumMember(Value = "WIDOWER")]
WIDOWEREnum,
/// <summary>
/// Enum SEPARATEDEnum for "SEPARATED"
/// </summary>
[EnumMember(Value = "SEPARATED")]
SEPARATEDEnum,
/// <summary>
/// Enum UNINFORMEDEnum for "UNINFORMED"
/// </summary>
[EnumMember(Value = "UNINFORMED")]
UNINFORMEDEnum
}
/// <summary>
/// Status do participante
/// </summary>
/// <value>Status do participante</value>
public enum StatusEnum
{
/// <summary>
/// Enum ACTIVEEnum for "ACTIVE"
/// </summary>
[EnumMember(Value = "ACTIVE")]
ACTIVEEnum,
/// <summary>
/// Enum SIGNPENDANTEnum for "SIGNPENDANT"
/// </summary>
[EnumMember(Value = "SIGNPENDANT")]
SIGNPENDANTEnum,
/// <summary>
/// Enum INACTIVEEnum for "INACTIVE"
/// </summary>
[EnumMember(Value = "INACTIVE")]
INACTIVEEnum,
/// <summary>
/// Enum WAITEnum for "WAIT"
/// </summary>
[EnumMember(Value = "WAIT")]
WAITEnum,
/// <summary>
/// Enum PENDINGVALIDATIONEnum for "PENDINGVALIDATION"
/// </summary>
[EnumMember(Value = "PENDINGVALIDATION")]
PENDINGVALIDATIONEnum,
/// <summary>
/// Enum PENDINGREGISTRATIONEnum for "PENDINGREGISTRATION"
/// </summary>
[EnumMember(Value = "PENDINGREGISTRATION")]
PENDINGREGISTRATIONEnum,
/// <summary>
/// Enum PENDINGPAYMENTEnum for "PENDINGPAYMENT"
/// </summary>
[EnumMember(Value = "PENDINGPAYMENT")]
PENDINGPAYMENTEnum,
/// <summary>
/// Enum CANCELLEDCARDEnum for "CANCELLEDCARD"
/// </summary>
[EnumMember(Value = "CANCELLEDCARD")]
CANCELLEDCARDEnum,
/// <summary>
/// Enum STANDBYWITHOUTPRIZEEnum for "STANDBYWITHOUTPRIZE"
/// </summary>
[EnumMember(Value = "STANDBYWITHOUTPRIZE")]
STANDBYWITHOUTPRIZEEnum,
/// <summary>
/// Enum PASSWORDSIGNPENDANTEnum for "PASSWORDSIGNPENDANT"
/// </summary>
[EnumMember(Value = "PASSWORDSIGNPENDANT")]
PASSWORDSIGNPENDANTEnum
}
/// <summary>
/// Tipo de pessoa
/// </summary>
/// <value>Tipo de pessoa</value>
[DataMember(Name="persontype")]
public PersontypeEnum? Persontype { get; set; }
/// <summary>
/// Gênero
/// </summary>
/// <value>Gênero</value>
[DataMember(Name="genderType")]
public GenderTypeEnum? GenderType { get; set; }
/// <summary>
/// Estado civil
/// </summary>
/// <value>Estado civil</value>
[DataMember(Name="maritalStatus")]
public MaritalStatusEnum? MaritalStatus { get; set; }
/// <summary>
/// Status do participante
/// </summary>
/// <value>Status do participante</value>
[DataMember(Name="status")]
public StatusEnum? Status { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="Participant" /> class.
/// </summary>
/// <param name="Id">Identificador do participante.</param>
/// <param name="Name">Nome do participante.</param>
/// <param name="Username">Login do participante.</param>
/// <param name="DocumentNumber">Documento ex: CPF, CNPJ.</param>
/// <param name="Rg">RG do participante.</param>
/// <param name="BirthDate">Data de nascimento.</param>
/// <param name="Persontype">Tipo de pessoa.</param>
/// <param name="GenderType">Gênero.</param>
/// <param name="MaritalStatus">Estado civil.</param>
/// <param name="Status">Status do participante.</param>
/// <param name="Emails">E-mails.</param>
/// <param name="Phones">Telefones.</param>
/// <param name="Address">Address.</param>
public Participant(string Id = default(string), string Name = default(string), string Username = default(string), string DocumentNumber = default(string), string Rg = default(string), DateTime? BirthDate = default(DateTime?), PersontypeEnum? Persontype = default(PersontypeEnum?), GenderTypeEnum? GenderType = default(GenderTypeEnum?), MaritalStatusEnum? MaritalStatus = default(MaritalStatusEnum?), StatusEnum? Status = default(StatusEnum?), List<Email> Emails = default(List<Email>), List<Phone> Phones = default(List<Phone>), AddressReq Address = default(AddressReq))
{
this.Id = Id;
this.Name = Name;
this.Username = Username;
this.DocumentNumber = DocumentNumber;
this.Rg = Rg;
this.BirthDate = BirthDate;
this.Persontype = Persontype;
this.GenderType = GenderType;
this.MaritalStatus = MaritalStatus;
this.Status = Status;
this.Emails = Emails;
this.Phones = Phones;
this.Address = Address;
}
/// <summary>
/// Identificador do participante
/// </summary>
/// <value>Identificador do participante</value>
[DataMember(Name="id")]
public string Id { get; set; }
/// <summary>
/// Nome do participante
/// </summary>
/// <value>Nome do participante</value>
[DataMember(Name="name")]
public string Name { get; set; }
/// <summary>
/// Login do participante
/// </summary>
/// <value>Login do participante</value>
[DataMember(Name="username")]
public string Username { get; set; }
/// <summary>
/// Documento ex: CPF, CNPJ
/// </summary>
/// <value>Documento ex: CPF, CNPJ</value>
[DataMember(Name="documentNumber")]
public string DocumentNumber { get; set; }
/// <summary>
/// RG do participante
/// </summary>
/// <value>RG do participante</value>
[DataMember(Name="rg")]
public string Rg { get; set; }
/// <summary>
/// Data de nascimento
/// </summary>
/// <value>Data de nascimento</value>
[DataMember(Name="birthDate")]
public DateTime? BirthDate { get; set; }
/// <summary>
/// E-mails
/// </summary>
/// <value>E-mails</value>
[DataMember(Name="emails")]
public List<Email> Emails { get; set; }
/// <summary>
/// Telefones
/// </summary>
/// <value>Telefones</value>
[DataMember(Name="phones")]
public List<Phone> Phones { get; set; }
/// <summary>
/// Gets or Sets Address
/// </summary>
[DataMember(Name="address")]
public AddressReq Address { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class Participant {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" Username: ").Append(Username).Append("\n");
sb.Append(" DocumentNumber: ").Append(DocumentNumber).Append("\n");
sb.Append(" Rg: ").Append(Rg).Append("\n");
sb.Append(" BirthDate: ").Append(BirthDate).Append("\n");
sb.Append(" Persontype: ").Append(Persontype).Append("\n");
sb.Append(" GenderType: ").Append(GenderType).Append("\n");
sb.Append(" MaritalStatus: ").Append(MaritalStatus).Append("\n");
sb.Append(" Status: ").Append(Status).Append("\n");
sb.Append(" Emails: ").Append(Emails).Append("\n");
sb.Append(" Phones: ").Append(Phones).Append("\n");
sb.Append(" Address: ").Append(Address).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((Participant)obj);
}
/// <summary>
/// Returns true if Participant instances are equal
/// </summary>
/// <param name="other">Instance of Participant to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(Participant other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.Name == other.Name ||
this.Name != null &&
this.Name.Equals(other.Name)
) &&
(
this.Username == other.Username ||
this.Username != null &&
this.Username.Equals(other.Username)
) &&
(
this.DocumentNumber == other.DocumentNumber ||
this.DocumentNumber != null &&
this.DocumentNumber.Equals(other.DocumentNumber)
) &&
(
this.Rg == other.Rg ||
this.Rg != null &&
this.Rg.Equals(other.Rg)
) &&
(
this.BirthDate == other.BirthDate ||
this.BirthDate != null &&
this.BirthDate.Equals(other.BirthDate)
) &&
(
this.Persontype == other.Persontype ||
this.Persontype != null &&
this.Persontype.Equals(other.Persontype)
) &&
(
this.GenderType == other.GenderType ||
this.GenderType != null &&
this.GenderType.Equals(other.GenderType)
) &&
(
this.MaritalStatus == other.MaritalStatus ||
this.MaritalStatus != null &&
this.MaritalStatus.Equals(other.MaritalStatus)
) &&
(
this.Status == other.Status ||
this.Status != null &&
this.Status.Equals(other.Status)
) &&
(
this.Emails == other.Emails ||
this.Emails != null &&
this.Emails.SequenceEqual(other.Emails)
) &&
(
this.Phones == other.Phones ||
this.Phones != null &&
this.Phones.SequenceEqual(other.Phones)
) &&
(
this.Address == other.Address ||
this.Address != null &&
this.Address.Equals(other.Address)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.Name != null)
hash = hash * 59 + this.Name.GetHashCode();
if (this.Username != null)
hash = hash * 59 + this.Username.GetHashCode();
if (this.DocumentNumber != null)
hash = hash * 59 + this.DocumentNumber.GetHashCode();
if (this.Rg != null)
hash = hash * 59 + this.Rg.GetHashCode();
if (this.BirthDate != null)
hash = hash * 59 + this.BirthDate.GetHashCode();
if (this.Persontype != null)
hash = hash * 59 + this.Persontype.GetHashCode();
if (this.GenderType != null)
hash = hash * 59 + this.GenderType.GetHashCode();
if (this.MaritalStatus != null)
hash = hash * 59 + this.MaritalStatus.GetHashCode();
if (this.Status != null)
hash = hash * 59 + this.Status.GetHashCode();
if (this.Emails != null)
hash = hash * 59 + this.Emails.GetHashCode();
if (this.Phones != null)
hash = hash * 59 + this.Phones.GetHashCode();
if (this.Address != null)
hash = hash * 59 + this.Address.GetHashCode();
return hash;
}
}
#region Operators
public static bool operator ==(Participant left, Participant right)
{
return Equals(left, right);
}
public static bool operator !=(Participant left, Participant right)
{
return !Equals(left, right);
}
#endregion Operators
}
}
| 35.966667 | 578 | 0.480769 | [
"MIT"
] | ltm-arquitetura/webpremios-csharp-sdks | src/IO.Swagger/Models/Participant.cs | 17,269 | 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 chime-2018-05-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.Chime.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Chime.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for BatchSuspendUser operation
/// </summary>
public class BatchSuspendUserResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
BatchSuspendUserResponse response = new BatchSuspendUserResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("UserErrors", targetDepth))
{
var unmarshaller = new ListUnmarshaller<UserError, UserErrorUnmarshaller>(UserErrorUnmarshaller.Instance);
response.UserErrors = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null))
{
if (errorResponse.Code != null && errorResponse.Code.Equals("BadRequestException"))
{
return BadRequestExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ForbiddenException"))
{
return ForbiddenExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("NotFoundException"))
{
return NotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ServiceFailureException"))
{
return ServiceFailureExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ServiceUnavailableException"))
{
return ServiceUnavailableExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ThrottledClientException"))
{
return ThrottledClientExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("UnauthorizedClientException"))
{
return UnauthorizedClientExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonChimeException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static BatchSuspendUserResponseUnmarshaller _instance = new BatchSuspendUserResponseUnmarshaller();
internal static BatchSuspendUserResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static BatchSuspendUserResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 41.626866 | 188 | 0.639118 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/Chime/Generated/Model/Internal/MarshallTransformations/BatchSuspendUserResponseUnmarshaller.cs | 5,578 | C# |
//******************************
// Written by Peter Golde
// Copyright (c) 2004-2005, Wintellect
//
// Use and restribution of this code is subject to the license agreement
// contained in the file "License.txt" accompanying this file.
//******************************
using System;
using System.Diagnostics;
using System.Collections.Generic;
namespace Wintellect.PowerCollections
{
/// <summary>
/// Describes what to do if a key is already in the tree when doing an
/// insertion.
/// </summary>
internal enum DuplicatePolicy {
InsertFirst, // Insert a new node before duplicates
InsertLast, // Insert a new node after duplicates
ReplaceFirst, // Replace the first of the duplicate nodes
ReplaceLast, // Replace the last of the duplicate nodes
DoNothing // Do nothing to the tree
};
/// <summary>
/// The base implementation for various collections classes that use Red-Black trees
/// as part of their implementation. This class should not (and can not) be
/// used directly by end users; it's only for internal use by the collections package.
/// </summary>
/// <remarks>
/// The Red-Black tree manages items of type T, and uses a IComparer<T> that
/// compares items to sort the tree. Multiple items can compare equal and be stored
/// in the tree. Insert, Delete, and Find operations are provided in their full generality;
/// all operations allow dealing with either the first or last of items that compare equal.
///</remarks>
#if !PCL
[Serializable]
#endif
internal class RedBlackTree<T>: IEnumerable<T> {
private IComparer<T> comparer; // interface for comparing elements, only Compare is used.
private Node root; // The root of the tree. Can be null when tree is empty.
private int count; // The count of elements in the tree.
private int changeStamp; // An integer that is changed every time the tree structurally changes.
// Used so that enumerations throw an exception if the tree is changed
// during enumeration.
private Node[] stack; // A stack of nodes. This is cached locally to avoid constant re-allocated it.
/// <summary>
/// Create an array of Nodes big enough for any path from top
/// to bottom. This is cached, and reused from call-to-call, so only one
/// can be around at a time per tree.
/// </summary>
/// <returns>The node stack.</returns>
private Node[] GetNodeStack()
{
// Maximum depth needed is 2 * lg count + 1.
int maxDepth;
if (count < 0x400)
maxDepth = 21;
else if (count < 0x10000)
maxDepth = 41;
else
maxDepth = 65;
if (stack == null || stack.Length < maxDepth)
stack = new Node[maxDepth];
return stack;
}
/// <summary>
/// The class that is each node in the red-black tree.
/// </summary>
#if !PCL
[Serializable]
#endif
private class Node {
public Node left, right;
public T item;
private const uint REDMASK = 0x80000000;
private uint count;
/// <summary>
/// Is this a red node?
/// </summary>
public bool IsRed {
get { return (count & REDMASK) != 0; }
set {
if (value)
count |= REDMASK;
else
count &= ~REDMASK;
}
}
/// <summary>
/// Get or set the Count field -- a 31-bit field
/// that holds the number of nodes at or below this
/// level.
/// </summary>
public int Count
{
get { return (int)(count & ~REDMASK); }
set { count = (count & REDMASK) | (uint)value; }
}
/// <summary>
/// Add one to the Count.
/// </summary>
public void IncrementCount()
{
++count;
}
/// <summary>
/// Subtract one from the Count. The current
/// Count must be non-zero.
/// </summary>
public void DecrementCount()
{
Debug.Assert(Count != 0);
--count;
}
/// <summary>
/// Clones a node and all its descendants.
/// </summary>
/// <returns>The cloned node.</returns>
public Node Clone()
{
Node newNode = new Node();
newNode.item = item;
newNode.count = count;
if (left != null)
newNode.left = left.Clone();
if (right != null)
newNode.right = right.Clone();
return newNode;
}
}
/// <summary>
/// Must be called whenever there is a structural change in the tree. Causes
/// changeStamp to be changed, which causes any in-progress enumerations
/// to throw exceptions.
/// </summary>
internal void StopEnumerations()
{
++changeStamp;
}
/// <summary>
/// Checks the given stamp against the current change stamp. If different, the
/// collection has changed during enumeration and an InvalidOperationException
/// must be thrown
/// </summary>
/// <param name="startStamp">changeStamp at the start of the enumeration.</param>
private void CheckEnumerationStamp(int startStamp)
{
if (startStamp != changeStamp) {
throw new InvalidOperationException(Strings.ChangeDuringEnumeration);
}
}
/// <summary>
/// Initialize a red-black tree, using the given interface instance to compare elements. Only
/// Compare is used on the IComparer interface.
/// </summary>
/// <param name="comparer">The IComparer<T> used to sort keys.</param>
public RedBlackTree(IComparer<T> comparer) {
this.comparer = comparer;
this.count = 0;
this.root = null;
}
/// <summary>
/// Returns the number of elements in the tree.
/// </summary>
public int ElementCount {
get {
return count;
}
}
/// <summary>
/// Clone the tree, returning a new tree containing the same items. Should
/// take O(N) take.
/// </summary>
/// <returns>Clone version of this tree.</returns>
public RedBlackTree<T> Clone()
{
RedBlackTree<T> newTree = new RedBlackTree<T>(comparer);
newTree.count = this.count;
if (this.root != null)
newTree.root = this.root.Clone();
return newTree;
}
/// <summary>
/// Finds the key in the tree. If multiple items in the tree have
/// compare equal to the key, finds the first or last one. Optionally replaces the item
/// with the one searched for.
/// </summary>
/// <param name="key">Key to search for.</param>
/// <param name="findFirst">If true, find the first of duplicates, else finds the last of duplicates.</param>
/// <param name="replace">If true, replaces the item with key (if function returns true)</param>
/// <param name="item">Returns the found item, before replacing (if function returns true).</param>
/// <returns>True if the key was found.</returns>
public bool Find(T key, bool findFirst, bool replace, out T item) {
Node current = root; // current search location in the tree
Node found = null; // last node found with the key, or null if none.
while (current != null) {
int compare = comparer.Compare(key, current.item);
if (compare < 0) {
current = current.left;
}
else if (compare > 0) {
current = current.right;
}
else {
// Go left/right on equality to find first/last of elements with this key.
Debug.Assert(compare == 0);
found = current;
if (findFirst)
current = current.left;
else
current = current.right;
}
}
if (found != null) {
item = found.item;
if (replace)
found.item = key;
return true;
}
else {
item = default(T);
return false;
}
}
/// <summary>
/// Finds the index of the key in the tree. If multiple items in the tree have
/// compare equal to the key, finds the first or last one.
/// </summary>
/// <param name="key">Key to search for.</param>
/// <param name="findFirst">If true, find the first of duplicates, else finds the last of duplicates.</param>
/// <returns>Index of the item found if the key was found, -1 if not found.</returns>
public int FindIndex(T key, bool findFirst)
{
T dummy;
if (findFirst)
return FirstItemInRange(EqualRangeTester(key), out dummy);
else
return LastItemInRange(EqualRangeTester(key), out dummy);
}
/// <summary>
/// Find the item at a particular index in the tree.
/// </summary>
/// <param name="index">The zero-based index of the item. Must be >= 0 and < Count.</param>
/// <returns>The item at the particular index.</returns>
public T GetItemByIndex(int index)
{
if (index < 0 || index >= count)
throw new ArgumentOutOfRangeException("index");
Node current = root; // current search location in the tree
for (; ; ) {
int leftCount;
if (current.left != null)
leftCount = current.left.Count;
else
leftCount = 0;
if (leftCount > index)
current = current.left;
else if (leftCount == index)
return current.item;
else {
index -= leftCount + 1;
current = current.right;
}
}
}
/// <summary>
/// Insert a new node into the tree, maintaining the red-black invariants.
/// </summary>
/// <remarks>Algorithm from Sedgewick, "Algorithms".</remarks>
/// <param name="item">The new item to insert</param>
/// <param name="dupPolicy">What to do if equal item is already present.</param>
/// <param name="previous">If false, returned, the previous item.</param>
/// <returns>false if duplicate exists, otherwise true.</returns>
public bool Insert(T item, DuplicatePolicy dupPolicy, out T previous) {
Node node = root;
Node parent = null, gparent = null, ggparent = null; // parent, grand, a great-grantparent of node.
bool wentLeft = false, wentRight = false; // direction from parent to node.
bool rotated;
Node duplicateFound = null;
// The tree may be changed.
StopEnumerations();
// We increment counts on the way down the tree. If we end up not inserting an items due
// to a duplicate, we need a stack to adjust the counts back. We don't need the stack if the duplicate
// policy means that we will always do an insertion.
bool needStack = !((dupPolicy == DuplicatePolicy.InsertFirst) || (dupPolicy == DuplicatePolicy.InsertLast));
Node[] nodeStack = null;
int nodeStackPtr = 0; // first free item on the stack.
if (needStack)
nodeStack = GetNodeStack();
while (node != null) {
// If we find a node with two red children, split it so it doesn't cause problems
// when inserting a node.
if (node.left != null && node.left.IsRed && node.right != null && node.right.IsRed) {
node = InsertSplit(ggparent, gparent, parent, node, out rotated);
if (needStack && rotated) {
nodeStackPtr -= 2;
if (nodeStackPtr < 0)
nodeStackPtr = 0;
}
}
// Keep track of parent, grandparent, great-grand parent.
ggparent = gparent; gparent = parent; parent = node;
// Compare the key and the node.
int compare = comparer.Compare(item, node.item);
if (compare == 0) {
// Found a node with the data already. Check duplicate policy.
if (dupPolicy == DuplicatePolicy.DoNothing) {
previous = node.item;
// Didn't insert after all. Return counts back to their previous value.
for (int i = 0; i < nodeStackPtr; ++i)
nodeStack[i].DecrementCount();
return false;
}
else if (dupPolicy == DuplicatePolicy.InsertFirst || dupPolicy == DuplicatePolicy.ReplaceFirst) {
// Insert first by treating the key as less than nodes in the tree.
duplicateFound = node;
compare = -1;
}
else {
Debug.Assert(dupPolicy == DuplicatePolicy.InsertLast || dupPolicy == DuplicatePolicy.ReplaceLast);
// Insert last by treating the key as greater than nodes in the tree.
duplicateFound = node;
compare = 1;
}
}
Debug.Assert(compare != 0);
node.IncrementCount();
if (needStack)
nodeStack[nodeStackPtr++] = node;
// Move to the left or right as needed to find the insertion point.
if (compare < 0) {
node = node.left;
wentLeft = true; wentRight = false;
}
else {
node = node.right;
wentRight = true; wentLeft = false;
}
}
if (duplicateFound != null) {
previous = duplicateFound.item;
// Are we replacing instread of inserting?
if (duplicateFound != null && (dupPolicy == DuplicatePolicy.ReplaceFirst || dupPolicy == DuplicatePolicy.ReplaceLast)) {
duplicateFound.item = item;
// Didn't insert after all. Return counts back to their previous value.
for (int i = 0; i < nodeStackPtr; ++i)
nodeStack[i].DecrementCount();
return false;
}
}
else {
previous = default(T);
}
// Create a new node.
node = new Node();
node.item = item;
node.Count = 1;
// Link the node into the tree.
if (wentLeft)
parent.left = node;
else if (wentRight)
parent.right = node;
else {
Debug.Assert(root == null);
root = node;
}
// Maintain the red-black policy.
InsertSplit(ggparent, gparent, parent, node, out rotated);
// We've added a node to the tree, so update the count.
count += 1;
return (duplicateFound == null);
}
/// <summary>
/// Split a node with two red children (a 4-node in the 2-3-4 tree formalism), as
/// part of an insert operation.
/// </summary>
/// <param name="ggparent">great grand-parent of "node", can be null near root</param>
/// <param name="gparent">grand-parent of "node", can be null near root</param>
/// <param name="parent">parent of "node", can be null near root</param>
/// <param name="node">Node to split, can't be null</param>
/// <param name="rotated">Indicates that rotation(s) occurred in the tree.</param>
/// <returns>Node to continue searching from.</returns>
private Node InsertSplit(Node ggparent, Node gparent, Node parent, Node node, out bool rotated) {
if (node != root)
node.IsRed = true;
if (node.left != null)
node.left.IsRed = false;
if (node.right != null)
node.right.IsRed = false;
if (parent != null && parent.IsRed) {
// Since parent is red, gparent can't be null (root is always black). ggparent
// might be null, however.
Debug.Assert(gparent != null);
// if links from gparent and parent are opposite (left/right or right/left),
// then rotate.
if ((gparent.left == parent) != (parent.left == node)) {
Rotate(gparent, parent, node);
parent = node;
}
gparent.IsRed = true;
// Do a rotate to prevent two red links in a row.
Rotate(ggparent, gparent, parent);
parent.IsRed = false;
rotated = true;
return parent;
}
else {
rotated = false;
return node;
}
}
/// <summary>
/// Performs a rotation involving the node, it's child and grandchild. The counts of
/// childs and grand-child are set the correct values from their children; this is important
/// if they have been adjusted on the way down the try as part of an insert/delete.
/// </summary>
/// <param name="node">Top node of the rotation. Can be null if child==root.</param>
/// <param name="child">One child of "node". Not null.</param>
/// <param name="gchild">One child of "child". Not null.</param>
private void Rotate(Node node, Node child, Node gchild) {
if (gchild == child.left) {
child.left = gchild.right;
gchild.right = child;
}
else {
Debug.Assert(gchild == child.right);
child.right = gchild.left;
gchild.left = child;
}
// Restore the counts.
child.Count = (child.left != null ? child.left.Count : 0) + (child.right != null ? child.right.Count : 0) + 1;
gchild.Count = (gchild.left != null ? gchild.left.Count : 0) + (gchild.right != null ? gchild.right.Count : 0) + 1;
if (node == null) {
Debug.Assert(child == root);
root = gchild;
}
else if (child == node.left) {
node.left = gchild;
}
else {
Debug.Assert(child == node.right);
node.right = gchild;
}
}
/// <summary>
/// Deletes a key from the tree. If multiple elements are equal to key,
/// deletes the first or last. If no element is equal to the key,
/// returns false.
/// </summary>
/// <remarks>Top-down algorithm from Weiss. Basic plan is to move down in the tree,
/// rotating and recoloring along the way to always keep the current node red, which
/// ensures that the node we delete is red. The details are quite complex, however! </remarks>
/// <param name="key">Key to delete.</param>
/// <param name="deleteFirst">Which item to delete if multiple are equal to key. True to delete the first, false to delete last.</param>
/// <param name="item">Returns the item that was deleted, if true returned.</param>
/// <returns>True if an element was deleted, false if no element had
/// specified key.</returns>
public bool Delete(T key, bool deleteFirst, out T item)
{
return DeleteItemFromRange(EqualRangeTester(key), deleteFirst, out item);
}
///
/// <summary>
/// Enumerate all the items in-order
/// </summary>
/// <returns>An enumerator for all the items, in order.</returns>
/// <exception cref="InvalidOperationException">The tree has an item added or deleted during the enumeration.</exception>
public IEnumerator<T> GetEnumerator()
{
return EnumerateRange(EntireRangeTester).GetEnumerator();
}
/// <summary>
/// Enumerate all the items in-order
/// </summary>
/// <returns>An enumerator for all the items, in order.</returns>
/// <exception cref="InvalidOperationException">The tree has an item added or deleted during the enumeration.</exception>
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#region Ranges
/// <summary>
/// A delegate that tests if an item is within a custom range. The range must be a contiguous
/// range of items with the ordering of this tree. The range test function must test
/// if an item is before, withing, or after the range.
/// </summary>
/// <param name="item">Item to test against the range.</param>
/// <returns>Returns negative if item is before the range, zero if item is withing the range,
/// and positive if item is after the range.</returns>
public delegate int RangeTester(T item);
/// <summary>
/// Gets a range tester that defines a range by first and last items.
/// </summary>
/// <param name="useFirst">If true, bound the range on the bottom by first.</param>
/// <param name="first">If useFirst is true, the inclusive lower bound.</param>
/// <param name="useLast">If true, bound the range on the top by last.</param>
/// <param name="last">If useLast is true, the exclusive upper bound.</param>
/// <returns>A RangeTester delegate that tests for an item in the given range.</returns>
public RangeTester BoundedRangeTester(bool useFirst, T first, bool useLast, T last)
{
return delegate(T item) {
if (useFirst && comparer.Compare(first, item) > 0)
return -1; // item is before first.
else if (useLast && comparer.Compare(last, item) <= 0)
return 1; // item is after or equal to last.
else
return 0; // item is greater or equal to first, and less than last.
};
}
/// <summary>
/// Gets a range tester that defines a range by first and last items.
/// </summary>
/// <param name="first">The lower bound.</param>
/// <param name="firstInclusive">True if the lower bound is inclusive, false if exclusive.</param>
/// <param name="last">The upper bound.</param>
/// <param name="lastInclusive">True if the upper bound is inclusive, false if exclusive.</param>
/// <returns>A RangeTester delegate that tests for an item in the given range.</returns>
public RangeTester DoubleBoundedRangeTester(T first, bool firstInclusive, T last, bool lastInclusive)
{
return delegate(T item) {
if (firstInclusive) {
if (comparer.Compare(first, item) > 0)
return -1; // item is before first.
}
else {
if (comparer.Compare(first, item) >= 0)
return -1; // item is before or equal to first.
}
if (lastInclusive) {
if (comparer.Compare(last, item) < 0)
return 1; // item is after last.
}
else {
if (comparer.Compare(last, item) <= 0)
return 1; // item is after or equal to last
}
return 0; // item is between first and last.
};
}
/// <summary>
/// Gets a range tester that defines a range by a lower bound.
/// </summary>
/// <param name="first">The lower bound.</param>
/// <param name="inclusive">True if the lower bound is inclusive, false if exclusive.</param>
/// <returns>A RangeTester delegate that tests for an item in the given range.</returns>
public RangeTester LowerBoundedRangeTester(T first, bool inclusive)
{
return delegate(T item) {
if (inclusive) {
if (comparer.Compare(first, item) > 0)
return -1; // item is before first.
else
return 0; // item is after or equal to first
}
else {
if (comparer.Compare(first, item) >= 0)
return -1; // item is before or equal to first.
else
return 0; // item is after first
}
};
}
/// <summary>
/// Gets a range tester that defines a range by upper bound.
/// </summary>
/// <param name="last">The upper bound.</param>
/// <param name="inclusive">True if the upper bound is inclusive, false if exclusive.</param>
/// <returns>A RangeTester delegate that tests for an item in the given range.</returns>
public RangeTester UpperBoundedRangeTester(T last, bool inclusive)
{
return delegate(T item) {
if (inclusive) {
if (comparer.Compare(last, item) < 0)
return 1; // item is after last.
else
return 0; // item is before or equal to last.
}
else {
if (comparer.Compare(last, item) <= 0)
return 1; // item is after or equal to last
else
return 0; // item is before last.
}
};
}
/// <summary>
/// Gets a range tester that defines a range by all items equal to an item.
/// </summary>
/// <param name="equalTo">The item that is contained in the range.</param>
/// <returns>A RangeTester delegate that tests for an item equal to <paramref name="equalTo"/>.</returns>
public RangeTester EqualRangeTester(T equalTo)
{
return delegate(T item) {
return comparer.Compare(item, equalTo);
};
}
/// <summary>
/// A range tester that defines a range that is the entire tree.
/// </summary>
/// <param name="item">Item to test.</param>
/// <returns>Always returns 0.</returns>
public int EntireRangeTester(T item)
{
return 0;
}
/// <summary>
/// Enumerate the items in a custom range in the tree. The range is determined by
/// a RangeTest delegate.
/// </summary>
/// <param name="rangeTester">Tests an item against the custom range.</param>
/// <returns>An IEnumerable<T> that enumerates the custom range in order.</returns>
/// <exception cref="InvalidOperationException">The tree has an item added or deleted during the enumeration.</exception>
public IEnumerable<T> EnumerateRange(RangeTester rangeTester)
{
return EnumerateRange(rangeTester, false);
}
/// <summary>
/// Enumerate the items in a custom range in the tree, in reversed order. The range is determined by
/// a RangeTest delegate.
/// </summary>
/// <param name="rangeTester">Tests an item against the custom range.</param>
/// <returns>An IEnumerable<T> that enumerates the custom range in reversed order.</returns>
/// <exception cref="InvalidOperationException">The tree has an item added or deleted during the enumeration.</exception>
public IEnumerable<T> EnumerateRangeReversed(RangeTester rangeTester)
{
return EnumerateRange(rangeTester, true);
}
/// <summary>
/// Enumerate all the items in a custom range, optionally reversing the order.
/// </summary>
/// <param name="rangeTester">Tests an item against the custom range.</param>
/// <param name="reversed">Indicates whether or not to reverse the order.</param>
/// <returns>An enumerable of the items.</returns>
/// <exception cref="InvalidOperationException">The tree has an item added or deleted during the enumeration.</exception>
private IEnumerable<T> EnumerateRange(RangeTester rangeTester, bool reversed)
{
int startStamp = changeStamp;
Stack<Node> stack = new Stack<Node>(2 * Util.LogBase2(unchecked((uint)count + 1)));
Node current = root;
while (current != null) {
stack.Push(current);
// if we just pushed an item outside the range, then we can stop
// here, since we'd otherwise just go further outside the range.
// note, we have to wait until *after* we push one outside the
// range, because there might be some nodes under it in the
// opposite direction that are inside the range.
int range = rangeTester(current.item);
if (reversed ? range > 0 : range < 0)
break;
current = reversed ? current.right : current.left;
}
while (stack.Count != 0) {
current = stack.Pop();
if (rangeTester(current.item) == 0) {
yield return current.item;
CheckEnumerationStamp(startStamp);
}
current = reversed ? current.left : current.right;
while (current != null) {
stack.Push(current);
// same as before
int range = rangeTester(current.item);
if (reversed ? range > 0 : range < 0)
break;
current = reversed ? current.right : current.left;
}
}
}
/// <summary>
/// Deletes either the first or last item from a range, as identified by a RangeTester
/// delegate. If the range is empty, returns false.
/// </summary>
/// <remarks>Top-down algorithm from Weiss. Basic plan is to move down in the tree,
/// rotating and recoloring along the way to always keep the current node red, which
/// ensures that the node we delete is red. The details are quite complex, however! </remarks>
/// <param name="rangeTester">Range to delete from.</param>
/// <param name="deleteFirst">If true, delete the first item from the range, else the last.</param>
/// <param name="item">Returns the item that was deleted, if true returned.</param>
/// <returns>True if an element was deleted, false if the range is empty.</returns>
public bool DeleteItemFromRange(RangeTester rangeTester, bool deleteFirst, out T item)
{
Node node; // The current node.
Node parent; // Parent of the current node.
Node gparent; // Grandparent of the current node.
Node sib; // Sibling of the current node.
Node keyNode; // Node with the key that is being removed.
// The tree may be changed.
StopEnumerations();
if (root == null) {
// Nothing in the tree. Go home now.
item = default(T);
return false;
}
// We decrement counts on the way down the tree. If we end up not finding an item to delete
// we need a stack to adjust the counts back.
Node[] nodeStack = GetNodeStack();
int nodeStackPtr = 0; // first free item on the stack.
// Start at the root.
node = root;
sib = parent = gparent = null;
keyNode = null;
// Proceed down the tree, making the current node red so it can be removed.
for (; ; ) {
Debug.Assert(parent == null || parent.IsRed);
Debug.Assert(sib == null || !sib.IsRed);
Debug.Assert(!node.IsRed);
if ((node.left == null || !node.left.IsRed) && (node.right == null || !node.right.IsRed)) {
// node has two black children (null children are considered black).
if (parent == null) {
// Special case for the root.
Debug.Assert(node == root);
node.IsRed = true;
}
else if ((sib.left == null || !sib.left.IsRed) && (sib.right == null || !sib.right.IsRed)) {
// sib has two black children.
node.IsRed = true;
sib.IsRed = true;
parent.IsRed = false;
}
else {
if (parent.left == node && (sib.right == null || !sib.right.IsRed)) {
// sib has a black child on the opposite side as node.
Node tleft = sib.left;
Rotate(parent, sib, tleft);
sib = tleft;
}
else if (parent.right == node && (sib.left == null || !sib.left.IsRed)) {
// sib has a black child on the opposite side as node.
Node tright = sib.right;
Rotate(parent, sib, tright);
sib = tright;
}
// sib has a red child.
Rotate(gparent, parent, sib);
node.IsRed = true;
sib.IsRed = true;
sib.left.IsRed = false;
sib.right.IsRed = false;
sib.DecrementCount();
nodeStack[nodeStackPtr - 1] = sib;
parent.DecrementCount();
nodeStack[nodeStackPtr++] = parent;
}
}
// Compare the key and move down the tree to the correct child.
do {
Node nextNode, nextSib; // Node we've moving to, and it's sibling.
node.DecrementCount();
nodeStack[nodeStackPtr++] = node;
// Determine which way to move in the tree by comparing the
// current item to what we're looking for.
int compare = rangeTester(node.item);
if (compare == 0) {
// We've found the node to remove. Remember it, then keep traversing the
// tree to either find the first/last of equal keys, and if needed, the predecessor
// or successor (the actual node to be removed).
keyNode = node;
if (deleteFirst) {
nextNode = node.left; nextSib = node.right;
}
else {
nextNode = node.right; nextSib = node.left;
}
}
else if (compare > 0) {
nextNode = node.left; nextSib = node.right;
}
else {
nextNode = node.right; nextSib = node.left;
}
// Have we reached the end of our tree walk?
if (nextNode == null)
goto FINISHED;
// Move down the tree.
gparent = parent;
parent = node;
node = nextNode;
sib = nextSib;
} while (!parent.IsRed && node.IsRed);
if (!parent.IsRed) {
Debug.Assert(!node.IsRed);
// moved to a black child.
Rotate(gparent, parent, sib);
sib.DecrementCount();
nodeStack[nodeStackPtr - 1] = sib;
parent.DecrementCount();
nodeStack[nodeStackPtr++] = parent;
sib.IsRed = false;
parent.IsRed = true;
gparent = sib;
sib = (parent.left == node) ? parent.right : parent.left;
}
}
FINISHED:
if (keyNode == null) {
// We never found a node to delete.
// Return counts back to their previous value.
for (int i = 0; i < nodeStackPtr; ++i)
nodeStack[i].IncrementCount();
// Color the root black, in case it was colored red above.
if (root != null)
root.IsRed = false;
item = default(T);
return false;
}
// Return the item from the node we're deleting.
item = keyNode.item;
// At a leaf or a node with one child which is a leaf. Remove the node.
if (keyNode != node) {
// The node we want to delete is interior. Move the item from the
// node we're actually deleting to the key node.
keyNode.item = node.item;
}
// If we have one child, replace the current with the child, otherwise,
// replace the current node with null.
Node replacement;
if (node.left != null) {
replacement = node.left;
Debug.Assert(!node.IsRed && replacement.IsRed);
replacement.IsRed = false;
}
else if (node.right != null) {
replacement = node.right;
Debug.Assert(!node.IsRed && replacement.IsRed);
replacement.IsRed = false;
}
else
replacement = null;
if (parent == null) {
Debug.Assert(root == node);
root = replacement;
}
else if (parent.left == node)
parent.left = replacement;
else {
Debug.Assert(parent.right == node);
parent.right = replacement;
}
// Color the root black, in case it was colored red above.
if (root != null)
root.IsRed = false;
// Update item count.
count -= 1;
// And we're done.
return true;
}
/// <summary>
/// Delete all the items in a range, identified by a RangeTester delegate.
/// </summary>
/// <param name="rangeTester">The delegate that defines the range to delete.</param>
/// <returns>The number of items deleted.</returns>
public int DeleteRange(RangeTester rangeTester)
{
bool deleted;
int count = 0;
T dummy;
do {
deleted = DeleteItemFromRange(rangeTester, true, out dummy);
if (deleted)
++count;
} while (deleted);
return count;
}
/// <summary>
/// Count the items in a custom range in the tree. The range is determined by
/// a RangeTester delegate.
/// </summary>
/// <param name="rangeTester">The delegate that defines the range.</param>
/// <returns>The number of items in the range.</returns>
public int CountRange(RangeTester rangeTester)
{
return CountRangeUnderNode(rangeTester, root, false, false);
}
/// <summary>
/// Count all the items in a custom range, under and including node.
/// </summary>
/// <param name="rangeTester">The delegate that defines the range.</param>
/// <param name="node">Node to begin enumeration. May be null.</param>
/// <param name="belowRangeTop">This node and all under it are either in the range or below it.</param>
/// <param name="aboveRangeBottom">This node and all under it are either in the range or above it.</param>
/// <returns>The number of items in the range, under and include node.</returns>
private int CountRangeUnderNode(RangeTester rangeTester, Node node, bool belowRangeTop, bool aboveRangeBottom)
{
if (node != null) {
if (belowRangeTop && aboveRangeBottom) {
// This node and all below it must be in the range. Use the predefined count.
return node.Count;
}
int compare = rangeTester(node.item);
int count;
if (compare == 0) {
count = 1; // the node itself
count += CountRangeUnderNode(rangeTester, node.left, true, aboveRangeBottom);
count += CountRangeUnderNode(rangeTester, node.right, belowRangeTop, true);
}
else if (compare < 0) {
count = CountRangeUnderNode(rangeTester, node.right, belowRangeTop, aboveRangeBottom);
}
else { // compare > 0
count = CountRangeUnderNode(rangeTester, node.left, belowRangeTop, aboveRangeBottom);
}
return count;
}
else {
return 0;
}
}
/// <summary>
/// Find the first item in a custom range in the tree, and it's index. The range is determined
/// by a RangeTester delegate.
/// </summary>
/// <param name="rangeTester">The delegate that defines the range.</param>
/// <param name="item">Returns the item found, if true was returned.</param>
/// <returns>Index of first item in range if range is non-empty, -1 otherwise.</returns>
public int FirstItemInRange(RangeTester rangeTester, out T item)
{
Node node = root, found = null;
int curCount = 0, foundIndex = -1;
while (node != null) {
int compare = rangeTester(node.item);
if (compare == 0) {
found = node;
if (node.left != null)
foundIndex = curCount + node.left.Count;
else
foundIndex = curCount;
}
if (compare >= 0)
node = node.left;
else {
if (node.left != null)
curCount += node.left.Count + 1;
else
curCount += 1;
node = node.right;
}
}
if (found != null) {
item = found.item;
return foundIndex;
}
else {
item = default(T);
return -1;
}
}
/// <summary>
/// Find the last item in a custom range in the tree, and it's index. The range is determined
/// by a RangeTester delegate.
/// </summary>
/// <param name="rangeTester">The delegate that defines the range.</param>
/// <param name="item">Returns the item found, if true was returned.</param>
/// <returns>Index of the item if range is non-empty, -1 otherwise.</returns>
public int LastItemInRange(RangeTester rangeTester, out T item)
{
Node node = root, found = null;
int curCount = 0, foundIndex = -1;
while (node != null) {
int compare = rangeTester(node.item);
if (compare == 0) {
found = node;
if (node.left != null)
foundIndex = curCount + node.left.Count;
else
foundIndex = curCount;
}
if (compare <= 0) {
if (node.left != null)
curCount += node.left.Count + 1;
else
curCount += 1;
node = node.right;
}
else
node = node.left;
}
if (found != null) {
item = found.item;
return foundIndex;
}
else {
item = default(T);
return foundIndex;
}
}
#endregion Ranges
#if DEBUG
/// <summary>
/// Prints out the tree.
/// </summary>
public void Print() {
PrintSubTree(root, "", "");
Console.WriteLine("");
}
/// <summary>
/// Prints a sub-tree.
/// </summary>
/// <param name="node">Node to print from</param>
/// <param name="prefixNode">Prefix for the node</param>
/// <param name="prefixChildren">Prefix for the node's children</param>
private static void PrintSubTree(Node node, string prefixNode, string prefixChildren) {
if (node == null)
return;
// Red nodes marked as "@@", black nodes as "..".
Console.WriteLine("{0}{1} {2,4} {3}", prefixNode, node.IsRed ? "@@" : "..", node.Count, node.item.ToString());
PrintSubTree(node.left, prefixChildren + "|-L-", prefixChildren + "| ");
PrintSubTree(node.right, prefixChildren + "|-R-", prefixChildren + " ");
}
/// <summary>
/// Validates that the tree is correctly sorted, and meets the red-black tree
/// axioms.
/// </summary>
public void Validate() {
Debug.Assert(comparer != null, "Comparer should not be null");
if (root == null) {
Debug.Assert(0 == count, "Count in empty tree should be 0.");
}
else {
Debug.Assert(! root.IsRed, "Root is not black");
int blackHeight;
int nodeCount = ValidateSubTree(root, out blackHeight);
Debug.Assert(nodeCount == this.count, "Node count of tree is not correct.");
}
}
/// <summary>
/// Validates a sub-tree and returns the count and black height.
/// </summary>
/// <param name="node">Sub-tree to validate. May be null.</param>
/// <param name="blackHeight">Returns the black height of the tree.</param>
/// <returns>Returns the number of nodes in the sub-tree. 0 if node is null.</returns>
private int ValidateSubTree(Node node, out int blackHeight) {
if (node == null) {
blackHeight = 0;
return 0;
}
// Check that this node is sorted with respect to any children.
if (node.left != null)
Debug.Assert(comparer.Compare(node.left.item, node.item) <= 0, "Left child is not less than or equal to node");
if (node.right != null)
Debug.Assert(comparer.Compare(node.right.item, node.item) >= 0, "Right child is not greater than or equal to node");
// Check that the two-red rule is not violated.
if (node.IsRed) {
if (node.left != null)
Debug.Assert(! node.left.IsRed, "Node and left child both red");
if (node.right != null)
Debug.Assert(! node.right.IsRed, "Node and right child both red");
}
// Validate sub-trees and get their size and heights.
int leftCount, leftBlackHeight;
int rightCount, rightBlackHeight;
int ourCount;
leftCount = ValidateSubTree(node.left, out leftBlackHeight);
rightCount = ValidateSubTree(node.right, out rightBlackHeight);
ourCount = leftCount + rightCount + 1;
Debug.Assert(ourCount == node.Count);
// Validate the equal black-height rule.
Debug.Assert(leftBlackHeight == rightBlackHeight, "Black heights are not equal");
// Calculate our black height and return the count
blackHeight = leftBlackHeight;
if (! node.IsRed)
blackHeight += 1;
return ourCount;
}
#endif //DEBUG
}
}
| 39.822041 | 139 | 0.519536 | [
"EPL-1.0"
] | NetTopologySuite/PowerCollections | Source/PowerCollections/RedBlack.cs | 48,782 | C# |
using MyJetWallet.Sdk.Service;
using MyYamlParser;
namespace Service.MatchingEngine.EventBridge.Settings
{
public class SettingsModel
{
[YamlProperty("MatchingEngineEventBridge.SeqServiceUrl")]
public string SeqServiceUrl { get; set; }
[YamlProperty("MatchingEngineEventBridge.ServiceBus.HostPort")]
public string ServiceBusHostPort { get; set; }
[YamlProperty("MatchingEngineEventBridge.ServiceBus.TopicName")]
public string TopicName { get; set; }
[YamlProperty("MatchingEngineEventBridge.ZipkinUrl")]
public string ZipkinUrl { get; set; }
[YamlProperty("MatchingEngineEventBridge.ElkLogs")]
public LogElkSettings ElkLogs { get; set; }
[YamlProperty("MatchingEngineEventBridge.GrpcMaxReceiveMessageSize")]
public int GrpcMaxReceiveMessageSize { get; set; }
[YamlProperty("MatchingEngineEventBridge.FailProbability")]
public double FailProbability { get; set; }
}
} | 34.413793 | 77 | 0.709419 | [
"MIT"
] | MyJetWallet/Service.MatchingEngine.EventBridge | src/Service.MatchingEngine.EventBridge/Settings/SettingsModel.cs | 1,000 | C# |
// <copyright file="ItemCountViewModel.cs" company="Dark Bond, Inc.">
// Copyright © 2016-2018 - Dark Bond, Inc. All Rights Reserved.
// </copyright>
// <author>Donald Roy Airey</author>
namespace DarkBond.ViewModels
{
using System.Globalization;
using DarkBond.ViewModels.Strings;
/// <summary>
/// View model for presenting the number of items.
/// </summary>
public class ItemCountViewModel : TextViewModel
{
/// <summary>
/// The number of items.
/// </summary>
private int countField;
/// <summary>
/// Initializes a new instance of the <see cref="ItemCountViewModel"/> class.
/// </summary>
public ItemCountViewModel()
{
// These property change events are handled by this class.
this.PropertyChangedActions["Count"] = this.OnCountChanged;
// This will initialize the view model with the current count.
this.OnCountChanged();
}
/// <summary>
/// Gets or sets the number of items.
/// </summary>
public int Count
{
get
{
return this.countField;
}
set
{
if (this.countField != value)
{
this.countField = value;
this.OnPropertyChanged("Count");
}
}
}
/// <summary>
/// Handles a change to the Count property.
/// </summary>
private void OnCountChanged()
{
// Format a message showing how many items are displayed in the view.
this.Text = string.Format(
CultureInfo.InvariantCulture,
Labels.ItemFormat,
this.countField,
this.countField == 1 ? Labels.Item : Labels.Items);
}
}
}
| 28.954545 | 85 | 0.52224 | [
"MIT"
] | DonaldAirey/dark-bond-main | DarkBond.ViewModels/Metadata/ItemCountViewModel.cs | 1,914 | C# |
using System;
using System.Net.Http;
using System.Text.Json;
namespace Front
{
public static class RequestHelper
{
public static HttpRequestMessage CreateRequest(string uri, string method)
=> new HttpRequestMessage(method.ToHttpMethod(), new Uri(uri, UriKind.RelativeOrAbsolute));
public static T? Deserialize<T>(this string source)
=> JsonSerializer.Deserialize<T>(source, Options);
private static JsonSerializerOptions Options { get; } = new JsonSerializerOptions
{
AllowTrailingCommas = true,
PropertyNameCaseInsensitive = true
};
private static HttpMethod ToHttpMethod(this string method)
=> method switch
{
"GET" => HttpMethod.Get,
"PUT" => HttpMethod.Put,
_ => HttpMethod.Options
};
}
} | 30.655172 | 103 | 0.611924 | [
"MIT"
] | niccou/hateoas-talk | demo/src/Front/RequestHelper.cs | 891 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNet.Http.Internal;
using Microsoft.AspNet.Mvc.ModelBinding;
using Microsoft.AspNet.Mvc.ModelBinding.Validation;
using Xunit;
namespace Microsoft.AspNet.Mvc.WebApiCompatShim
{
public class HttpRequestMessageModelBinderTest
{
[Fact]
public async Task BindModelAsync_ReturnsNonEmptyResult_ForHttpRequestMessageType()
{
// Arrange
var binder = new HttpRequestMessageModelBinder();
var bindingContext = GetBindingContext(typeof(HttpRequestMessage));
var expectedModel = bindingContext.OperationBindingContext.HttpContext.GetHttpRequestMessage();
// Act
var result = await binder.BindModelAsync(bindingContext);
// Assert
Assert.NotEqual(ModelBindingResult.NoResult, result);
Assert.True(result.IsModelSet);
Assert.Same(expectedModel, result.Model);
var entry = bindingContext.ValidationState[result.Model];
Assert.True(entry.SuppressValidation);
Assert.Null(entry.Key);
Assert.Null(entry.Metadata);
}
[Theory]
[InlineData(typeof(int))]
[InlineData(typeof(object))]
[InlineData(typeof(HttpRequestMessageModelBinderTest))]
public async Task BindModelAsync_ReturnsNull_ForNonHttpRequestMessageType(Type type)
{
// Arrange
var binder = new HttpRequestMessageModelBinder();
var bindingContext = GetBindingContext(type);
// Act
var result = await binder.BindModelAsync(bindingContext);
// Assert
Assert.Equal(ModelBindingResult.NoResult, result);
}
private static ModelBindingContext GetBindingContext(Type modelType)
{
var metadataProvider = new EmptyModelMetadataProvider();
ModelBindingContext bindingContext = new ModelBindingContext
{
ModelMetadata = metadataProvider.GetMetadataForType(modelType),
ModelName = "someName",
OperationBindingContext = new OperationBindingContext
{
ActionContext = new ActionContext()
{
HttpContext = new DefaultHttpContext(),
},
MetadataProvider = metadataProvider,
},
ValidationState = new ValidationStateDictionary(),
};
bindingContext.OperationBindingContext.HttpContext.Request.Method = "GET";
return bindingContext;
}
}
}
| 36.265823 | 111 | 0.633508 | [
"Apache-2.0"
] | corefan/Mvc | test/Microsoft.AspNet.Mvc.WebApiCompatShimTest/HttpRequestMessage/HttpRequestMessageModelBinderTest.cs | 2,867 | C# |
using FubuTestingSupport;
using NUnit.Framework;
using NuGet;
using ripple.Commands;
using ripple.Model;
namespace ripple.Testing.Integration
{
[TestFixture]
public class restore_dependencies_case_insensitive
{
private SolutionGraphScenario theScenario;
private Solution theSolution;
[SetUp]
public void SetUp()
{
theScenario = SolutionGraphScenario.Create(scenario =>
{
scenario.Solution("Test", test =>
{
test.SolutionDependency("StructureMap", "2.6.3", UpdateMode.Fixed);
test.ProjectDependency("Test", "structuremap");
});
});
theSolution = theScenario.Find("Test");
FeedScenario.Create(scenario =>
{
scenario.For(Feed.Fubu)
.Add("structuremap", "2.6.4.54");
scenario.For(Feed.NuGetV2)
.Add("structuremap", "2.6.3");
});
RippleOperation
.With(theSolution)
.Execute<RestoreInput, RestoreCommand>();
}
[TearDown]
public void TearDown()
{
theScenario.Cleanup();
}
[Test]
public void restores_the_fixed_version()
{
var local = theSolution.LocalDependencies();
local.Get("structuremap").Version.ShouldEqual(new SemanticVersion("2.6.3"));
}
}
} | 26.982143 | 88 | 0.529451 | [
"Apache-2.0"
] | danielHalan/ripple | src/ripple.Testing/Integration/restore_dependencies_case_insensitive.cs | 1,513 | C# |
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
namespace MvcMovieSampleApp.Models
{
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; }
}
public class ManageLoginsViewModel
{
public IList<UserLoginInfo> CurrentLogins { get; set; }
public IList<AuthenticationDescription> OtherLogins { get; set; }
}
public class FactorViewModel
{
public string Purpose { get; set; }
}
public class SetPasswordViewModel
{
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public class ChangePasswordViewModel
{
[Required]
[DataType(DataType.Password)]
[Display(Name = "Current password")]
public string OldPassword { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public class AddPhoneNumberViewModel
{
[Required]
[Phone]
[Display(Name = "Phone Number")]
public string Number { get; set; }
}
public class VerifyPhoneNumberViewModel
{
[Required]
[Display(Name = "Code")]
public string Code { get; set; }
[Required]
[Phone]
[Display(Name = "Phone Number")]
public string PhoneNumber { get; set; }
}
public class ConfigureTwoFactorViewModel
{
public string SelectedProvider { get; set; }
public ICollection<System.Web.Mvc.SelectListItem> Providers { get; set; }
}
} | 30.94186 | 110 | 0.626832 | [
"Apache-2.0"
] | adityap/Infuse | test/MvcMovieSampleApp/Models/ManageViewModels.cs | 2,663 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("Addless20useClasslibrary")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Sky123.Org")]
[assembly: AssemblyProduct("Addless20useClasslibrary")]
[assembly: AssemblyCopyright("Copyright © Sky123.Org 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("b3780a9c-f36b-4841-a293-617278a09321")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 内部版本号
// 修订号
//
// 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 27.918919 | 61 | 0.701839 | [
"Apache-2.0"
] | sunlupeng2020/addless20 | Addless20useClasslibrary/Properties/AssemblyInfo.cs | 1,400 | C# |
using System;
using System.Linq;
using System.Collections.Generic;
using System.Reflection;
namespace Goofy.Core.Infrastructure
{
public class GoofyResourcesLocator : IResourcesLocator
{
private readonly IAssembliesProvider _assembliesProvider;
public GoofyResourcesLocator(IAssembliesProvider resourcesLocator)
{
_assembliesProvider = resourcesLocator;
}
public IEnumerable<Type> FindClassesOfType(Type type)
{
var result = new List<Type>();
foreach (var t in _assembliesProvider.GetAssemblies().SelectMany(assembly => assembly.GetExportedTypes()))
{
var typeInfo = t.GetTypeInfo();
if (type.IsAssignableFrom(t) && typeInfo.IsClass)
{
if (!typeInfo.IsInterface && !typeInfo.IsAbstract)
{
yield return t;
}
}
}
}
public IEnumerable<Type> FindClassesOfType<T>()
{
return FindClassesOfType(typeof(T));
}
}
}
| 28.794872 | 118 | 0.570793 | [
"MIT"
] | GoofyCMS/Backend | libs/Goofy.Core/Infrastructure/ResourcesManagement/GoofyResourcesLocator.cs | 1,125 | C# |
using FluentAssertions;
using Kros.KORM.Materializer;
using Kros.KORM.Metadata;
using Kros.KORM.Metadata.Attribute;
using Kros.KORM.UnitTests.Helper;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Xunit;
namespace Kros.KORM.UnitTests.Materializer
{
public class ModelBuilderShould
{
#region Tests
[Fact]
public void MaterializeDataFromReader()
{
IDataReader reader = new InMemoryDataReader(CreateDataForReader());
ModelBuilder builder = CreateBuilder();
var data = builder.Materialize<Foo>(reader).ToList();
data.Should().HaveCount(2);
data[0].Id.Should().Be(1);
data[0].PropertyGuid.Should().Be("ddc995d7-4dda-41ca-abab-7f45e651784a");
data[1].PropertyString.Should().Be("Kitty");
data[1].PropertyDateTime.Should().Be(new DateTime(1984, 4, 20));
}
[Fact]
public void GetEmptyDataFromEmptyReader()
{
var sourceData = CreateDataForReader();
sourceData.Clear();
IDataReader reader = new InMemoryDataReader(sourceData);
ModelBuilder builder = CreateBuilder();
var data = builder.Materialize<Foo>(reader).ToList();
data.Should().HaveCount(0);
}
[Fact]
public void MaterializeDataFromDataTable()
{
var dataTable = CreateDataTable();
ModelBuilder builder = CreateBuilder();
var data = builder.Materialize<Foo>(dataTable).ToList();
data.Should().HaveCount(3);
data[0].Id.Should().Be(1);
data[0].PropertyDateTime.Should().Be(new DateTime(1990, 1, 1));
data[1].PropertyEnum.Should().Be(TestEnum.Value3);
data[1].PropertyDateTime.Should().Be(new DateTime(1975, 10, 11));
data[2].Id.Should().Be(12);
data[2].PropertyString.Should().BeNull();
}
[Fact]
public void CallDisposeOnInternalReaderAndCloseConnection()
{
IDbConnection connection = Substitute.For<IDbConnection>();
IDataReader internalReader = Substitute.For<IDataReader>();
IDbCommand command = Substitute.For<IDbCommand>();
command.Connection = connection;
command.ExecuteReader().Returns(internalReader);
ModelBuilder.QueryDataReader reader = new ModelBuilder.QueryDataReader(command, true);
ModelBuilder builder = CreateBuilder();
var data = builder.Materialize<Foo>(reader).ToList();
internalReader.Received().Dispose();
connection.Received().Close();
}
[Fact]
public void NotCallDisposeMethodOnReader()
{
IDataReader reader = Substitute.For<IDataReader>();
ModelBuilder builder = CreateBuilder();
var data = builder.Materialize<Foo>(reader).ToList();
reader.DidNotReceive().Dispose();
}
[Fact]
public void MaterializeDataFromDataRow()
{
var dataTable = CreateDataTable();
ModelBuilder builder = CreateBuilder();
var data = builder.Materialize<Foo>(dataTable.Rows[0]);
data.Id.Should().Be(1);
data.PropertyDateTime.Should().Be(new DateTime(1990, 1, 1));
}
#endregion
private static ModelBuilder CreateBuilder()
{
return new ModelBuilder(new DynamicMethodModelFactory(new DatabaseMapper(new ConventionModelMapper())));
}
#region Creating reader data
private List<Dictionary<string, object>> CreateDataForReader()
{
List<Dictionary<string, object>> ret = new List<Dictionary<string, object>>();
AddRow(ret, 1, "Hello", 45.78, (decimal)785.78, new DateTime(1980, 7, 24),
true, new Guid("ddc995d7-4dda-41ca-abab-7f45e651784a"), TestEnum.Value2);
AddRow(ret, 2, "Kitty", 47.98, (decimal)75.8, new DateTime(1984, 4, 20),
true, new Guid("ddc995d7-4dda-41ca-abab-7f45e6517844"), TestEnum.Value1);
return ret;
}
private static void AddRow(List<Dictionary<string, object>> ret,
int id,
string firstName,
double something,
decimal salary,
DateTime birthday,
bool iS,
Guid guid,
TestEnum enumV)
{
Dictionary<string, object> row = new Dictionary<string, object>() { { "Id", id },
{ "FirstName", firstName },
{ "Something", something},
{ "Salary",salary},
{ "Birthday", birthday},
{ "Is", iS},
{ "PropertyGuid", guid}};
ret.Add(row);
}
#endregion
#region Creating test datatable
private DataTable CreateDataTable()
{
var ret = new DataTable();
ret.Columns.Add("Id", typeof(int));
ret.Columns.Add("FirstName", typeof(string));
ret.Columns.Add("Birthday", typeof(DateTime));
ret.Columns.Add("PropertyEnum", typeof(TestEnum));
AddRow(ret, 1, "Michael", new DateTime(1990, 1, 1), TestEnum.Value2);
AddRow(ret, 4, "Peter", new DateTime(1975, 10, 11), TestEnum.Value3);
AddRow(ret, 12, DBNull.Value, new DateTime(1987, 9, 9), TestEnum.Value1);
return ret;
}
private void AddRow(DataTable table, int id, object firstName, DateTime birthday, TestEnum propertyEnum)
{
var row = table.NewRow();
row["Id"] = id;
row["FirstName"] = firstName;
row["birthday"] = birthday;
row["PropertyEnum"] = propertyEnum;
table.Rows.Add(row);
}
#endregion
#region Test classes
private class Foo
{
public int Id { get; set; }
[Alias("FirstName")]
public string PropertyString { get; set; }
[Alias("Something")]
public double PropertyDouble { get; set; }
[Alias("Salary")]
public decimal PropertyDecimal { get; set; }
[Alias("Birthday")]
public DateTime PropertyDateTime { get; set; }
public bool Is { get; set; }
[NoMap]
public int Bar { get; set; }
public Guid PropertyGuid { get; set; }
public TestEnum PropertyEnum { get; set; }
}
private enum TestEnum
{
Value1 = 1,
Value2 = 2,
Value3 = 3,
}
#endregion
}
}
| 32.908696 | 116 | 0.50403 | [
"MIT"
] | JardoHornak/Kros.Libs | Kros.KORM/tests/Kros.KORM.UnitTests/Materializer/ModelBuilderShould.cs | 7,571 | C# |
namespace CodeGeneration
{
partial class Form1
{
/// <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.button1 = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(12, 12);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "Generate";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// textBox1
//
this.textBox1.Dock = System.Windows.Forms.DockStyle.Bottom;
this.textBox1.Location = new System.Drawing.Point(0, 41);
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(624, 369);
this.textBox1.TabIndex = 1;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(624, 410);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button button1;
private System.Windows.Forms.TextBox textBox1;
}
}
| 34.306667 | 107 | 0.551496 | [
"Apache-2.0"
] | Infosys/Script-Control-Center | ScriptDevelopmentTool/CodeGeneration/Form1.Designer.cs | 2,575 | C# |
//-----------------------------------------------------------------------
// <copyright file="RuntimeTool.cs" company="Sphere 10 Software">
//
// Copyright (c) Sphere 10 Software. All rights reserved. (http://www.sphere10.com)
//
// Distributed under the MIT software license, see the accompanying file
// LICENSE or visit http://www.opensource.org/licenses/mit-license.php.
//
// <author>Herman Schoenfeld</author>
// <date>2018</date>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using Sphere10.Framework;
using Sphere10.Framework.FastReflection;
namespace Tools {
public static class Runtime {
private static readonly object _threadLock = new object();
private static bool _hasDeterminedDesignMode = false;
private static bool _isDesignMode = false;
private static Assembly _entryAssembly = null;
private static bool? _isWebApp = null;
public static bool IsWebApp {
get {
#warning IsWebApp needs testing for NET_CORE and NET STANDARD apps
return false;
//#if __MOBILE__
// return false;
//#else
// if (_isWebApp == null) {
// lock (_threadLock) {
// if (_isWebApp == null) {
// _isWebApp = Path.GetFileName(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile).EndsWith("web.config", true, CultureInfo.InvariantCulture);
// }
// }
// }
//#endif
// return _isWebApp.Value;
}
}
public static Assembly GetEntryAssembly() {
if (_entryAssembly == null) {
lock (_threadLock) {
if (_entryAssembly == null) {
_entryAssembly = IsWebApp ? GetWebEntryAssembly() : Assembly.GetEntryAssembly();
if (_entryAssembly == null)
throw new SoftwareException("Unable to determine entry assembly");
}
}
}
return _entryAssembly;
}
private static Assembly GetWebEntryAssembly() {
throw new NotImplementedException();
////return Assembly.GetExecutingAssembly();
//var httpContextType = TypeResolver.Resolve("System.Web.HttpContext");
//var httpContextCurrent = httpContextType.GetProperty("Current").FastGetValue(null);
////var httpContextCurrentHandler = httpContextCurrent.GetType().GetProperty("Handler").FastGetValue(httpContextCurrent);
//var httpContextCurrentApplicationInstance = httpContextCurrent.GetType().GetProperty("ApplicationInstance").FastGetValue(httpContextCurrent);
//return httpContextCurrentApplicationInstance.GetType().BaseType.Assembly;
////if ((System.Web.HttpContext.Current == null) || (System.Web.HttpContext.Current.Handler == null))
//// return Tools.Runtime.GetEntryAssembly(); // Not a web application
////return System.Web.HttpContext.Current.Handler.GetType().BaseType.Assembly;
}
public static bool IsDesignMode {
get {
if (!_hasDeterminedDesignMode) {
lock (_threadLock) {
if (!_hasDeterminedDesignMode) {
var processName = Process.GetCurrentProcess().ProcessName.ToUpperInvariant();
_isDesignMode = processName.IsIn("DEVENV", "SHARPDEVELOP", "DESIGNTOOLSSERVER");
_hasDeterminedDesignMode = true;
}
}
}
return _isDesignMode;
}
}
}
}
| 38.87619 | 191 | 0.569819 | [
"MIT"
] | Sphere10/Framework | src/Sphere10.Framework/Environment/RuntimeTool.cs | 4,082 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.42
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Emeraldwalk.Emeraldwalk_VsFileMirror {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Emeraldwalk.Emeraldwalk_VsFileMirror.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
| 43.369231 | 191 | 0.614757 | [
"Apache-2.0"
] | bmingles/emeraldwalk | Emeraldwalk.VsPackages/Emeraldwalk.VsFileMirror/Resources.Designer.cs | 2,821 | C# |
using System;
namespace MessageSerializer
{
public class TypeSelectorDateTime : ITypeSelector
{
public Type CheckType(MessageSerializedPropertyInfo propertyInfo)
{
if (propertyInfo.ElementType.FullName == typeof(DateTime).FullName
&& propertyInfo.MessagePropertyAttribute.IsBcd)
{
return typeof(TypeSerializerDateTime);
}
return null;
}
}
}
| 24.210526 | 78 | 0.61087 | [
"MIT"
] | jacknino/MessageSerializer | MessageSerializer/TypeSelectorDateTime.cs | 462 | C# |
using System.Collections.Generic;
using Tanks.App.Globals;
using Tanks.App.Inputs;
using Tanks.App.Players;
using UnityEngine;
using UnityEngine.InputSystem;
namespace Tanks.App.Lobbies
{
public class Lobby : MonoBehaviour
{
[SerializeField] private PlayerJoinedGameChannel playerJoinedGameChannel;
[SerializeField] private PlayerJoinedLobbyChannel playerJoinedLobbyChannel;
[SerializeField] private LobbyContentRequestChannel lobbyContentRequestChannel;
[SerializeField] private LobbyContentResponseChannel lobbyContentResponseChannel;
private List<IPlayer> players;
private void Awake()
{
this.players = new List<IPlayer>(4);
}
private void OnEnable()
{
this.playerJoinedGameChannel.OnInvoked += this.AddPlayer;
this.lobbyContentRequestChannel.OnInvoked += this.OnContentRequestHandler;
}
private void OnDisable()
{
this.playerJoinedGameChannel.OnInvoked -= this.AddPlayer;
this.lobbyContentRequestChannel.OnInvoked -= this.OnContentRequestHandler;
}
private void OnContentRequestHandler()
{
this.lobbyContentResponseChannel.Broadcast(this.players);
}
private void AddPlayer(PlayerInput playerInput)
{
playerInput.transform.SetParent(this.transform);
var player = playerInput.GetComponent<IPlayer>();
player.SetId(playerInput.user.id);
player.SetDeviceId(playerInput.devices[0].deviceId);
this.players.Add(player);
this.playerJoinedLobbyChannel.Broadcast(player);
}
}
} | 30.767857 | 89 | 0.665699 | [
"MIT"
] | george-vasilchenko/tanks | Assets/App/Lobbies/Lobby.cs | 1,723 | C# |
namespace Gu.State
{
using System.Collections.Concurrent;
internal static class ConcurrentDictionaryPool<TKey, TValue>
{
private static readonly ConcurrentQueue<ConcurrentDictionary<TKey, TValue>> Cache = new();
internal static IBorrowed<ConcurrentDictionary<TKey, TValue>> Borrow()
{
if (Cache.TryDequeue(out var dictionary))
{
return Borrowed.Create(dictionary, Return);
}
return Borrowed.Create(new ConcurrentDictionary<TKey, TValue>(), Return);
}
private static void Return(ConcurrentDictionary<TKey, TValue> dictionary)
{
dictionary.Clear();
Cache.Enqueue(dictionary);
}
}
}
| 28.615385 | 98 | 0.620968 | [
"MIT"
] | JohanLarsson/Gu.ChangeTracking | Gu.State/Internals/Pools/ConcurrentDictionaryPool.cs | 744 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
/// <summary>
/// The type WorkbookFunctionsXirrRequest.
/// </summary>
public partial class WorkbookFunctionsXirrRequest : BaseRequest, IWorkbookFunctionsXirrRequest
{
/// <summary>
/// Constructs a new WorkbookFunctionsXirrRequest.
/// </summary>
public WorkbookFunctionsXirrRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
this.Method = "POST";
this.ContentType = "application/json";
this.RequestBody = new WorkbookFunctionsXirrRequestBody();
}
/// <summary>
/// Gets the request body.
/// </summary>
public WorkbookFunctionsXirrRequestBody RequestBody { get; private set; }
/// <summary>
/// Issues the POST request.
/// </summary>
public System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync()
{
return this.PostAsync(CancellationToken.None);
}
/// <summary>
/// Issues the POST request.
/// </summary>
/// <param name=""cancellationToken"">The <see cref=""CancellationToken""/> for the request.</param>
/// <returns>The task to await for async call.</returns>
public System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync(
CancellationToken cancellationToken)
{
return this.SendAsync<WorkbookFunctionResult>(this.RequestBody, cancellationToken);
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookFunctionsXirrRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookFunctionsXirrRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
}
}
| 35.987805 | 153 | 0.57472 | [
"MIT"
] | MIchaelMainer/GraphAPI | src/Microsoft.Graph/Requests/Generated/WorkbookFunctionsXirrRequest.cs | 2,951 | C# |
using FluentAssertions;
using RoadCaptain.GameStates;
using Xunit;
namespace RoadCaptain.App.Runner.Tests.Unit.Engine
{
public class WhenNotLoggedInStateIsReceived : EngineTest
{
public WhenNotLoggedInStateIsReceived()
{
GivenTaskIsRunning("_initiatorTask");
GivenTaskIsRunning("_listenerTask");
GivenTaskIsRunning("_messageHandlingTask");
}
[Fact]
public void ZwiftConnectionListenerIsCleanedUp()
{
GivenNotLoggedInStateIsReceived();
TheTaskWithName("_listenerTask")
.Should()
.BeNull();
}
[Fact]
public void ZwiftConnectionInitiatorIsCleanedUp()
{
GivenNotLoggedInStateIsReceived();
TheTaskWithName("_initiatorTask")
.Should()
.BeNull();
}
[Fact]
public void PreviousGameStateIsSetToLoggedInState()
{
var loggedInState = new LoggedInState("token");
ReceiveGameState(loggedInState);
GetFieldValueByName("_previousGameState")
.Should()
.Be(loggedInState);
}
[Fact]
public void MessageHandlingIsCleanedUp()
{
GivenNotLoggedInStateIsReceived();
TheTaskWithName("_messageHandlingTask")
.Should()
.BeNull();
}
private void GivenNotLoggedInStateIsReceived()
{
ReceiveGameState(new NotLoggedInState());
}
}
} | 25.174603 | 60 | 0.566835 | [
"Artistic-2.0"
] | sandermvanvliet/RoadCaptain | test/RoadCaptain.App.Runner.Tests.Unit/Engine/WhenNotLoggedInStateIsReceived.cs | 1,588 | 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 gamelift-2015-10-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.GameLift.Model
{
/// <summary>
/// Represents the returned data in response to a request action.
/// </summary>
public partial class UpdateBuildResponse : AmazonWebServiceResponse
{
private Build _build;
/// <summary>
/// Gets and sets the property Build.
/// <para>
/// The updated build record.
/// </para>
/// </summary>
public Build Build
{
get { return this._build; }
set { this._build = value; }
}
// Check to see if Build property is set
internal bool IsSetBuild()
{
return this._build != null;
}
}
} | 28.107143 | 106 | 0.64676 | [
"Apache-2.0"
] | UpendoVentures/aws-sdk-net | sdk/src/Services/GameLift/Generated/Model/UpdateBuildResponse.cs | 1,574 | C# |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V9.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V9.Services
{
/// <summary>Settings for <see cref="CustomerNegativeCriterionServiceClient"/> instances.</summary>
public sealed partial class CustomerNegativeCriterionServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="CustomerNegativeCriterionServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="CustomerNegativeCriterionServiceSettings"/>.</returns>
public static CustomerNegativeCriterionServiceSettings GetDefault() => new CustomerNegativeCriterionServiceSettings();
/// <summary>
/// Constructs a new <see cref="CustomerNegativeCriterionServiceSettings"/> object with default settings.
/// </summary>
public CustomerNegativeCriterionServiceSettings()
{
}
private CustomerNegativeCriterionServiceSettings(CustomerNegativeCriterionServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetCustomerNegativeCriterionSettings = existing.GetCustomerNegativeCriterionSettings;
MutateCustomerNegativeCriteriaSettings = existing.MutateCustomerNegativeCriteriaSettings;
OnCopy(existing);
}
partial void OnCopy(CustomerNegativeCriterionServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>CustomerNegativeCriterionServiceClient.GetCustomerNegativeCriterion</c> and
/// <c>CustomerNegativeCriterionServiceClient.GetCustomerNegativeCriterionAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetCustomerNegativeCriterionSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>CustomerNegativeCriterionServiceClient.MutateCustomerNegativeCriteria</c> and
/// <c>CustomerNegativeCriterionServiceClient.MutateCustomerNegativeCriteriaAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings MutateCustomerNegativeCriteriaSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="CustomerNegativeCriterionServiceSettings"/> object.</returns>
public CustomerNegativeCriterionServiceSettings Clone() => new CustomerNegativeCriterionServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="CustomerNegativeCriterionServiceClient"/> to provide simple configuration of
/// credentials, endpoint etc.
/// </summary>
internal sealed partial class CustomerNegativeCriterionServiceClientBuilder : gaxgrpc::ClientBuilderBase<CustomerNegativeCriterionServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public CustomerNegativeCriterionServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public CustomerNegativeCriterionServiceClientBuilder()
{
UseJwtAccessWithScopes = CustomerNegativeCriterionServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref CustomerNegativeCriterionServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<CustomerNegativeCriterionServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override CustomerNegativeCriterionServiceClient Build()
{
CustomerNegativeCriterionServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<CustomerNegativeCriterionServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<CustomerNegativeCriterionServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private CustomerNegativeCriterionServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return CustomerNegativeCriterionServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<CustomerNegativeCriterionServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return CustomerNegativeCriterionServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => CustomerNegativeCriterionServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() =>
CustomerNegativeCriterionServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => CustomerNegativeCriterionServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>CustomerNegativeCriterionService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage customer negative criteria.
/// </remarks>
public abstract partial class CustomerNegativeCriterionServiceClient
{
/// <summary>
/// The default endpoint for the CustomerNegativeCriterionService service, which is a host of
/// "googleads.googleapis.com" and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default CustomerNegativeCriterionService scopes.</summary>
/// <remarks>
/// The default CustomerNegativeCriterionService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="CustomerNegativeCriterionServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="CustomerNegativeCriterionServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="CustomerNegativeCriterionServiceClient"/>.</returns>
public static stt::Task<CustomerNegativeCriterionServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new CustomerNegativeCriterionServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="CustomerNegativeCriterionServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="CustomerNegativeCriterionServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="CustomerNegativeCriterionServiceClient"/>.</returns>
public static CustomerNegativeCriterionServiceClient Create() =>
new CustomerNegativeCriterionServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="CustomerNegativeCriterionServiceClient"/> which uses the specified call invoker for
/// remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="CustomerNegativeCriterionServiceSettings"/>.</param>
/// <returns>The created <see cref="CustomerNegativeCriterionServiceClient"/>.</returns>
internal static CustomerNegativeCriterionServiceClient Create(grpccore::CallInvoker callInvoker, CustomerNegativeCriterionServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
CustomerNegativeCriterionService.CustomerNegativeCriterionServiceClient grpcClient = new CustomerNegativeCriterionService.CustomerNegativeCriterionServiceClient(callInvoker);
return new CustomerNegativeCriterionServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC CustomerNegativeCriterionService client</summary>
public virtual CustomerNegativeCriterionService.CustomerNegativeCriterionServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested criterion in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::CustomerNegativeCriterion GetCustomerNegativeCriterion(GetCustomerNegativeCriterionRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested criterion in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CustomerNegativeCriterion> GetCustomerNegativeCriterionAsync(GetCustomerNegativeCriterionRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested criterion in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CustomerNegativeCriterion> GetCustomerNegativeCriterionAsync(GetCustomerNegativeCriterionRequest request, st::CancellationToken cancellationToken) =>
GetCustomerNegativeCriterionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested criterion in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the criterion to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::CustomerNegativeCriterion GetCustomerNegativeCriterion(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCustomerNegativeCriterion(new GetCustomerNegativeCriterionRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested criterion in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the criterion to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CustomerNegativeCriterion> GetCustomerNegativeCriterionAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCustomerNegativeCriterionAsync(new GetCustomerNegativeCriterionRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested criterion in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the criterion to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CustomerNegativeCriterion> GetCustomerNegativeCriterionAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetCustomerNegativeCriterionAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested criterion in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the criterion to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::CustomerNegativeCriterion GetCustomerNegativeCriterion(gagvr::CustomerNegativeCriterionName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCustomerNegativeCriterion(new GetCustomerNegativeCriterionRequest
{
ResourceNameAsCustomerNegativeCriterionName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested criterion in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the criterion to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CustomerNegativeCriterion> GetCustomerNegativeCriterionAsync(gagvr::CustomerNegativeCriterionName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCustomerNegativeCriterionAsync(new GetCustomerNegativeCriterionRequest
{
ResourceNameAsCustomerNegativeCriterionName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested criterion in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the criterion to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CustomerNegativeCriterion> GetCustomerNegativeCriterionAsync(gagvr::CustomerNegativeCriterionName resourceName, st::CancellationToken cancellationToken) =>
GetCustomerNegativeCriterionAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates or removes criteria. Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateCustomerNegativeCriteriaResponse MutateCustomerNegativeCriteria(MutateCustomerNegativeCriteriaRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates or removes criteria. Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCustomerNegativeCriteriaResponse> MutateCustomerNegativeCriteriaAsync(MutateCustomerNegativeCriteriaRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates or removes criteria. Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCustomerNegativeCriteriaResponse> MutateCustomerNegativeCriteriaAsync(MutateCustomerNegativeCriteriaRequest request, st::CancellationToken cancellationToken) =>
MutateCustomerNegativeCriteriaAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates or removes criteria. Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose criteria are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual criteria.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateCustomerNegativeCriteriaResponse MutateCustomerNegativeCriteria(string customerId, scg::IEnumerable<CustomerNegativeCriterionOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateCustomerNegativeCriteria(new MutateCustomerNegativeCriteriaRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates or removes criteria. Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose criteria are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual criteria.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCustomerNegativeCriteriaResponse> MutateCustomerNegativeCriteriaAsync(string customerId, scg::IEnumerable<CustomerNegativeCriterionOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateCustomerNegativeCriteriaAsync(new MutateCustomerNegativeCriteriaRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates or removes criteria. Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose criteria are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual criteria.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCustomerNegativeCriteriaResponse> MutateCustomerNegativeCriteriaAsync(string customerId, scg::IEnumerable<CustomerNegativeCriterionOperation> operations, st::CancellationToken cancellationToken) =>
MutateCustomerNegativeCriteriaAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>CustomerNegativeCriterionService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage customer negative criteria.
/// </remarks>
public sealed partial class CustomerNegativeCriterionServiceClientImpl : CustomerNegativeCriterionServiceClient
{
private readonly gaxgrpc::ApiCall<GetCustomerNegativeCriterionRequest, gagvr::CustomerNegativeCriterion> _callGetCustomerNegativeCriterion;
private readonly gaxgrpc::ApiCall<MutateCustomerNegativeCriteriaRequest, MutateCustomerNegativeCriteriaResponse> _callMutateCustomerNegativeCriteria;
/// <summary>
/// Constructs a client wrapper for the CustomerNegativeCriterionService service, with the specified gRPC client
/// and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="CustomerNegativeCriterionServiceSettings"/> used within this client.
/// </param>
public CustomerNegativeCriterionServiceClientImpl(CustomerNegativeCriterionService.CustomerNegativeCriterionServiceClient grpcClient, CustomerNegativeCriterionServiceSettings settings)
{
GrpcClient = grpcClient;
CustomerNegativeCriterionServiceSettings effectiveSettings = settings ?? CustomerNegativeCriterionServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetCustomerNegativeCriterion = clientHelper.BuildApiCall<GetCustomerNegativeCriterionRequest, gagvr::CustomerNegativeCriterion>(grpcClient.GetCustomerNegativeCriterionAsync, grpcClient.GetCustomerNegativeCriterion, effectiveSettings.GetCustomerNegativeCriterionSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetCustomerNegativeCriterion);
Modify_GetCustomerNegativeCriterionApiCall(ref _callGetCustomerNegativeCriterion);
_callMutateCustomerNegativeCriteria = clientHelper.BuildApiCall<MutateCustomerNegativeCriteriaRequest, MutateCustomerNegativeCriteriaResponse>(grpcClient.MutateCustomerNegativeCriteriaAsync, grpcClient.MutateCustomerNegativeCriteria, effectiveSettings.MutateCustomerNegativeCriteriaSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateCustomerNegativeCriteria);
Modify_MutateCustomerNegativeCriteriaApiCall(ref _callMutateCustomerNegativeCriteria);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetCustomerNegativeCriterionApiCall(ref gaxgrpc::ApiCall<GetCustomerNegativeCriterionRequest, gagvr::CustomerNegativeCriterion> call);
partial void Modify_MutateCustomerNegativeCriteriaApiCall(ref gaxgrpc::ApiCall<MutateCustomerNegativeCriteriaRequest, MutateCustomerNegativeCriteriaResponse> call);
partial void OnConstruction(CustomerNegativeCriterionService.CustomerNegativeCriterionServiceClient grpcClient, CustomerNegativeCriterionServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC CustomerNegativeCriterionService client</summary>
public override CustomerNegativeCriterionService.CustomerNegativeCriterionServiceClient GrpcClient { get; }
partial void Modify_GetCustomerNegativeCriterionRequest(ref GetCustomerNegativeCriterionRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_MutateCustomerNegativeCriteriaRequest(ref MutateCustomerNegativeCriteriaRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested criterion in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gagvr::CustomerNegativeCriterion GetCustomerNegativeCriterion(GetCustomerNegativeCriterionRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetCustomerNegativeCriterionRequest(ref request, ref callSettings);
return _callGetCustomerNegativeCriterion.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested criterion in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gagvr::CustomerNegativeCriterion> GetCustomerNegativeCriterionAsync(GetCustomerNegativeCriterionRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetCustomerNegativeCriterionRequest(ref request, ref callSettings);
return _callGetCustomerNegativeCriterion.Async(request, callSettings);
}
/// <summary>
/// Creates or removes criteria. Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override MutateCustomerNegativeCriteriaResponse MutateCustomerNegativeCriteria(MutateCustomerNegativeCriteriaRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateCustomerNegativeCriteriaRequest(ref request, ref callSettings);
return _callMutateCustomerNegativeCriteria.Sync(request, callSettings);
}
/// <summary>
/// Creates or removes criteria. Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<MutateCustomerNegativeCriteriaResponse> MutateCustomerNegativeCriteriaAsync(MutateCustomerNegativeCriteriaRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateCustomerNegativeCriteriaRequest(ref request, ref callSettings);
return _callMutateCustomerNegativeCriteria.Async(request, callSettings);
}
}
}
| 53.306958 | 574 | 0.667119 | [
"Apache-2.0"
] | friedenberg/google-ads-dotnet | src/V9/Services/CustomerNegativeCriterionServiceClient.g.cs | 39,074 | C# |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V9.Resources;
namespace Google.Ads.GoogleAds.V9.Services
{
public partial class GetAgeRangeViewRequest
{
/// <summary>
/// <see cref="gagvr::AgeRangeViewName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
public gagvr::AgeRangeViewName ResourceNameAsAgeRangeViewName
{
get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::AgeRangeViewName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
}
}
| 37.060606 | 128 | 0.696648 | [
"Apache-2.0"
] | friedenberg/google-ads-dotnet | src/V9/Services/AgeRangeViewServiceResourceNames.g.cs | 1,223 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Daihenka.AssetPipeline.Filters;
using Daihenka.AssetPipeline.Import;
using Daihenka.AssetPipeline.Processors;
using UnityEditor;
using UnityEngine;
using UnityEngine.Rendering;
namespace Daihenka.AssetPipeline.PropertyDrawers
{
[CustomPropertyDrawer(typeof(SetupMaterials.MaterialSetup))]
internal class MaterialSetupPropertyDrawer : PropertyDrawer
{
static readonly Texture s_HiddenIcon = EditorGUIUtility.FindTexture("scenevis_hidden_hover@2x");
static float singleLineHeight => EditorGUIUtility.singleLineHeight;
static string[] shaderNames => SetupMaterialsInspector.m_ShaderNames;
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
var propHeights = 0f;
var propMappings = property.FindPropertyRelative("propertyMappings");
for (var i = 0; i < propMappings.arraySize; i++) {
var shaderProperty = propMappings.GetArrayElementAtIndex(i);
if (IsShaderPropertyType(shaderProperty, ShaderUtil.ShaderPropertyType.TexEnv)) {
propHeights += EditorGUI.GetPropertyHeight(shaderProperty.FindPropertyRelative("textureNameFilter"), GetShaderPropertyName(shaderProperty));
}
else if (IsShaderPropertyType(shaderProperty, ShaderUtil.ShaderPropertyType.Color)) {
propHeights += EditorGUI.GetPropertyHeight(shaderProperty.FindPropertyRelative("colorValue"), GetShaderPropertyName(shaderProperty));
}
else if (IsShaderPropertyType(shaderProperty, ShaderUtil.ShaderPropertyType.Vector)) {
propHeights += EditorGUI.GetPropertyHeight(shaderProperty.FindPropertyRelative("vectorValue"), GetShaderPropertyName(shaderProperty));
}
else if (IsShaderPropertyType(shaderProperty, ShaderUtil.ShaderPropertyType.Float)) {
propHeights += EditorGUI.GetPropertyHeight(shaderProperty.FindPropertyRelative("floatValue"), GetShaderPropertyName(shaderProperty));
}
else if (IsShaderPropertyType(shaderProperty, ShaderUtil.ShaderPropertyType.Range)) {
propHeights += EditorGUI.GetPropertyHeight(shaderProperty.FindPropertyRelative("floatValue"), GetShaderPropertyName(shaderProperty));
}
}
return singleLineHeight * 4 + propHeights + 36 + propMappings.arraySize * 2;
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
var rect = new Rect(position.x, position.y + 12, position.width, singleLineHeight);
var propMappings = property.FindPropertyRelative("propertyMappings");
EditorGUI.PropertyField(rect, property.FindPropertyRelative("materialFilter"), DaiGUIContent.materialNameFilter);
rect.y += singleLineHeight + 2;
DrawShaderDropdown(rect, property, propMappings);
rect.y += singleLineHeight + 2;
EditorGUI.PropertyField(rect, property.FindPropertyRelative("textureSearch"));
rect.y += singleLineHeight + 2;
rect.y += 6;
if (propMappings.arraySize == 0)
{
EditorGUI.LabelField(rect, "No Material Properties", DaiGUIStyles.boldLabelCentered);
rect.y += singleLineHeight + 1;
}
else
{
EditorGUI.LabelField(rect, "Material Properties", DaiGUIStyles.boldLabel);
rect.y += singleLineHeight + 1;
for (var i = 0; i < propMappings.arraySize; i++)
{
var propMap = propMappings.GetArrayElementAtIndex(i);
rect.y += DrawShaderProperty(rect, propMap) + 2;
}
}
}
static float DrawShaderProperty(Rect rect, SerializedProperty property)
{
var height = 0f;
EditorGUI.PropertyField(rect, property.FindPropertyRelative("overridden"), GUIContent.none);
GUI.enabled = property.FindPropertyRelative("overridden").boolValue;
var rectPropertyField = new Rect(rect.x + 18, rect.y, rect.width - 18, rect.height);
if (IsShaderPropertyType(property, ShaderUtil.ShaderPropertyType.TexEnv))
{
var isSet = !string.IsNullOrEmpty(property.FindPropertyRelative("textureNameFilter").FindPropertyRelative("pattern").stringValue);
height = EditorGUI.GetPropertyHeight(property.FindPropertyRelative("textureNameFilter"), GetShaderPropertyName(property));
EditorGUI.PropertyField(rectPropertyField, property.FindPropertyRelative("textureNameFilter"), GetShaderPropertyName(property));
EditorGUI.DrawRect(new Rect(rect.x - 14, rect.y, 4, rect.height), AssetPipelineSettings.GetStatusColor(isSet));
DrawTexture(rect, AssetImportPipeline.AssetTypeIcons[ImportAssetType.Textures]);
DrawHiddenTexture(rect, property, 22);
}
else if (IsShaderPropertyType(property, ShaderUtil.ShaderPropertyType.Color))
{
height = EditorGUI.GetPropertyHeight(property.FindPropertyRelative("colorValue"), GetShaderPropertyName(property));
EditorGUI.PropertyField(rectPropertyField, property.FindPropertyRelative("colorValue"), GetShaderPropertyName(property));
DrawHiddenTexture(rect, property);
}
else if (IsShaderPropertyType(property, ShaderUtil.ShaderPropertyType.Vector))
{
height = EditorGUI.GetPropertyHeight(property.FindPropertyRelative("vectorValue"), GetShaderPropertyName(property));
var vectorProp = property.FindPropertyRelative("vectorValue");
vectorProp.vector4Value = EditorGUI.Vector4Field(rectPropertyField, GetShaderPropertyName(property), vectorProp.vector4Value);
DrawHiddenTexture(rect, property);
}
else if (IsShaderPropertyType(property, ShaderUtil.ShaderPropertyType.Float))
{
var propName = property.FindPropertyRelative("materialPropertyName").stringValue;
height = EditorGUI.GetPropertyHeight(property.FindPropertyRelative("floatValue"), GetShaderPropertyName(property));
var floatProp = property.FindPropertyRelative("floatValue");
var propLabel = GetShaderPropertyName(property);
switch (propName)
{
case "_SrcBlend":
case "_DstBlend":
floatProp.floatValue = EditorGUI.IntPopup(rectPropertyField, propLabel, (int) floatProp.floatValue, Enum.GetNames(typeof(BlendMode)).Select(x => new GUIContent(x)).ToArray(), (int[]) Enum.GetValues(typeof(BlendMode)));
break;
case "_AlphaClip":
case "_ZWrite":
floatProp.floatValue = EditorGUI.Toggle(rectPropertyField, propLabel, (int) floatProp.floatValue == 1) ? 1f : 0f;
break;
case "_Surface":
floatProp.floatValue = EditorGUI.IntPopup(rectPropertyField, propLabel, (int) floatProp.floatValue, Enum.GetNames(typeof(SurfaceType)).Select(x => new GUIContent(x)).ToArray(), (int[]) Enum.GetValues(typeof(SurfaceType)));
break;
case "_Cull":
floatProp.floatValue = EditorGUI.IntPopup(rectPropertyField, propLabel, (int) floatProp.floatValue, Enum.GetNames(typeof(CullMode)).Select(x => new GUIContent(x)).ToArray(), (int[]) Enum.GetValues(typeof(CullMode)));
break;
default:
EditorGUI.PropertyField(rectPropertyField, floatProp, propLabel);
break;
}
DrawHiddenTexture(rect, property);
}
else if (IsShaderPropertyType(property, ShaderUtil.ShaderPropertyType.Range))
{
height = EditorGUI.GetPropertyHeight(property.FindPropertyRelative("floatValue"), GetShaderPropertyName(property));
EditorGUI.Slider(rectPropertyField, property.FindPropertyRelative("floatValue"), property.FindPropertyRelative("minRange").floatValue, property.FindPropertyRelative("maxRange").floatValue, GetShaderPropertyName(property));
DrawHiddenTexture(rect, property);
}
GUI.enabled = true;
return height;
}
static void DrawHiddenTexture(Rect rect, SerializedProperty prop, int offset = 2)
{
if (prop.FindPropertyRelative("isHidden").boolValue)
DrawTexture(rect, s_HiddenIcon, offset);
}
static void DrawTexture(Rect rect, Texture assetTypeIcon, float offset = 2)
{
GUI.DrawTexture(new Rect(rect.x + EditorGUIUtility.labelWidth + 2f - offset, rect.y + (rect.height - 16) * 0.5f, 16, 16), assetTypeIcon);
}
static GUIContent GetShaderPropertyName(SerializedProperty prop)
{
var propLabel = prop.FindPropertyRelative("materialPropertyDescription").stringValue;
return new GUIContent(string.IsNullOrEmpty(propLabel) ? prop.FindPropertyRelative("materialPropertyName").stringValue : propLabel);
}
static bool IsShaderPropertyType(SerializedProperty prop, ShaderUtil.ShaderPropertyType type)
{
return prop.FindPropertyRelative("materialPropertyType").enumValueIndex == (int) type;
}
static void DrawShaderDropdown(Rect rect, SerializedProperty property, SerializedProperty propMappings)
{
var shaderProp = property.FindPropertyRelative("shader");
var shader = (Shader) shaderProp.objectReferenceValue;
var shaderIndex = shader ? ArrayUtility.IndexOf(shaderNames, shader.name) : -1;
var newShaderIndex = EditorGUI.Popup(rect, "Shader", shaderIndex, shaderNames);
if (newShaderIndex != shaderIndex)
{
shader = Shader.Find(shaderNames[newShaderIndex]);
shaderProp.objectReferenceValue = shader;
UpdateMaterialPropertyMappings(property, propMappings, shader);
}
}
static void UpdateMaterialPropertyMappings(SerializedProperty property, SerializedProperty propMappings, Shader shader)
{
property.serializedObject.ApplyModifiedProperties();
var propMap = propMappings.GetSerializedValue<List<SetupMaterials.MaterialTextureMap>>();
propMap.Clear();
for (var i = 0; i < ShaderUtil.GetPropertyCount(shader); i++)
{
var propName = ShaderUtil.GetPropertyName(shader, i);
var propDesc = ShaderUtil.GetPropertyDescription(shader, i);
var propType = ShaderUtil.GetPropertyType(shader, i);
var isHidden = ShaderUtil.IsShaderPropertyHidden(shader, i);
if (propType == ShaderUtil.ShaderPropertyType.TexEnv)
{
propMap.Add(new SetupMaterials.MaterialTextureMap(propName, propDesc, new PathFilter {pattern = ""}, isHidden));
}
else if (propType == ShaderUtil.ShaderPropertyType.Color)
{
propMap.Add(new SetupMaterials.MaterialTextureMap(propName, propDesc, ShaderUtil.ShaderPropertyType.Color, shader.GetPropertyDefaultVectorValue(i), isHidden));
}
else if (propType == ShaderUtil.ShaderPropertyType.Vector)
{
propMap.Add(new SetupMaterials.MaterialTextureMap(propName, propDesc, ShaderUtil.ShaderPropertyType.Vector, shader.GetPropertyDefaultVectorValue(i), isHidden));
}
else if (propType == ShaderUtil.ShaderPropertyType.Float)
{
propMap.Add(new SetupMaterials.MaterialTextureMap(propName, propDesc, shader.GetPropertyDefaultFloatValue(i), isHidden));
}
else if (propType == ShaderUtil.ShaderPropertyType.Range)
{
var value = ShaderUtil.GetRangeLimits(shader, i, 0);
var min = ShaderUtil.GetRangeLimits(shader, i, 1);
var max = ShaderUtil.GetRangeLimits(shader, i, 2);
propMap.Add(new SetupMaterials.MaterialTextureMap(propName, propDesc, value, min, max, isHidden));
}
}
property.serializedObject.Update();
}
enum SurfaceType
{
Opaque,
Transparent
}
}
}
| 55.95671 | 246 | 0.638945 | [
"MIT"
] | bpastoors/asset-pipeline | Editor/Interface/PropertyDrawers/MaterialSetupPropertyDrawer.cs | 12,928 | C# |
/*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; 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 org.camunda.bpm.example.invoice.service
{
using ProcessEngineException = org.camunda.bpm.engine.ProcessEngineException;
using DelegateExecution = org.camunda.bpm.engine.@delegate.DelegateExecution;
using JavaDelegate = org.camunda.bpm.engine.@delegate.JavaDelegate;
using FileValue = org.camunda.bpm.engine.variable.value.FileValue;
/// <summary>
/// <para>This is an empty service implementation illustrating how to use a plain
/// Java Class as a BPMN 2.0 Service Task delegate.</para>
/// </summary>
public class ArchiveInvoiceService : JavaDelegate
{
//JAVA TO C# CONVERTER WARNING: The .NET Type.FullName property will not always yield results identical to the Java Class.getName method:
private readonly Logger LOGGER = Logger.getLogger(typeof(ArchiveInvoiceService).FullName);
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public void execute(org.camunda.bpm.engine.delegate.DelegateExecution execution) throws Exception
public virtual void execute(DelegateExecution execution)
{
bool? shouldFail = (bool?) execution.getVariable("shouldFail");
FileValue invoiceDocumentVar = execution.getVariableTyped("invoiceDocument");
if (shouldFail != null && shouldFail)
{
throw new ProcessEngineException("Could not archive invoice...");
}
else
{
LOGGER.info("\n\n ... Now archiving invoice " + execution.getVariable("invoiceNumber") + ", filename: " + invoiceDocumentVar.Filename + " \n\n");
}
}
}
} | 41.553571 | 150 | 0.758058 | [
"Apache-2.0"
] | luizfbicalho/Camunda.NET | camunda-bpm-platform-net/examples/invoice/src/main/java/org/camunda/bpm/example/invoice/service/ArchiveInvoiceService.cs | 2,329 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using Newtonsoft.Json;
using UiPath.Orchestrator.Extensibility.Configuration;
using UiPath.Orchestrator.Extensibility.SecureStores;
namespace DevOpsVault.SecureStore
{
public class DevOpsVaultSecureStore : ISecureStore
{
private readonly IDevOpsVaultClientFactory _clientFactory;
private IDevOpsVaultClient _dsvClient;
public DevOpsVaultSecureStore() : this(new DevOpsVaultClientFactory())
{
}
public DevOpsVaultSecureStore(IDevOpsVaultClientFactory clientFactory)
{
_clientFactory = clientFactory;
}
public void Initialize(Dictionary<string, string> hostSettings)
{
}
public SecureStoreInfo GetStoreInfo()
{
return new SecureStoreInfo {Identifier = "DevOpsSecretsVault", IsReadOnly = false};
}
public async Task ValidateContextAsync(string context)
{
var id = Guid.NewGuid();
var ctx = DeserializeContext(context);
_dsvClient = await _clientFactory.GetClient(ctx);
var response = await _dsvClient.CreateSecretAsync($"validate:{id}", id.ToString());
await _dsvClient.DeleteSecretAsync(response);
}
public IEnumerable<ConfigurationEntry> GetConfiguration()
{
return new List<ConfigurationEntry>
{
new ConfigurationValue(ConfigurationValueType.String)
{
Key = "DevOpsVaultUrl",
DisplayName = DevOpsVaultResource.GetResource("DevOpsVaultUrl"),
IsMandatory = true,
},
new ConfigurationValue(ConfigurationValueType.String)
{
Key = "ClientId",
DisplayName = DevOpsVaultResource.GetResource("ClientId"),
IsMandatory = true,
},
new ConfigurationValue(ConfigurationValueType.String)
{
Key = "ClientSecret",
DisplayName = DevOpsVaultResource.GetResource("ClientSecret"),
IsMandatory = true,
},
new ConfigurationValue(ConfigurationValueType.String)
{
Key = "BasePathPrefix",
DisplayName = DevOpsVaultResource.GetResource("BasePathPrefix"),
DefaultValue = "uipath",
},
};
}
public async Task<string> CreateValueAsync(string context, string key, string value)
{
var ctx = DeserializeContext(context);
value = value ?? throw new ArgumentNullException(nameof(value));
_dsvClient = await _clientFactory.GetClient(ctx);
var response = await _dsvClient.CreateSecretAsync(key, value);
return response;
}
public async Task<string> GetValueAsync(string context, string key)
{
var ctx = DeserializeContext(context);
key = key ?? throw new SecureStoreException();
_dsvClient = await _clientFactory.GetClient(ctx);
var response = await _dsvClient.GetSecretAsync(key);
return response?.Data["password"].ToString();
}
public async Task<string> CreateCredentialsAsync(string context, string key, Credential value)
{
var ctx = DeserializeContext(context);
value = value ?? throw new ArgumentNullException(nameof(value));
_dsvClient = await _clientFactory.GetClient(ctx);
var response = await _dsvClient.CreateSecretAsync(key, value);
return response;
}
public async Task<Credential> GetCredentialsAsync(string context, string key)
{
var ctx = DeserializeContext(context);
key = key ?? throw new SecureStoreException();
_dsvClient = await _clientFactory.GetClient(ctx);
var response = await _dsvClient.GetSecretAsync(key);
return new Credential()
{
Username = response.Data["username"].ToString(),
Password = response.Data["password"].ToString(),
};
}
public async Task<string> UpdateValueAsync(string context, string key, string oldAugumentedKey, string value)
{
var ctx = DeserializeContext(context);
key = key ?? throw new SecureStoreException();
_dsvClient = await _clientFactory.GetClient(ctx);
var response = await _dsvClient.UpdateSecretAsync(key, oldAugumentedKey, value);
return response;
}
public async Task<string> UpdateCredentialsAsync(string context, string key, string oldAugumentedKey,
Credential value)
{
var ctx = DeserializeContext(context);
key = key ?? throw new SecureStoreException();
_dsvClient = await _clientFactory.GetClient(ctx);
var response = await _dsvClient.UpdateSecretAsync(key, oldAugumentedKey, value);
return response;
}
public async Task RemoveValueAsync(string context, string key)
{
var ctx = DeserializeContext(context);
key = key ?? throw new SecureStoreException();
_dsvClient = await _clientFactory.GetClient(ctx);
await _dsvClient.DeleteSecretAsync(key);
}
private DevOpsVaultContext DeserializeContext(string context)
{
var dsvConfig = JsonConvert.DeserializeObject<DevOpsVaultContext>(context);
return dsvConfig;
}
}
} | 39.265306 | 117 | 0.605163 | [
"Apache-2.0"
] | thycotic/uipath-orchestrator | DevOpsVault.SecureStore/DevOpsVaultSecureStore.cs | 5,774 | C# |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using Microsoft.Azure.Commands.Compute.Automation.Models;
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Management.Compute.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Compute.Automation
{
[Cmdlet(VerbsCommon.Get, ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "Snapshot", DefaultParameterSetName = "DefaultParameter")]
[OutputType(typeof(PSSnapshot))]
public partial class GetAzureRmSnapshot : ComputeAutomationBaseCmdlet
{
public override void ExecuteCmdlet()
{
base.ExecuteCmdlet();
ExecuteClientAction(() =>
{
string resourceGroupName = this.ResourceGroupName;
string snapshotName = this.SnapshotName;
if (!string.IsNullOrEmpty(resourceGroupName) && !string.IsNullOrEmpty(snapshotName))
{
var result = SnapshotsClient.Get(resourceGroupName, snapshotName);
var psObject = new PSSnapshot();
ComputeAutomationAutoMapperProfile.Mapper.Map<Snapshot, PSSnapshot>(result, psObject);
WriteObject(psObject);
}
else if (!string.IsNullOrEmpty(resourceGroupName))
{
var result = SnapshotsClient.ListByResourceGroup(resourceGroupName);
var resultList = result.ToList();
var nextPageLink = result.NextPageLink;
while (!string.IsNullOrEmpty(nextPageLink))
{
var pageResult = SnapshotsClient.ListByResourceGroupNext(nextPageLink);
foreach (var pageItem in pageResult)
{
resultList.Add(pageItem);
}
nextPageLink = pageResult.NextPageLink;
}
var psObject = new List<PSSnapshotList>();
foreach (var r in resultList)
{
psObject.Add(ComputeAutomationAutoMapperProfile.Mapper.Map<Snapshot, PSSnapshotList>(r));
}
WriteObject(psObject, true);
}
else
{
var result = SnapshotsClient.List();
var resultList = result.ToList();
var nextPageLink = result.NextPageLink;
while (!string.IsNullOrEmpty(nextPageLink))
{
var pageResult = SnapshotsClient.ListNext(nextPageLink);
foreach (var pageItem in pageResult)
{
resultList.Add(pageItem);
}
nextPageLink = pageResult.NextPageLink;
}
var psObject = new List<PSSnapshotList>();
foreach (var r in resultList)
{
psObject.Add(ComputeAutomationAutoMapperProfile.Mapper.Map<Snapshot, PSSnapshotList>(r));
}
WriteObject(psObject, true);
}
});
}
[Parameter(
ParameterSetName = "DefaultParameter",
Position = 1,
ValueFromPipelineByPropertyName = true)]
[ResourceGroupCompleter]
public string ResourceGroupName { get; set; }
[Parameter(
ParameterSetName = "DefaultParameter",
Position = 2,
ValueFromPipelineByPropertyName = true)]
[ResourceNameCompleter("Microsoft.Compute/snapshots", "ResourceGroupName")]
[Alias("Name")]
public string SnapshotName { get; set; }
}
}
| 42.692982 | 144 | 0.567906 | [
"MIT"
] | Acidburn0zzz/azure-powershell | src/ResourceManager/Compute/Commands.Compute/Generated/Snapshot/SnapshotGetMethod.cs | 4,754 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Android.App;
// 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("FreeChat.Android")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FreeChat.Android")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[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("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
// Add some common permissions, these can be removed if not needed
[assembly: UsesPermission(Android.Manifest.Permission.Internet)]
[assembly: UsesPermission(Android.Manifest.Permission.WriteExternalStorage)]
| 36.542857 | 84 | 0.756059 | [
"MIT"
] | DamienDoumer/freechat | FreeChat/FreeChat.Android/Properties/AssemblyInfo.cs | 1,282 | C# |
namespace PcapNgNet.Options;
public class StringOption : Option
{
[SerializeAs(SerializedType.SizedString)]
public string Value { get; set; }
}
| 19.25 | 45 | 0.733766 | [
"MIT"
] | jefffhaynes/PcapNgNet | PcapNgNet/Options/StringOption.cs | 156 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Data.Common;
using Microsoft.TestCommon;
using Moq;
using WebMatrix.Data.Test.Mocks;
namespace WebMatrix.Data.Test
{
public class DatabaseTest
{
[Fact]
public void OpenWithNullConnectionStringNameThrowsException()
{
Assert.ThrowsArgumentNullOrEmptyString(() => Database.Open(null), "name");
}
[Fact]
public void OpenConnectionStringWithNullConnectionStringThrowsException()
{
Assert.ThrowsArgumentNullOrEmptyString(
() => Database.OpenConnectionString(null),
"connectionString"
);
}
[Fact]
public void OpenConnectionStringWithEmptyConnectionStringThrowsException()
{
Assert.ThrowsArgumentNullOrEmptyString(
() => Database.OpenConnectionString(String.Empty),
"connectionString"
);
}
[Fact]
public void OpenNamedConnectionUsesConnectionStringFromConfigurationIfExists()
{
// Arrange
MockConfigurationManager mockConfigurationManager = new MockConfigurationManager();
Mock<DbConnection> mockConnection = new Mock<DbConnection>();
mockConnection.Setup(m => m.ConnectionString).Returns("connection string");
Mock<MockDbProviderFactory> mockProviderFactory = new Mock<MockDbProviderFactory>();
mockProviderFactory
.Setup(m => m.CreateConnection("connection string"))
.Returns(mockConnection.Object);
mockConfigurationManager.AddConnection(
"foo",
new ConnectionConfiguration(mockProviderFactory.Object, "connection string")
);
// Act
Database db = Database.OpenNamedConnection("foo", mockConfigurationManager);
// Assert
Assert.Equal("connection string", db.Connection.ConnectionString);
}
[Fact]
public void OpenNamedConnectionThrowsIfNoConnectionFound()
{
// Arrange
IConfigurationManager mockConfigurationManager = new MockConfigurationManager();
// Act & Assert
Assert.Throws<InvalidOperationException>(
() => Database.OpenNamedConnection("foo", mockConfigurationManager),
"Connection string \"foo\" was not found."
);
}
[Fact]
public void GetConnectionConfigurationGetConnectionForFileHandlersIfRegistered()
{
// Arrange
var mockHandler = new Mock<MockDbFileHandler>();
mockHandler
.Setup(m => m.GetConnectionConfiguration("filename.foo"))
.Returns(new MockConnectionConfiguration("some file based connection"));
var handlers = new Dictionary<string, IDbFileHandler>
{
{ ".foo", mockHandler.Object }
};
// Act
IConnectionConfiguration configuration = Database.GetConnectionConfiguration(
"filename.foo",
handlers
);
// Assert
Assert.NotNull(configuration);
Assert.Equal("some file based connection", configuration.ConnectionString);
}
[Fact]
public void GetConnectionThrowsIfNoHandlersRegisteredForExtension()
{
// Arrange
var handlers = new Dictionary<string, IDbFileHandler>();
// Act
Assert.Throws<InvalidOperationException>(
() => Database.GetConnectionConfiguration("filename.foo", handlers),
"Unable to determine the provider for the database file \"filename.foo\"."
);
}
}
}
| 35.39823 | 111 | 0.60675 | [
"Apache-2.0"
] | belav/AspNetWebStack | test/WebMatrix.Data.Test/DatabaseTest.cs | 4,002 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
namespace System.Data.Entity.Core.Mapping
{
using System.Data.Entity.Core.Metadata.Edm;
// <summary>
// Mapping metadata for all OC member maps.
// </summary>
internal class ObjectAssociationEndMapping : ObjectMemberMapping
{
// <summary>
// Construct a new AssociationEnd member mapping metadata object
// </summary>
internal ObjectAssociationEndMapping(AssociationEndMember edmAssociationEnd, AssociationEndMember clrAssociationEnd)
: base(edmAssociationEnd, clrAssociationEnd)
{
}
// <summary>
// return the member mapping kind
// </summary>
internal override MemberMappingKind MemberMappingKind
{
get { return MemberMappingKind.AssociationEndMapping; }
}
}
}
| 32.655172 | 132 | 0.670539 | [
"Apache-2.0"
] | CZEMacLeod/EntityFramework6 | src/EntityFramework/Core/Mapping/ObjectAssociationEndMapping.cs | 947 | C# |
/*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* 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.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/
using Microsoft.Scripting.Utils;
using Microsoft.Scripting.Runtime;
using IronRuby.Runtime;
using IronRuby.Builtins;
using System;
using System.Runtime.InteropServices;
namespace rho.rubyext
{
[RubyModule("RhoConf")]
public static class RhoConfig
{
#region Private Implementation Details
#endregion
#region Private Instance & Singleton Methods
[RubyMethodAttribute("set_property_by_name", RubyMethodAttributes.PublicSingleton)]
public static void set_property_by_name(RubyModule/*!*/ self, [NotNull]String/*!*/ name, Object value)
{
}
[RubyMethodAttribute("get_property_by_name", RubyMethodAttributes.PublicSingleton)]
public static Object get_property_by_name(RubyModule/*!*/ self, [NotNull]String/*!*/ name)
{
return null;
}
[RubyMethodAttribute("is_property_exists", RubyMethodAttributes.PublicSingleton)]
public static Boolean is_property_exists(RubyModule/*!*/ self, [NotNull]String/*!*/ name)
{
return true;
}
[RubyMethodAttribute("show_log", RubyMethodAttributes.PublicSingleton)]
public static void show_log(RubyModule/*!*/ self)
{
}
[RubyMethodAttribute("send_log", RubyMethodAttributes.PublicSingleton)]
public static void send_log(RubyModule/*!*/ self)
{
}
[RubyMethodAttribute("clean_log", RubyMethodAttributes.PublicSingleton)]
public static void clean_log(RubyModule/*!*/ self)
{
}
[RubyMethodAttribute("read_log", RubyMethodAttributes.PublicSingleton)]
public static void read_log(RubyModule/*!*/ self, int limit = 0)
{
}
#endregion
}
}
| 36.035294 | 110 | 0.667646 | [
"MIT"
] | abmahmoodi/rhodes | platform/wp7/RhoRubyExtGen/RhoConfig.cs | 3,065 | C# |
using HarmonyLib;
using Verse;
namespace RimBank.Trade
{
[StaticConstructorOnStartup]
internal static class DetourInjectorCompact
{
static DetourInjectorCompact()
{
var harmony = new Harmony("user19990313.RimBank-Unofficial");
harmony.PatchAll();
}
}
} | 21.2 | 73 | 0.638365 | [
"MIT"
] | emipa606/RimBank | Source/RimBank.Trade/DetourInjectorCompact.cs | 320 | 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 kafka-2018-11-14.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.Kafka.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Kafka.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for NodeExporter Object
/// </summary>
public class NodeExporterUnmarshaller : IUnmarshaller<NodeExporter, XmlUnmarshallerContext>, IUnmarshaller<NodeExporter, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
NodeExporter IUnmarshaller<NodeExporter, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
{
throw new NotImplementedException();
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public NodeExporter Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
if (context.CurrentTokenType == JsonToken.Null)
return null;
NodeExporter unmarshalledObject = new NodeExporter();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("enabledInBroker", targetDepth))
{
var unmarshaller = BoolUnmarshaller.Instance;
unmarshalledObject.EnabledInBroker = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static NodeExporterUnmarshaller _instance = new NodeExporterUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static NodeExporterUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 33.271739 | 149 | 0.6377 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/Kafka/Generated/Model/Internal/MarshallTransformations/NodeExporterUnmarshaller.cs | 3,061 | C# |
using System;
using UniDecAPI;
namespace UniDec.WSFTPLegacy.Codec
{
public class Codec : ICodec
{
public string FriendlyName { get { return "WS FTP Legacy"; } }
public string CallName { get { return "wsftp-le"; } }
public bool NeedsKey { get { return false; } }
private string _preamble = "PWD=V";
private readonly Random _random = new Random();
public string Decode(string input)
{
try
{
var actualInput = input;
if (!input.Contains("PWD="))
{
actualInput = "PWD=" + input;
}
var decodedText = "";
var pw = actualInput.Substring(37, actualInput.Length - 37);
for (var i = 0; i < pw.Length / 2; i++)
{
var character = pw.Substring(i * 2, 2);
var salt = actualInput.Substring(5 + i, (6 + i) - (5 + i));
var decodedCharacter = Convert.ToInt32(character, 16) - i - 1 -
((47 + Convert.ToInt32(salt, 16)) % 57);
decodedText += (char)decodedCharacter;
}
return decodedText;
}
catch
{
return "Invalid string specified.";
}
}
public string Encode(string input)
{
if (input.Length > 32)
return "Password too long (32 characters maximum).";
var salt = "";
var encodedString = _preamble;
for (var i = 0; i < 32; i++)
{
salt += _random.Next(0, 15).ToString("X");
}
encodedString += salt;
for (var i = 0; i < input.Length; i++)
{
var encodedCharacter = input[i] + i + 1 + (47 + Convert.ToInt32(salt.Substring(i, 1), 16)) % 57;
encodedString += encodedCharacter.ToString("X");
}
return encodedString;
}
public string Decode(string input, string key)
{
return "No key required.";
}
public string Encode(string input, string key)
{
return "No key required.";
}
}
}
| 30.513158 | 112 | 0.455369 | [
"MIT"
] | parmik1/UniDec | UniDec.WSFTPLegacy.Codec/Codec.cs | 2,321 | C# |
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
// ReSharper disable CheckNamespace
// ReSharper disable CommentTypo
// ReSharper disable IdentifierTypo
// ReSharper disable MemberCanBePrivate.Global
// ReSharper disable UnusedAutoPropertyAccessor.Global
// ReSharper disable UnusedType.Global
#region Using directives
using System;
using System.Text.Json.Serialization;
using System.Windows.Forms;
using System.Xml.Serialization;
using AM;
using AM.Json;
#endregion
#nullable enable
namespace FormsTests
{
public sealed class FormsTest
: IFormsTest
{
#region Properties
/// <summary>
/// Имя класса с тестом.
/// </summary>
[XmlAttribute("class")]
[JsonPropertyName("class")]
public string? ClassName { get; set; }
/// <summary>
/// Заголовок.
/// </summary>
[XmlAttribute("title")]
[JsonPropertyName("title")]
public string? Title { get; set; }
#endregion
#region Public methods
public static FormsTest[] LoadFromFile (string fileName) =>
JsonUtility.ReadObjectFromFile<FormsTest[]>(fileName);
#endregion
#region IFormsTest members
/// <summary>
/// Run the test.
/// </summary>
public void RunTest
(
IWin32Window? ownerWindow
)
{
var type = Type.GetType
(
ClassName.ThrowIfNull("ClassName"),
true
)
.ThrowIfNull("Type.GetType");
var testObject = (IFormsTest) Activator.CreateInstance(type)
.ThrowIfNull("Activator.CreateInstance");
testObject.RunTest(ownerWindow);
if (testObject is IDisposable disposable)
{
disposable.Dispose();
}
} // method RunTest
#endregion
#region Object members
/// <inheritdoc cref="object.ToString"/>
public override string ToString() => Title.ToVisibleString();
#endregion
} // class FormsTest
} // namespace FormsTest
| 23.791667 | 84 | 0.58669 | [
"MIT"
] | amironov73/ManagedIrbis5 | Source/Tests/FormsTests/Source/FormsTest.cs | 2,311 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Yapp
{
[CreateAssetMenu(fileName = Constants.TemplateCollection_FileName, menuName = Constants.TemplateCollection_MenuName)]
[System.Serializable]
public class PrefabTemplateCollection : ScriptableObject
{
/// <summary>
/// Collection of various prefab settings templates
/// </summary>
[SerializeField]
public List<PrefabSettingsTemplate> templates = new List<PrefabSettingsTemplate>();
}
} | 31.882353 | 121 | 0.723247 | [
"MIT"
] | TheWizardsCode/PrefabPainter | Assets/Yapp/Scripts/PrefabTemplateCollection.cs | 544 | C# |
// Copyright (c) Microsoft Corporation
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
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("Microsoft.Xbox.Services.UnitTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Microsoft.Xbox.Services.UnitTests")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("6a9cef50-6bef-4b8a-8da5-f1fd0c1ba666")]
// 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")]
| 39.6 | 101 | 0.75 | [
"MIT"
] | Barallob/xbox-live-unity-plugin | CSharpSource/Source/Microsoft.Xbox.Services.UnitTests/Properties/AssemblyInfo.cs | 1,587 | C# |
// GENERATED AUTOMATICALLY FROM 'Assets/Scripts/InputSystem/JoystickInputs.inputactions'
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Utilities;
public class @JoystickInputs : IInputActionCollection, IDisposable
{
public InputActionAsset asset { get; }
public @JoystickInputs()
{
asset = InputActionAsset.FromJson(@"{
""name"": ""JoystickInputs"",
""maps"": [
{
""name"": ""MouseJoystick"",
""id"": ""3d44236e-168b-4d99-85f0-198853ce2419"",
""actions"": [
{
""name"": ""RightOne"",
""type"": ""Button"",
""id"": ""983b64a8-ef1d-4660-b44d-f2c3e9f7c918"",
""expectedControlType"": ""Button"",
""processors"": """",
""interactions"": """"
},
{
""name"": ""LeftOne"",
""type"": ""Button"",
""id"": ""fc0f4c33-5f0f-4791-9880-0ca783ae1bc7"",
""expectedControlType"": ""Button"",
""processors"": """",
""interactions"": """"
},
{
""name"": ""RightStickUp"",
""type"": ""Button"",
""id"": ""5f5b8476-0974-487a-9597-0468e909326e"",
""expectedControlType"": ""Button"",
""processors"": """",
""interactions"": """"
},
{
""name"": ""RightStickDown"",
""type"": ""Button"",
""id"": ""0c1bda4c-6203-4b7d-8d04-ddf63138984f"",
""expectedControlType"": ""Button"",
""processors"": """",
""interactions"": """"
}
],
""bindings"": [
{
""name"": """",
""id"": ""b6747678-d4ae-4bf5-8749-7bb0354208ab"",
""path"": ""<Gamepad>/rightShoulder"",
""interactions"": """",
""processors"": """",
""groups"": """",
""action"": ""RightOne"",
""isComposite"": false,
""isPartOfComposite"": false
},
{
""name"": """",
""id"": ""2931fbdb-8945-43a2-a9f0-a516e600890d"",
""path"": ""<Gamepad>/leftShoulder"",
""interactions"": """",
""processors"": """",
""groups"": """",
""action"": ""LeftOne"",
""isComposite"": false,
""isPartOfComposite"": false
}
]
},
{
""name"": ""KeyboardJoystick"",
""id"": ""b9e14ca5-bc31-40a3-a4f8-456323252e54"",
""actions"": [
{
""name"": ""RightTwo"",
""type"": ""Button"",
""id"": ""af26fddc-01a3-4864-bec1-cd5401345b2a"",
""expectedControlType"": ""Button"",
""processors"": """",
""interactions"": """"
},
{
""name"": ""LeftTwo"",
""type"": ""Button"",
""id"": ""fdf52754-210c-46dd-bdea-ed641572866f"",
""expectedControlType"": ""Button"",
""processors"": """",
""interactions"": """"
},
{
""name"": ""SouthButton"",
""type"": ""Button"",
""id"": ""5fd1fbc7-3084-4ed7-a528-c3f14283ccde"",
""expectedControlType"": ""Button"",
""processors"": """",
""interactions"": """"
},
{
""name"": ""NorthButton"",
""type"": ""Button"",
""id"": ""0e5f07be-43f0-4776-ba44-763e573fac2e"",
""expectedControlType"": ""Button"",
""processors"": """",
""interactions"": """"
},
{
""name"": ""EastButton"",
""type"": ""Button"",
""id"": ""ebeb2842-d9c9-4e11-b1a4-440e14ba8167"",
""expectedControlType"": ""Button"",
""processors"": """",
""interactions"": """"
},
{
""name"": ""WestButton"",
""type"": ""Button"",
""id"": ""2342b977-e412-439d-83bb-b4fb28b90279"",
""expectedControlType"": ""Button"",
""processors"": """",
""interactions"": """"
}
],
""bindings"": [
{
""name"": """",
""id"": ""b56dc999-d533-47ee-9c71-a7bcea3b3f41"",
""path"": ""<Gamepad>/rightTrigger"",
""interactions"": """",
""processors"": """",
""groups"": """",
""action"": ""RightTwo"",
""isComposite"": false,
""isPartOfComposite"": false
},
{
""name"": """",
""id"": ""678b0cc1-c854-4cfe-a060-5b80694e6e16"",
""path"": ""<Gamepad>/leftTrigger"",
""interactions"": """",
""processors"": """",
""groups"": """",
""action"": ""LeftTwo"",
""isComposite"": false,
""isPartOfComposite"": false
},
{
""name"": """",
""id"": ""473e1cd1-4893-48f3-b7a5-64128cd2b48a"",
""path"": ""<Gamepad>/buttonSouth"",
""interactions"": """",
""processors"": """",
""groups"": """",
""action"": ""SouthButton"",
""isComposite"": false,
""isPartOfComposite"": false
},
{
""name"": """",
""id"": ""4b5ee8c1-6b7b-436c-a116-4c2a2464c02a"",
""path"": ""<Gamepad>/buttonNorth"",
""interactions"": """",
""processors"": """",
""groups"": """",
""action"": ""NorthButton"",
""isComposite"": false,
""isPartOfComposite"": false
},
{
""name"": """",
""id"": ""1e529b09-8484-4653-9d59-8afdc9525407"",
""path"": ""<Gamepad>/buttonEast"",
""interactions"": """",
""processors"": """",
""groups"": """",
""action"": ""EastButton"",
""isComposite"": false,
""isPartOfComposite"": false
},
{
""name"": """",
""id"": ""0dac3b2b-bb47-429d-985c-0f7d2a4e5573"",
""path"": ""<Gamepad>/buttonWest"",
""interactions"": """",
""processors"": """",
""groups"": """",
""action"": ""WestButton"",
""isComposite"": false,
""isPartOfComposite"": false
}
]
}
],
""controlSchemes"": []
}");
// MouseJoystick
m_MouseJoystick = asset.FindActionMap("MouseJoystick", throwIfNotFound: true);
m_MouseJoystick_RightOne = m_MouseJoystick.FindAction("RightOne", throwIfNotFound: true);
m_MouseJoystick_LeftOne = m_MouseJoystick.FindAction("LeftOne", throwIfNotFound: true);
m_MouseJoystick_RightStickUp = m_MouseJoystick.FindAction("RightStickUp", throwIfNotFound: true);
m_MouseJoystick_RightStickDown = m_MouseJoystick.FindAction("RightStickDown", throwIfNotFound: true);
// KeyboardJoystick
m_KeyboardJoystick = asset.FindActionMap("KeyboardJoystick", throwIfNotFound: true);
m_KeyboardJoystick_RightTwo = m_KeyboardJoystick.FindAction("RightTwo", throwIfNotFound: true);
m_KeyboardJoystick_LeftTwo = m_KeyboardJoystick.FindAction("LeftTwo", throwIfNotFound: true);
m_KeyboardJoystick_SouthButton = m_KeyboardJoystick.FindAction("SouthButton", throwIfNotFound: true);
m_KeyboardJoystick_NorthButton = m_KeyboardJoystick.FindAction("NorthButton", throwIfNotFound: true);
m_KeyboardJoystick_EastButton = m_KeyboardJoystick.FindAction("EastButton", throwIfNotFound: true);
m_KeyboardJoystick_WestButton = m_KeyboardJoystick.FindAction("WestButton", throwIfNotFound: true);
}
public void Dispose()
{
UnityEngine.Object.Destroy(asset);
}
public InputBinding? bindingMask
{
get => asset.bindingMask;
set => asset.bindingMask = value;
}
public ReadOnlyArray<InputDevice>? devices
{
get => asset.devices;
set => asset.devices = value;
}
public ReadOnlyArray<InputControlScheme> controlSchemes => asset.controlSchemes;
public bool Contains(InputAction action)
{
return asset.Contains(action);
}
public IEnumerator<InputAction> GetEnumerator()
{
return asset.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void Enable()
{
asset.Enable();
}
public void Disable()
{
asset.Disable();
}
// MouseJoystick
private readonly InputActionMap m_MouseJoystick;
private IMouseJoystickActions m_MouseJoystickActionsCallbackInterface;
private readonly InputAction m_MouseJoystick_RightOne;
private readonly InputAction m_MouseJoystick_LeftOne;
private readonly InputAction m_MouseJoystick_RightStickUp;
private readonly InputAction m_MouseJoystick_RightStickDown;
public struct MouseJoystickActions
{
private @JoystickInputs m_Wrapper;
public MouseJoystickActions(@JoystickInputs wrapper) { m_Wrapper = wrapper; }
public InputAction @RightOne => m_Wrapper.m_MouseJoystick_RightOne;
public InputAction @LeftOne => m_Wrapper.m_MouseJoystick_LeftOne;
public InputAction @RightStickUp => m_Wrapper.m_MouseJoystick_RightStickUp;
public InputAction @RightStickDown => m_Wrapper.m_MouseJoystick_RightStickDown;
public InputActionMap Get() { return m_Wrapper.m_MouseJoystick; }
public void Enable() { Get().Enable(); }
public void Disable() { Get().Disable(); }
public bool enabled => Get().enabled;
public static implicit operator InputActionMap(MouseJoystickActions set) { return set.Get(); }
public void SetCallbacks(IMouseJoystickActions instance)
{
if (m_Wrapper.m_MouseJoystickActionsCallbackInterface != null)
{
@RightOne.started -= m_Wrapper.m_MouseJoystickActionsCallbackInterface.OnRightOne;
@RightOne.performed -= m_Wrapper.m_MouseJoystickActionsCallbackInterface.OnRightOne;
@RightOne.canceled -= m_Wrapper.m_MouseJoystickActionsCallbackInterface.OnRightOne;
@LeftOne.started -= m_Wrapper.m_MouseJoystickActionsCallbackInterface.OnLeftOne;
@LeftOne.performed -= m_Wrapper.m_MouseJoystickActionsCallbackInterface.OnLeftOne;
@LeftOne.canceled -= m_Wrapper.m_MouseJoystickActionsCallbackInterface.OnLeftOne;
@RightStickUp.started -= m_Wrapper.m_MouseJoystickActionsCallbackInterface.OnRightStickUp;
@RightStickUp.performed -= m_Wrapper.m_MouseJoystickActionsCallbackInterface.OnRightStickUp;
@RightStickUp.canceled -= m_Wrapper.m_MouseJoystickActionsCallbackInterface.OnRightStickUp;
@RightStickDown.started -= m_Wrapper.m_MouseJoystickActionsCallbackInterface.OnRightStickDown;
@RightStickDown.performed -= m_Wrapper.m_MouseJoystickActionsCallbackInterface.OnRightStickDown;
@RightStickDown.canceled -= m_Wrapper.m_MouseJoystickActionsCallbackInterface.OnRightStickDown;
}
m_Wrapper.m_MouseJoystickActionsCallbackInterface = instance;
if (instance != null)
{
@RightOne.started += instance.OnRightOne;
@RightOne.performed += instance.OnRightOne;
@RightOne.canceled += instance.OnRightOne;
@LeftOne.started += instance.OnLeftOne;
@LeftOne.performed += instance.OnLeftOne;
@LeftOne.canceled += instance.OnLeftOne;
@RightStickUp.started += instance.OnRightStickUp;
@RightStickUp.performed += instance.OnRightStickUp;
@RightStickUp.canceled += instance.OnRightStickUp;
@RightStickDown.started += instance.OnRightStickDown;
@RightStickDown.performed += instance.OnRightStickDown;
@RightStickDown.canceled += instance.OnRightStickDown;
}
}
}
public MouseJoystickActions @MouseJoystick => new MouseJoystickActions(this);
// KeyboardJoystick
private readonly InputActionMap m_KeyboardJoystick;
private IKeyboardJoystickActions m_KeyboardJoystickActionsCallbackInterface;
private readonly InputAction m_KeyboardJoystick_RightTwo;
private readonly InputAction m_KeyboardJoystick_LeftTwo;
private readonly InputAction m_KeyboardJoystick_SouthButton;
private readonly InputAction m_KeyboardJoystick_NorthButton;
private readonly InputAction m_KeyboardJoystick_EastButton;
private readonly InputAction m_KeyboardJoystick_WestButton;
public struct KeyboardJoystickActions
{
private @JoystickInputs m_Wrapper;
public KeyboardJoystickActions(@JoystickInputs wrapper) { m_Wrapper = wrapper; }
public InputAction @RightTwo => m_Wrapper.m_KeyboardJoystick_RightTwo;
public InputAction @LeftTwo => m_Wrapper.m_KeyboardJoystick_LeftTwo;
public InputAction @SouthButton => m_Wrapper.m_KeyboardJoystick_SouthButton;
public InputAction @NorthButton => m_Wrapper.m_KeyboardJoystick_NorthButton;
public InputAction @EastButton => m_Wrapper.m_KeyboardJoystick_EastButton;
public InputAction @WestButton => m_Wrapper.m_KeyboardJoystick_WestButton;
public InputActionMap Get() { return m_Wrapper.m_KeyboardJoystick; }
public void Enable() { Get().Enable(); }
public void Disable() { Get().Disable(); }
public bool enabled => Get().enabled;
public static implicit operator InputActionMap(KeyboardJoystickActions set) { return set.Get(); }
public void SetCallbacks(IKeyboardJoystickActions instance)
{
if (m_Wrapper.m_KeyboardJoystickActionsCallbackInterface != null)
{
@RightTwo.started -= m_Wrapper.m_KeyboardJoystickActionsCallbackInterface.OnRightTwo;
@RightTwo.performed -= m_Wrapper.m_KeyboardJoystickActionsCallbackInterface.OnRightTwo;
@RightTwo.canceled -= m_Wrapper.m_KeyboardJoystickActionsCallbackInterface.OnRightTwo;
@LeftTwo.started -= m_Wrapper.m_KeyboardJoystickActionsCallbackInterface.OnLeftTwo;
@LeftTwo.performed -= m_Wrapper.m_KeyboardJoystickActionsCallbackInterface.OnLeftTwo;
@LeftTwo.canceled -= m_Wrapper.m_KeyboardJoystickActionsCallbackInterface.OnLeftTwo;
@SouthButton.started -= m_Wrapper.m_KeyboardJoystickActionsCallbackInterface.OnSouthButton;
@SouthButton.performed -= m_Wrapper.m_KeyboardJoystickActionsCallbackInterface.OnSouthButton;
@SouthButton.canceled -= m_Wrapper.m_KeyboardJoystickActionsCallbackInterface.OnSouthButton;
@NorthButton.started -= m_Wrapper.m_KeyboardJoystickActionsCallbackInterface.OnNorthButton;
@NorthButton.performed -= m_Wrapper.m_KeyboardJoystickActionsCallbackInterface.OnNorthButton;
@NorthButton.canceled -= m_Wrapper.m_KeyboardJoystickActionsCallbackInterface.OnNorthButton;
@EastButton.started -= m_Wrapper.m_KeyboardJoystickActionsCallbackInterface.OnEastButton;
@EastButton.performed -= m_Wrapper.m_KeyboardJoystickActionsCallbackInterface.OnEastButton;
@EastButton.canceled -= m_Wrapper.m_KeyboardJoystickActionsCallbackInterface.OnEastButton;
@WestButton.started -= m_Wrapper.m_KeyboardJoystickActionsCallbackInterface.OnWestButton;
@WestButton.performed -= m_Wrapper.m_KeyboardJoystickActionsCallbackInterface.OnWestButton;
@WestButton.canceled -= m_Wrapper.m_KeyboardJoystickActionsCallbackInterface.OnWestButton;
}
m_Wrapper.m_KeyboardJoystickActionsCallbackInterface = instance;
if (instance != null)
{
@RightTwo.started += instance.OnRightTwo;
@RightTwo.performed += instance.OnRightTwo;
@RightTwo.canceled += instance.OnRightTwo;
@LeftTwo.started += instance.OnLeftTwo;
@LeftTwo.performed += instance.OnLeftTwo;
@LeftTwo.canceled += instance.OnLeftTwo;
@SouthButton.started += instance.OnSouthButton;
@SouthButton.performed += instance.OnSouthButton;
@SouthButton.canceled += instance.OnSouthButton;
@NorthButton.started += instance.OnNorthButton;
@NorthButton.performed += instance.OnNorthButton;
@NorthButton.canceled += instance.OnNorthButton;
@EastButton.started += instance.OnEastButton;
@EastButton.performed += instance.OnEastButton;
@EastButton.canceled += instance.OnEastButton;
@WestButton.started += instance.OnWestButton;
@WestButton.performed += instance.OnWestButton;
@WestButton.canceled += instance.OnWestButton;
}
}
}
public KeyboardJoystickActions @KeyboardJoystick => new KeyboardJoystickActions(this);
public interface IMouseJoystickActions
{
void OnRightOne(InputAction.CallbackContext context);
void OnLeftOne(InputAction.CallbackContext context);
void OnRightStickUp(InputAction.CallbackContext context);
void OnRightStickDown(InputAction.CallbackContext context);
}
public interface IKeyboardJoystickActions
{
void OnRightTwo(InputAction.CallbackContext context);
void OnLeftTwo(InputAction.CallbackContext context);
void OnSouthButton(InputAction.CallbackContext context);
void OnNorthButton(InputAction.CallbackContext context);
void OnEastButton(InputAction.CallbackContext context);
void OnWestButton(InputAction.CallbackContext context);
}
}
| 47.64878 | 112 | 0.555999 | [
"MIT"
] | Maestroymn/LoremIpsumJamProject | Assets/Scripts/InputSystem/JoystickInputs.cs | 19,536 | C# |
using Catel.Windows;
using PresetMagician.ViewModels;
namespace PresetMagician.Views
{
public partial class CharacteristicView
{
public CharacteristicView(CharacteristicViewModel viewModel) : base(viewModel, DataWindowMode.OkCancel)
{
InitializeComponent();
}
}
} | 24 | 111 | 0.705128 | [
"MIT"
] | PresetMagician/PresetMagician | PresetMagician/Views/CharacteristicView.xaml.cs | 312 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
static public class HalperLogs {
static public string gatherDataHierarchyInfo(Transform tr)
{
string ct = "";
if (tr.parent != null) ct = tr.parent + "/" + tr.name;
else ct = tr.name;
ct += " (children " + tr.childCount + ") " + tr.gameObject.activeSelf;
ct += "[";
Component[] comps = tr.GetComponents<Component>();
for (int i = 0; i < comps.Length; i++)
{
ct += "," + comps[i].GetType();
}
ct += "]";
foreach(Transform child in tr)
{
ct += "\n L "+ gatherDataHierarchyInfo(child);
}
return ct;
}
}
| 21.354839 | 74 | 0.57855 | [
"MIT"
] | Legogo/fwProtoss | Sources/halper/HalperLogs.cs | 664 | 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/MsHTML.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System;
using System.Runtime.InteropServices;
using static TerraFX.Interop.Windows.IID;
namespace TerraFX.Interop.Windows.UnitTests;
/// <summary>Provides validation of the <see cref="HTMLPopup" /> struct.</summary>
public static unsafe partial class HTMLPopupTests
{
/// <summary>Validates that the <see cref="Guid" /> of the <see cref="HTMLPopup" /> struct is correct.</summary>
[Test]
public static void GuidOfTest()
{
Assert.That(typeof(HTMLPopup).GUID, Is.EqualTo(IID_HTMLPopup));
}
/// <summary>Validates that the <see cref="HTMLPopup" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<HTMLPopup>(), Is.EqualTo(sizeof(HTMLPopup)));
}
/// <summary>Validates that the <see cref="HTMLPopup" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(HTMLPopup).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="HTMLPopup" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
Assert.That(sizeof(HTMLPopup), Is.EqualTo(1));
}
}
| 35.136364 | 145 | 0.69599 | [
"MIT"
] | IngmarBitter/terrafx.interop.windows | tests/Interop/Windows/Windows/um/MsHTML/HTMLPopupTests.cs | 1,548 | 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("CoursesiOS")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CoursesiOS")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bd5e860b-2047-4b0f-8344-88df53b82609")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.648649 | 84 | 0.744436 | [
"MIT"
] | MikaelGyth/Courses | CoursesiOS/Properties/AssemblyInfo.cs | 1,396 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.