content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using Microsoft.EntityFrameworkCore.Migrations; namespace WebApplicationEF.Migrations { public partial class typetable_uint : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "Uint", table: "TestType"); migrationBuilder.AlterColumn<short>( name: "Sbyte", table: "TestType", type: "SMALLINT(6)", nullable: false, oldClrType: typeof(short)); migrationBuilder.AlterColumn<short>( name: "Bool", table: "TestType", nullable: false, oldClrType: typeof(short)); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.AlterColumn<short>( name: "Sbyte", table: "TestType", nullable: false, oldClrType: typeof(short), oldType: "SMALLINT(6)"); migrationBuilder.AlterColumn<short>( name: "Bool", table: "TestType", nullable: false, oldClrType: typeof(short)); migrationBuilder.AddColumn<long>( name: "Uint", table: "TestType", nullable: false, defaultValue: 0L); } } }
29.44
71
0.498641
[ "MIT" ]
guitarrapc/CSharpPracticesLab
database/mysql/entityframework_mysql/src/WebApplicationEF/Migrations/20190719045406_typetable_uint.cs
1,474
C#
using CodingTrainer.CSharpRunner.CodeHost; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace CodingTrainer.CSharpRunner.Assessment { public class PreProgrammedTextReader : StringReader, ITextWriterInjectable { public PreProgrammedTextReader(string s) : base(s) { } public TextWriter TextWriter { private get; set; } public override int Read() { int result = base.Read(); if (result == -1) throw new EndOfStreamException("You have read too many lines from the console"); TextWriter?.Write(char.ConvertFromUtf32(result)); return result; } public override int Read([In, Out] char[] buffer, int index, int count) { int result = base.Read(buffer, index, count); if (result == 0 && count != 0) throw new EndOfStreamException("You have read too many lines from the console"); var output = new char[count]; TextWriter?.Write(buffer.Skip(index).Take(result)); return result; } public override string ReadToEnd() { if (Peek() == -1) throw new EndOfStreamException("You have read too many lines from the console"); string result = base.ReadToEnd(); TextWriter?.Write(result); return result; } public override string ReadLine() { if (Peek() == -1) throw new EndOfStreamException("You have read too many lines from the console"); string result = base.ReadLine(); TextWriter?.WriteLine(result); return result; } } }
31.982143
123
0.610274
[ "Apache-2.0" ]
ddashwood/CodingTrainer
Assessment/PreProgrammedTextReader.cs
1,793
C#
using Newtonsoft.Json; namespace SlackITSupport.SlackLibrary.JsonParsing.TeamJson.TeamLogsJson { public class JsonTeamLogin { [JsonProperty("user_id")] public string UserId { get; set; } [JsonProperty("username")] public string Username { get; set; } [JsonProperty("date_first")] public string TsFirst { get; set; } [JsonProperty("date_last")] public string TsLast { get; set; } [JsonProperty("count")] public int Count { get; set; } [JsonProperty("ip")] public string Ip { get; set; } [JsonProperty("user_agent")] public string UserAgent { get; set; } [JsonProperty("isp")] public string Isp { get; set; } [JsonProperty("country")] public string Country { get; set; } [JsonProperty("region")] public string Region { get; set; } } }
32.357143
71
0.587196
[ "Unlicense" ]
CarsonCook/SlackLibrary
SlackLibrary/JsonParsing/TeamJson/TeamLogsJson/JsonTeamLogin.cs
908
C#
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace $projectname$ { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { WpfToolset.AppHelper.AttachErrorHandling(this, e); base.OnStartup(e); } } }
21.869565
62
0.662028
[ "MIT" ]
Seti-0/microsoft-tools
Source/TemplateProject/App.xaml.cs
505
C#
using System; using System.Threading.Tasks; using IdentityServer4.Models; using IdentityServer4.Validation; using Microsoft.AspNetCore.Identity; using Xunit; namespace LeanCode.ExternalIdentityProviders.Tests { public class ExternalLoginGrantValidatorTests { private readonly UserManager<User> users = UserManager.PrepareInMemory(); private readonly ExternalLoginStub externalLogin; private readonly ExternalLoginGrantValidatorStub grantValidator; public ExternalLoginGrantValidatorTests() { externalLogin = new ExternalLoginStub(users); grantValidator = new ExternalLoginGrantValidatorStub(externalLogin); } [Fact] public async Task Passing_null_token_results_in_no_assertion_error() { var res = await ValidateAsync(null); res.AssertInvalid("no_assertion"); } [Fact] public async Task Passing_empty_token_results_in_no_assertion_error() { var res = await ValidateAsync(""); res.AssertInvalid("no_assertion"); } [Fact] public async Task Passing_invalid_token_results_in_invalid_assertion_error() { var res = await ValidateAsync("test"); res.AssertInvalid("invalid_assertion"); } [Fact] public async Task Passing_not_connected_token_results_in_no_user_error() { var token = AddToken(); var res = await ValidateAsync(token); res.AssertInvalid("no_user"); } [Fact] public async Task Passing_connected_token_succeeds() { var (token, uid) = await AddConnectedUserAsync(); var res = await ValidateAsync(token); res.AssertValid(uid); } private async Task<GrantValidationResult> ValidateAsync(string? token) { var ctx = new ExtensionGrantValidationContext { Request = new ValidatedTokenRequest { Raw = new System.Collections.Specialized.NameValueCollection { ["assertion"] = token, }, }, }; await grantValidator.ValidateAsync(ctx); Assert.NotNull(ctx.Result); return ctx.Result; } private async Task<(string, Guid)> AddConnectedUserAsync() { var token = AddToken(); var uid = await users.AddUserAsync(); await externalLogin.ConnectAsync(uid, token); return (token, uid); } private string AddToken() => externalLogin.AddToken(); } internal static class GrantValidationResultExtensions { public static void AssertValid(this GrantValidationResult result, Guid uid) { Assert.False(result.IsError); Assert.NotNull(result.Subject); Assert.Equal(uid.ToString(), result.Subject.FindFirst("sub")?.Value); } public static void AssertInvalid(this GrantValidationResult result, string error) { Assert.True(result.IsError); Assert.Equal("invalid_grant", result.Error); Assert.Equal(error, result.ErrorDescription); } } }
30.418182
89
0.603407
[ "Apache-2.0" ]
leancodepl/corelibrary
test/Infrastructure/LeanCode.ExternalIdentityProviders.Tests/ExternalLoginGrantValidatorTests.cs
3,346
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Alidns.Model.V20150109; using System; using System.Collections.Generic; namespace Aliyun.Acs.Alidns.Transform.V20150109 { public class RetrievalDomainNameResponseUnmarshaller { public static RetrievalDomainNameResponse Unmarshall(UnmarshallerContext context) { RetrievalDomainNameResponse retrievalDomainNameResponse = new RetrievalDomainNameResponse(); retrievalDomainNameResponse.HttpResponse = context.HttpResponse; retrievalDomainNameResponse.RequestId = context.StringValue("RetrievalDomainName.RequestId"); retrievalDomainNameResponse.DomainName = context.StringValue("RetrievalDomainName.DomainName"); retrievalDomainNameResponse.WhoisEmail = context.StringValue("RetrievalDomainName.WhoisEmail"); return retrievalDomainNameResponse; } } }
41.925
99
0.775194
[ "Apache-2.0" ]
DMIAOCHEN/AliyunService
Depends/aliyun-net-sdk-alidns/Alidns/Transform/V20150109/RetrievalDomainNameResponseUnmarshaller.cs
1,677
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.HealthcareApis.Models { using Microsoft.Rest; using Newtonsoft.Json; using System.Linq; /// <summary> /// The settings for the Cosmos DB database backing the service. /// </summary> public partial class ServiceCosmosDbConfigurationInfo { /// <summary> /// Initializes a new instance of the ServiceCosmosDbConfigurationInfo /// class. /// </summary> public ServiceCosmosDbConfigurationInfo() { CustomInit(); } /// <summary> /// Initializes a new instance of the ServiceCosmosDbConfigurationInfo /// class. /// </summary> /// <param name="offerThroughput">The provisioned throughput for the /// backing database.</param> public ServiceCosmosDbConfigurationInfo(int? offerThroughput = default(int?)) { OfferThroughput = offerThroughput; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets the provisioned throughput for the backing database. /// </summary> [JsonProperty(PropertyName = "offerThroughput")] public int? OfferThroughput { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (OfferThroughput > 10000) { throw new ValidationException(ValidationRules.InclusiveMaximum, "OfferThroughput", 10000); } if (OfferThroughput < 400) { throw new ValidationException(ValidationRules.InclusiveMinimum, "OfferThroughput", 400); } } } }
31.695652
106
0.595336
[ "MIT" ]
AzureMentor/azure-sdk-for-net
sdk/healthcareapis/Microsoft.Azure.Management.HealthcareApis/src/Generated/Models/ServiceCosmosDbConfigurationInfo.cs
2,187
C#
#region License /* Distributed under the terms of a MIT-style license: The MIT License Copyright (c) 2010 Marius Klimantavičius Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Marius.Html.Internal; using Marius.Html.Dom; namespace Marius.Html.Css.Selectors { // specifity 1,0,0,0 public class CssInlineElementSelector: CssSelector { private static readonly CssSpecificity StyleSpecificity = new CssSpecificity(1, 0, 0, 0); public IElementNode Element { get; private set; } public override CssSelectorType SelectorType { get { return CssSelectorType.InlineStyle; } } public CssInlineElementSelector(IElementNode element) { Element = element; } public override CssSpecificity Specificity { get { return StyleSpecificity; } } public override bool Equals(CssSelector other) { CssInlineElementSelector o = other as CssInlineElementSelector; if (o == null) return false; return o.Element.Equals(this.Element); } public override int GetHashCode() { return Utils.GetHashCode(Element, SelectorType); } } }
33.054795
98
0.690012
[ "MIT" ]
marius-klimantavicius/marius-html
Marius.Html/Css/Selectors/CssInlineElementSelector.cs
2,416
C#
using System.Collections.Generic; namespace DevAdventCalendarCompetition.Vms { public class TestResultsVm { public List<SingleTestResultsVm> SingleTestResults { get; set; } public List<TotalTestResultEntryVm> TotalTestResults { get; set; } } }
24.909091
74
0.726277
[ "MIT" ]
Loji/DevAdventCalendar
src/DevAdventCalendarCompetition/DevAdventCalendarCompetition/Vms/TestResultsVm.cs
276
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("11.PracticeCharAndStrings")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("11.PracticeCharAndStrings")] [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("da195884-124d-4098-80c9-bf9d50535243")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.459459
84
0.748419
[ "MIT" ]
yvelikov/Programming-Fundamentals
Data Types and Variables - Exercises Extended/Data Types and Variables - Exercises/11.PracticeCharAndStrings/Properties/AssemblyInfo.cs
1,426
C#
namespace WinForms.Reactive.Client.Views { partial class ItemsDDView { /// <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.btnLoad = new System.Windows.Forms.Button(); this.txtSearchStartsWith = new System.Windows.Forms.TextBox(); this.lstItems = new System.Windows.Forms.ListBox(); this.txtSearchEndsWith = new System.Windows.Forms.TextBox(); this.cmbSortBy = new System.Windows.Forms.ComboBox(); this.lblStartsWith = new System.Windows.Forms.Label(); this.lblEndsWith = new System.Windows.Forms.Label(); this.lblSortBy = new System.Windows.Forms.Label(); this.SuspendLayout(); // // btnLoad // this.btnLoad.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnLoad.Location = new System.Drawing.Point(1344, 53); this.btnLoad.Name = "btnLoad"; this.btnLoad.Size = new System.Drawing.Size(188, 58); this.btnLoad.TabIndex = 0; this.btnLoad.Text = "Load"; this.btnLoad.UseVisualStyleBackColor = true; // // txtSearchStartsWith // this.txtSearchStartsWith.Location = new System.Drawing.Point(182, 59); this.txtSearchStartsWith.Name = "txtSearchStartsWith"; this.txtSearchStartsWith.Size = new System.Drawing.Size(250, 47); this.txtSearchStartsWith.TabIndex = 1; // // lstItems // this.lstItems.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.lstItems.ColumnWidth = 200; this.lstItems.FormattingEnabled = true; this.lstItems.ItemHeight = 41; this.lstItems.Location = new System.Drawing.Point(21, 163); this.lstItems.MultiColumn = true; this.lstItems.Name = "lstItems"; this.lstItems.Size = new System.Drawing.Size(1511, 701); this.lstItems.TabIndex = 2; // // txtSearchEndsWith // this.txtSearchEndsWith.Location = new System.Drawing.Point(615, 59); this.txtSearchEndsWith.Name = "txtSearchEndsWith"; this.txtSearchEndsWith.Size = new System.Drawing.Size(250, 47); this.txtSearchEndsWith.TabIndex = 3; // // cmbSortBy // this.cmbSortBy.FormattingEnabled = true; this.cmbSortBy.Location = new System.Drawing.Point(1028, 57); this.cmbSortBy.Name = "cmbSortBy"; this.cmbSortBy.Size = new System.Drawing.Size(302, 49); this.cmbSortBy.TabIndex = 4; // // lblStartsWith // this.lblStartsWith.AutoSize = true; this.lblStartsWith.Location = new System.Drawing.Point(21, 62); this.lblStartsWith.Name = "lblStartsWith"; this.lblStartsWith.Size = new System.Drawing.Size(155, 41); this.lblStartsWith.TabIndex = 5; this.lblStartsWith.Text = "Starts with"; // // lblEndsWith // this.lblEndsWith.AutoSize = true; this.lblEndsWith.Location = new System.Drawing.Point(464, 62); this.lblEndsWith.Name = "lblEndsWith"; this.lblEndsWith.Size = new System.Drawing.Size(145, 41); this.lblEndsWith.TabIndex = 6; this.lblEndsWith.Text = "Ends with"; // // lblSortBy // this.lblSortBy.AutoSize = true; this.lblSortBy.Location = new System.Drawing.Point(909, 62); this.lblSortBy.Name = "lblSortBy"; this.lblSortBy.Size = new System.Drawing.Size(113, 41); this.lblSortBy.TabIndex = 7; this.lblSortBy.Text = "Sort by"; // // ItemsDDView // this.AutoScaleDimensions = new System.Drawing.SizeF(17F, 41F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.lblSortBy); this.Controls.Add(this.lblEndsWith); this.Controls.Add(this.lblStartsWith); this.Controls.Add(this.cmbSortBy); this.Controls.Add(this.txtSearchEndsWith); this.Controls.Add(this.lstItems); this.Controls.Add(this.txtSearchStartsWith); this.Controls.Add(this.btnLoad); this.Name = "ItemsDDView"; this.Size = new System.Drawing.Size(1556, 906); this.ResumeLayout(false); this.PerformLayout(); } #endregion private Button btnLoad; private TextBox txtSearchStartsWith; private ListBox lstItems; private TextBox txtSearchEndsWith; private ComboBox cmbSortBy; private Label lblStartsWith; private Label lblEndsWith; private Label lblSortBy; } }
41.627586
157
0.581842
[ "MIT" ]
rallets/ReactiveUI.Samples
winforms/demo2/WinForms.Reactive.Client/Views/ItemsDDView.Designer.cs
6,038
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.Diagnostics; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace Microsoft.EntityFrameworkCore.Metadata.Internal { /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerDisplay("{" + nameof(Metadata) + ",nq}")] public abstract class InternalAnnotatableBuilder : IConventionAnnotatableBuilder { /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> protected InternalAnnotatableBuilder([NotNull] ConventionAnnotatable metadata) { Metadata = metadata; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual ConventionAnnotatable Metadata { [DebuggerStepThrough] get; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public abstract InternalModelBuilder ModelBuilder { [DebuggerStepThrough] get; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalAnnotatableBuilder HasAnnotation( [NotNull] string name, [CanBeNull] object value, ConfigurationSource configurationSource) => HasAnnotation(name, value, configurationSource, canOverrideSameSource: true); private InternalAnnotatableBuilder HasAnnotation( string name, object value, ConfigurationSource configurationSource, bool canOverrideSameSource) { var existingAnnotation = Metadata.FindAnnotation(name); if (existingAnnotation != null) { if (Equals(existingAnnotation.Value, value)) { existingAnnotation.UpdateConfigurationSource(configurationSource); return this; } if (!CanSetAnnotationValue(existingAnnotation, value, configurationSource, canOverrideSameSource)) { return null; } Metadata.SetAnnotation(name, value, configurationSource); return this; } Metadata.AddAnnotation(name, value, configurationSource); return this; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalAnnotatableBuilder SetOrRemoveAnnotation( [NotNull] string name, [CanBeNull] object value, ConfigurationSource configurationSource) => value == null ? RemoveAnnotation(name, configurationSource) : HasAnnotation(name, value, configurationSource, canOverrideSameSource: true); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual bool CanSetAnnotation([NotNull] string name, [CanBeNull] object value, ConfigurationSource configurationSource) { var existingAnnotation = Metadata.FindAnnotation(name); return existingAnnotation == null || CanSetAnnotationValue(existingAnnotation, value, configurationSource, canOverrideSameSource: true); } private static bool CanSetAnnotationValue( ConventionAnnotation annotation, object value, ConfigurationSource configurationSource, bool canOverrideSameSource) { if (Equals(annotation.Value, value)) { return true; } var existingConfigurationSource = annotation.GetConfigurationSource(); return configurationSource.Overrides(existingConfigurationSource) && (configurationSource != existingConfigurationSource || canOverrideSameSource); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalAnnotatableBuilder RemoveAnnotation([NotNull] string name, ConfigurationSource configurationSource) { if (!CanRemoveAnnotation(name, configurationSource)) { return null; } Metadata.RemoveAnnotation(name); return this; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual bool CanRemoveAnnotation([NotNull] string name, ConfigurationSource configurationSource) { var existingAnnotation = Metadata.FindAnnotation(name); return existingAnnotation == null || configurationSource.Overrides(existingAnnotation.GetConfigurationSource()); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void MergeAnnotationsFrom([NotNull] ConventionAnnotatable annotatable) => MergeAnnotationsFrom(annotatable, ConfigurationSource.Explicit); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void MergeAnnotationsFrom( [NotNull] ConventionAnnotatable annotatable, ConfigurationSource minimalConfigurationSource) { foreach (var annotation in annotatable.GetAnnotations()) { var configurationSource = annotation.GetConfigurationSource(); if (configurationSource.Overrides(minimalConfigurationSource)) { HasAnnotation( annotation.Name, annotation.Value, configurationSource, canOverrideSameSource: false); } } } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> IConventionModelBuilder IConventionAnnotatableBuilder.ModelBuilder => ModelBuilder; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> IConventionAnnotatable IConventionAnnotatableBuilder.Metadata => Metadata; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> IConventionAnnotatableBuilder IConventionAnnotatableBuilder.HasAnnotation(string name, object value, bool fromDataAnnotation) => HasAnnotation(name, value, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> IConventionAnnotatableBuilder IConventionAnnotatableBuilder.SetOrRemoveAnnotation( string name, object value, bool fromDataAnnotation) => SetOrRemoveAnnotation(name, value, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> bool IConventionAnnotatableBuilder.CanSetAnnotation(string name, object value, bool fromDataAnnotation) => CanSetAnnotation(name, value, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> IConventionAnnotatableBuilder IConventionAnnotatableBuilder.RemoveAnnotation(string name, bool fromDataAnnotation) => RemoveAnnotation(name, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> bool IConventionAnnotatableBuilder.CanRemoveAnnotation(string name, bool fromDataAnnotation) => CanRemoveAnnotation(name, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); } }
61.685484
140
0.675579
[ "Apache-2.0" ]
GiorgioG/efcore
src/EFCore/Metadata/Internal/InternalAnnotatableBuilder.cs
15,298
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using Microsoft.Azure.Cosmos; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.Solutions.CosmosDB.SQL.ChangeFeed { public class ChangeFeedProcessHelper<TEntity> { public async Task<ChangeFeedProcessor> InitChangeFeedProcessorAsync( string DataConnectionString, string SourceDatabaseName, string MonitoredContainerName, Container.ChangesHandler<TEntity> ChangeHandler ) { Container leaseContainer; Database database; string leaseContainerName = $"{MonitoredContainerName}_lease"; var processorName = $"{MonitoredContainerName}_changefeedwatcher"; var instanceName = $"{processorName}_host_{Guid.NewGuid().ToString().Substring(0,8)}"; //Initialize CosmosDB Connection CosmosClient cosmosClient = new CosmosClient(DataConnectionString); database = cosmosClient.GetDatabase(SourceDatabaseName); if (database is null) throw new NullReferenceException("Specified Database doesn't exist"); leaseContainer = await database.CreateContainerIfNotExistsAsync(leaseContainerName, "/partitionKey"); ChangeFeedProcessor changeFeedProcessor = database.GetContainer(MonitoredContainerName) .GetChangeFeedProcessorBuilder<TEntity>(processorName: processorName, ChangeHandler) .WithInstanceName(instanceName) .WithLeaseContainer(leaseContainer) .Build(); Console.WriteLine($"Starting Change Feed Processor...{processorName} in {instanceName}"); await changeFeedProcessor.StartAsync(); Console.WriteLine($"Change Feed Processor {processorName} started in {instanceName}"); return changeFeedProcessor; } } }
48.571429
127
0.584874
[ "MIT" ]
microsoft/CosmosDB-Solution-Accelerator-CosmosDB-Helper
src/Libraries/Microsoft.Solutions.CosmosDB.SQL.ChangeFeed/ChangeFeedProcessorHelper.cs
2,382
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; public abstract class Property { protected string name; public Animator ani; public GameObject playerUnit;//獲取玩家單位 public NavMeshAgent agent; public Transform trans;//初始位置 public Vector3 initialPosition; public float wanderRadius; //游走半径,移动状态下,如果超出游走半径会返回出生位置 public float alertRadius; //警戒半径,玩家进入后怪物会发出警告,并一直面朝玩家 public float defendRadius; //自卫半径,玩家进入后怪物会追击玩家,当距离<攻击距离则会发动攻击(或者触发战斗) public float chaseRadius; //追击半径,当怪物超出追击半径后会放弃追击,返回追击起始位置 public float attackRange; //攻击距离 public float walkSpeed; //移动速度 public float runSpeed; //跑动速度 public float turnSpeed; //转身速度,建议0.1 public MonsterAby.MonsterState currentState = MonsterAby.MonsterState.Idle;//閒置時間 public float[] actionWeight;//设置待机时各种动作的权重,顺序依次为呼吸、观察、移动 public float actRestTime;//更換待機指令的間隔時間 public float lastActTime;//最近一次指令時間 public float distanceToPlayer;//與玩家距離 public float distanceToInitial;//怪物與初始位置的距離 public Quaternion targetRotation;//怪物的目標朝向 public bool is_Warned = false; public bool is_Running = false; public bool detectPlayer = false; public float subAngle; public float lookAngle; public int lookAccurate; }
29.956522
85
0.708999
[ "MIT" ]
karta571110/MonsterAi
Turtle/Assets/Turtle/Scripts/Property.cs
1,818
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. /*============================================================================= ** ** ** ** Purpose: To handle features that don't run on particular platforms ** ** =============================================================================*/ using System.Runtime.Serialization; namespace System { [Serializable] public class PlatformNotSupportedException : NotSupportedException { public PlatformNotSupportedException() : base(SR.Arg_PlatformNotSupported) { HResult = HResults.COR_E_PLATFORMNOTSUPPORTED; } public PlatformNotSupportedException(string message) : base(message) { HResult = HResults.COR_E_PLATFORMNOTSUPPORTED; } public PlatformNotSupportedException(string message, Exception inner) : base(message, inner) { HResult = HResults.COR_E_PLATFORMNOTSUPPORTED; } protected PlatformNotSupportedException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
29.25
119
0.584305
[ "MIT" ]
alfredr/corefx
src/Common/src/CoreLib/System/PlatformNotSupportedException.cs
1,287
C#
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Neo.Common.Storage.SQLiteModules { [Table("AssetBalance")] public class AssetBalanceEntity { [Key] public long Id { get; set; } public long AddressId { get; set; } public AddressEntity Address { get; set; } public long AssetId { get; set; } public ContractEntity Asset { get; set; } public byte[] Balance { get; set; } public uint BlockHeight { get; set; } } }
24.086957
51
0.635379
[ "MIT" ]
neo-ngd/Neo3-GUI
neo3-gui/neo3-gui/Common/Storage/SQLiteModules/AssetBalanceEntity.cs
556
C#
#region LICENSE // The contents of this file are subject to the Common Public Attribution // License Version 1.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://github.com/NiclasOlofsson/MiNET/blob/master/LICENSE. // The License is based on the Mozilla Public License Version 1.1, but Sections 14 // and 15 have been added to cover use of software over a computer network and // provide for limited attribution for the Original Developer. In addition, Exhibit A has // been modified to be consistent with Exhibit B. // // Software distributed under the License is distributed on an "AS IS" basis, // WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for // the specific language governing rights and limitations under the License. // // The Original Code is MiNET. // // The Original Developer is the Initial Developer. The Initial Developer of // the Original Code is Niclas Olofsson. // // All portions of the code written by Niclas Olofsson are Copyright (c) 2014-2017 Niclas Olofsson. // All Rights Reserved. #endregion using System.Numerics; using MiNET.Utils; using MiNET.Worlds; namespace MiNET.Blocks { public abstract class GlazedTerracotta : Block { public GlazedTerracotta(byte id) : base(id) { } public override bool PlaceBlock(Level world, Player player, BlockCoordinates blockCoordinates, BlockFace face, Vector3 faceCoords) { byte direction = player.GetDirection(); switch (direction) { case 1: Metadata = 2; break; // West case 2: Metadata = 5; break; // North case 3: Metadata = 3; break; // East case 0: Metadata = 4; break; // South } return false; } } }
29.327869
132
0.713807
[ "MPL-2.0" ]
TruDan/MiNET
src/MiNET/MiNET/Blocks/GlazedTerracotta.cs
1,789
C#
#region Copyright /*Copyright (C) 2015 Wosad Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Wosad.Common.CalculationLogger; using Wosad.Common.Entities; using Wosad.Common.Section.Interfaces; using Wosad.Common.Section.Predefined; using Wosad.Common.Section.SectionTypes; using Wosad.Steel.AISC.AISC360v10.Compression; using Wosad.Steel.AISC.Interfaces; using Wosad.Steel.AISC.Steel.Entities.Sections; using Wosad.Steel.AISC.SteelEntities.Materials; using Wosad.Steel.AISC.SteelEntities.Sections; namespace Wosad.Steel.AISC.AISC360v10.Compression { public class CompressionMemberFactory { //SteelMaterial mat public ISteelCompressionMember GetCompressionMember(ISection Shape, ISteelMaterial mat, double L_ex, double L_ey, double L_ez, bool IsRolledShape = true) { return GetCompressionMember(Shape, L_ex, L_ey, L_ez, mat.YieldStress, mat.ModulusOfElasticity, IsRolledShape); } public ISteelCompressionMember GetCompressionMember(ISection Shape, double L_ex, double L_ey, double L_ez, double F_y, double E, bool IsRolledShape = true) { string DEFAULT_EXCEPTION_STRING = "Selected shape is not supported. Select a different shape."; ISteelCompressionMember col = null; CalcLog log = new CalcLog(); SteelMaterial Material = new SteelMaterial(F_y, E); if (Shape is ISectionI) { ISectionI IShape = Shape as ISectionI; SteelSectionI SectionI = new SteelSectionI(IShape, Material); IShapeFactory IShapeFactory = new IShapeFactory(); return IShapeFactory.GetIshape(SectionI, IsRolledShape, L_ex, L_ey, L_ez, log); } else if (Shape is ISectionChannel) { ISectionChannel ChannelShape = Shape as ISectionChannel; SteelChannelSection ChannelSection = new SteelChannelSection(ChannelShape, Material); throw new Exception(DEFAULT_EXCEPTION_STRING); } else if (Shape is ISectionPipe) { ISectionPipe SectionPipe = Shape as ISectionPipe; SteelPipeSection PipeSection = new SteelPipeSection(SectionPipe, Material); ChsShapeFactory ChsFactory = new ChsShapeFactory(); return ChsFactory.GetChsShape(PipeSection, L_ex, L_ey, L_ez, log); } else if (Shape is ISectionTube) { ISectionTube TubeShape = Shape as ISectionTube; SteelRhsSection RectHSS_Section = new SteelRhsSection(TubeShape, Material); RhsShapeFactory RhsFactory = new RhsShapeFactory(); return RhsFactory.GetRhsShape(RectHSS_Section, L_ex, L_ey, L_ez, log); } else if (Shape is ISectionBox) { ISectionBox BoxShape = Shape as ISectionBox; SteelBoxSection BoxSection = new SteelBoxSection(BoxShape, Material); RhsShapeFactory RhsFactory = new RhsShapeFactory(); return RhsFactory.GetRhsShape(BoxSection, L_ex, L_ey, L_ez, log); } else if (Shape is ISectionTee) { ISectionTee TeeShape = Shape as ISectionTee; SteelTeeSection TeeSection = new SteelTeeSection(TeeShape, Material); throw new Exception(DEFAULT_EXCEPTION_STRING); } else { throw new Exception(DEFAULT_EXCEPTION_STRING); } } } }
37.026087
163
0.657116
[ "Apache-2.0" ]
Wosad/Wosad.Design
Wosad.Steel/AISC/AISC360v10/E_Compression/CompressionMemberFactory.cs
4,260
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the rds-2014-10-31.normal.json service model. */ using System; using System.Net; using Amazon.Runtime; namespace Amazon.RDS.Model { ///<summary> /// RDS exception /// </summary> #if !PCL [Serializable] #endif public class InvalidVPCNetworkStateException : AmazonRDSException { /// <summary> /// Constructs a new InvalidVPCNetworkStateException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public InvalidVPCNetworkStateException(string message) : base(message) {} /// <summary> /// Construct instance of InvalidVPCNetworkStateException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public InvalidVPCNetworkStateException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Construct instance of InvalidVPCNetworkStateException /// </summary> /// <param name="innerException"></param> public InvalidVPCNetworkStateException(Exception innerException) : base(innerException) {} /// <summary> /// Construct instance of InvalidVPCNetworkStateException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public InvalidVPCNetworkStateException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, requestId, statusCode) {} /// <summary> /// Construct instance of InvalidVPCNetworkStateException /// </summary> /// <param name="message"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public InvalidVPCNetworkStateException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, requestId, statusCode) {} #if !PCL /// <summary> /// Constructs a new instance of the InvalidVPCNetworkStateException class with serialized data. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception> protected InvalidVPCNetworkStateException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } #endif } }
43.381443
178
0.654468
[ "Apache-2.0" ]
SaschaHaertel/AmazonAWS
sdk/src/Services/RDS/Generated/Model/InvalidVPCNetworkStateException.cs
4,208
C#
using TicTacToe.Orleans; await Host.CreateDefaultBuilder(args) .UseOrleans((ctx, siloBuilder) => { // In order to support multiple hosts forming a cluster, they must listen on different ports. // Use the --InstanceId X option to launch subsequent hosts. var instanceId = ctx.Configuration.GetValue<int>("InstanceId"); siloBuilder.UseLocalhostClustering( siloPort: 11111 + instanceId, gatewayPort: 30000 + instanceId, new IPEndPoint(IPAddress.Loopback, 11111)); }).ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); webBuilder.ConfigureKestrel((ctx, kestrelOptions) => { // To avoid port conflicts, each Web server must listen on a different port. var instanceId = ctx.Configuration.GetValue<int>("InstanceId"); kestrelOptions.ListenLocalhost(5000 + instanceId); }); }) .RunConsoleAsync();
42.304348
101
0.653649
[ "Apache-2.0" ]
AhmedKhalil777/Orleans.Learning
src/TicTacToe.Orleans/TicTacToe.Orleans/Program.cs
973
C#
// Copyright © 2017 Chromely Projects. All rights reserved. // Use of this source code is governed by MIT license that can be found in the LICENSE file. namespace Chromely.Core.Host { public class WindowCustomStyle { public WindowCustomStyle(int styles, int exStyles) { WindowStyles = styles; WindowExStyles = exStyles; } public int WindowStyles { get; set; } public int WindowExStyles { get; set; } public bool IsValid() { return ((WindowStyles != 0) && (WindowExStyles != 0)); } } }
26.130435
92
0.599002
[ "MIT", "BSD-3-Clause" ]
PowerOlive/Chromely
src_5.2/Chromely.Core/Host/WindowCustomStyle.cs
604
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class EyeBlink : MonoBehaviour { public RectTransform upperBox; public RectTransform lowerBox; public float speed = 0.70f; public int blinkTimes = 3; public float closeTime = 1.0f; public bool endClosing = false; private Vector3 originalUpperPosition; private Vector3 originalLowerPosition; private Vector3 endUpper; private Vector3 endLower; private int currentBlink = 1; public enum Action { Open, Close }; void Awake() { originalUpperPosition = upperBox.position; originalLowerPosition = lowerBox.position; } void OnEnable() { StartCoroutine(blink()); } private IEnumerator blink() { yield return new WaitForSeconds(closeTime); while (currentBlink <= blinkTimes) { endUpper = originalUpperPosition; endLower = originalLowerPosition; endUpper.y += (50 * currentBlink); endLower.y -= (50 * currentBlink); // open eyelids yield return moveEyelids(endUpper, endLower, Action.Open); // check if we want to end the blink closing the eyes if (currentBlink == blinkTimes && !endClosing) { originalUpperPosition.y = Screen.height * 2; originalLowerPosition.y = -Screen.height; } // close eyelids yield return moveEyelids(originalUpperPosition, originalLowerPosition, Action.Close); currentBlink++; } } private IEnumerator moveEyelids(Vector3 upperLid, Vector3 lowerLid, Action action) { float elapsedTime = 0; while (elapsedTime < speed) { float duration = (elapsedTime / speed); if (action == Action.Open) { upperBox.position = Vector3.Lerp(originalUpperPosition, upperLid, duration); lowerBox.position = Vector3.Lerp(originalLowerPosition, lowerLid, duration); } else { upperBox.position = Vector3.Lerp(endUpper, upperLid, duration); lowerBox.position = Vector3.Lerp(endLower, lowerLid, duration); } elapsedTime += Time.deltaTime; yield return new WaitForEndOfFrame(); } } }
26.934066
97
0.593227
[ "MIT" ]
Helen1012/Capstone_Design
Assets/Works/Arim/02. Scripts/EyeBlink.cs
2,453
C#
// Adapted From Ryan Hipples https://github.com/roboryantron/Unite2017 Repository #if UNITY_EDITOR using UnityEngine; using UnityEditor; namespace JellyFish.Data.Primitive.Editor { // [CustomPropertyDrawer(typeof(StrField))] public class StringFieldDrawer : PropertyDrawer { /// <summary> /// Options to display in the popup to select constant or variable. /// </summary> private readonly string[] popupOptions = {"Use Constant", "Use Variable"}; /// <summary> Cached style to use to draw the popup button. </summary> private GUIStyle popupStyle; public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { if (popupStyle == null) { popupStyle = new GUIStyle(GUI.skin.GetStyle("PaneOptions")); popupStyle.imagePosition = ImagePosition.ImageOnly; } label = EditorGUI.BeginProperty(position, label, property); position = EditorGUI.PrefixLabel(position, label); EditorGUI.BeginChangeCheck(); // Get properties SerializedProperty useConstant = property.FindPropertyRelative("UseConstant"); SerializedProperty constantValue = property.FindPropertyRelative("ConstantValueType"); SerializedProperty variable = property.FindPropertyRelative("VariableType"); // Calculate rect for configuration button Rect buttonRect = new Rect(position); buttonRect.yMin += popupStyle.margin.top; buttonRect.width = popupStyle.fixedWidth + popupStyle.margin.right; position.xMin = buttonRect.xMax; // Store old indent level and set it to 0, the PrefixLabel takes care of it int indent = EditorGUI.indentLevel; EditorGUI.indentLevel = 0; int result = EditorGUI.Popup(buttonRect, useConstant.boolValue ? 0 : 1, popupOptions, popupStyle); useConstant.boolValue = result == 0; EditorGUI.PropertyField(position, useConstant.boolValue ? constantValue : variable, GUIContent.none); if (EditorGUI.EndChangeCheck()) property.serializedObject.ApplyModifiedProperties(); EditorGUI.indentLevel = indent; EditorGUI.EndProperty(); } } } #endif
38.292308
110
0.619124
[ "MIT" ]
Uncle-Uee/jellyfish-lite
Assets/JellyFish-Lite/Scripts/Runtime/Data/Primitives/Fields/Editor/StringFieldDrawer.cs
2,491
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 schemas-2019-12-02.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.Schemas.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Schemas.Model.Internal.MarshallTransformations { /// <summary> /// ListTagsForResource Request Marshaller /// </summary> public class ListTagsForResourceRequestMarshaller : IMarshaller<IRequest, ListTagsForResourceRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((ListTagsForResourceRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(ListTagsForResourceRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.Schemas"); request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2019-12-02"; request.HttpMethod = "GET"; if (!publicRequest.IsSetResourceArn()) throw new AmazonSchemasException("Request object does not have required field ResourceArn set"); request.AddPathResource("{resource-arn}", StringUtils.FromString(publicRequest.ResourceArn)); request.ResourcePath = "/tags/{resource-arn}"; request.MarshallerVersion = 2; return request; } private static ListTagsForResourceRequestMarshaller _instance = new ListTagsForResourceRequestMarshaller(); internal static ListTagsForResourceRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static ListTagsForResourceRequestMarshaller Instance { get { return _instance; } } } }
35.136364
153
0.660091
[ "Apache-2.0" ]
PureKrome/aws-sdk-net
sdk/src/Services/Schemas/Generated/Model/Internal/MarshallTransformations/ListTagsForResourceRequestMarshaller.cs
3,092
C#
using System; using System.IO; using System.Text; /* Originally written in 'C', this code has been converted to the C# language. * The author's copyright message is reproduced below. * All modifications from the original to C# are placed in the public domain. */ /* jsmin.c 2007-05-22 Copyright (c) 2002 Douglas Crockford (www.crockford.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace ClientDependency.Core.CompositeFiles { public class JSMin { const int EOF = -1; StringReader sr; StringWriter sw; int theA; int theB; int theLookahead = EOF; static int theX = EOF; static int theY = EOF; public static string CompressJS(string body) { return new JSMin().Minify(body); } public string Minify(string src) { StringBuilder sb = new StringBuilder(); using (sr = new StringReader(src)) { using (sw = new StringWriter(sb)) { jsmin(); } } return sb.ToString(); } /* jsmin -- Copy the input to the output, deleting the characters which are insignificant to JavaScript. Comments will be removed. Tabs will be replaced with spaces. Carriage returns will be replaced with linefeeds. Most spaces and linefeeds will be removed. */ void jsmin() { if (peek() == 0xEF) { get(); get(); get(); } theA = '\n'; action(3); while (theA != EOF) { switch (theA) { case ' ': action(isAlphanum(theB) ? 1 : 2); break; case '\n': switch (theB) { case '{': case '[': case '(': case '+': case '-': case '!': case '~': action(1); break; case ' ': action(3); break; default: action(isAlphanum(theB) ? 1 : 2); break; } break; default: switch (theB) { case ' ': action(isAlphanum(theA) ? 1 : 3); break; case '\n': switch (theA) { case '}': case ']': case ')': case '+': case '-': case '"': case '\'': case '`': action(1); break; default: action(isAlphanum(theA) ? 1 : 3); break; } break; default: action(1); break; } break; } } } /* action -- do something! What you do is determined by the argument: 1 Output A. Copy B to A. Get the next B. 2 Copy B to A. Get the next B. (Delete A). 3 Get the next B. (Delete B). action treats a string as a single character. Wow! action recognizes a regular expression if it is preceded by ( or , or =. */ void action(int d) { switch (d) { case 1: put(theA); if ( (theY == '\n' || theY == ' ') && (theA == '+' || theA == '-' || theA == '*' || theA == '/') && (theB == '+' || theB == '-' || theB == '*' || theB == '/') ) { put(theY); } goto case 2; case 2: theA = theB; if (theA == '\'' || theA == '"' || theA == '`') { for (;;) { put(theA); theA = get(); if (theA == theB) { break; } if (theA == '\\') { put(theA); theA = get(); } if (theA == EOF) { throw new Exception(string.Format("Error: JSMIN unterminated string literal: {0}\n", theA)); } } } goto case 3; case 3: theB = next(); if (theB == '/' && ( theA == '(' || theA == ',' || theA == '=' || theA == ':' || theA == '[' || theA == '!' || theA == '&' || theA == '|' || theA == '?' || theA == '+' || theA == '-' || theA == '~' || theA == '*' || theA == '/' || theA == '{' || theA == '\n' )) { put(theA); if (theA == '/' || theA == '*') { put(' '); } put(theB); for (;;) { theA = get(); if (theA == '[') { for (;;) { put(theA); theA = get(); if (theA == ']') { break; } if (theA == '\\') { put(theA); theA = get(); } if (theA == EOF) { throw new Exception(string.Format("Error: JSMIN Unterminated set in Regular Expression literal: {0}\n", theA)); } } } else if (theA == '/') { switch (peek()) { case '/': case '*': throw new Exception(string.Format("Error: JSMIN Unterminated set in Regular Expression literal: {0}\n", theA)); } break; } else if (theA == '\\') { put(theA); theA = get(); } if (theA == EOF) { throw new Exception(string.Format("Error: JSMIN Unterminated Regular Expression literal: {0}\n", theA)); } put(theA); } theB = next(); } goto default; default: break; } } /* next -- get the next character, excluding comments. peek() is used to see if a '/' is followed by a '/' or '*'. */ private int next() { int c = get(); if (c == '/') { switch (peek()) { case '/': for (;;) { c = get(); if (c <= '\n') { break; } } break; case '*': get(); while (c != ' ') { switch (get()) { case '*': var currPeek = peek(); if (currPeek == '/') { get(); c = ' '; //In one very peculiar circumstance, if the JS value is like: // val(1 /* Calendar */.toString()); // if we strip the comment out, JS will produce an error because // 1.toString() is not valid, however 1..toString() is valid and // similarly keeping the comment is valid. So we can check if the next value // is a '.' and if the current value is numeric and perform this operation. // The reason why .. works is because the JS parser cannot do 1.toString() because it // sees the '.' as a decimal if (char.IsDigit((char) theY)) { currPeek = peek(); if (currPeek == '.') { //we actually want to write another '.' return '.'; } } } break; case EOF: throw new Exception("Error: JSMIN Unterminated comment.\n"); } } break; } } //return c; theY = theX; theX = c; return c; } /* peek -- get the next character without getting it. */ int peek() { theLookahead = get(); return theLookahead; } /* get -- return the next character from stdin. Watch out for lookahead. If the character is a control character, translate it to a space or linefeed. */ int get() { int c = theLookahead; theLookahead = EOF; if (c == EOF) { c = sr.Read(); } if (c >= ' ' || c == '\n' || c == EOF) { return c; } if (c == '\r') { return '\n'; } return ' '; } void put(int c) { sw.Write((char)c); } /* isAlphanum -- return true if the character is a letter, digit, underscore, dollar sign, or non-ASCII character. */ bool isAlphanum(int c) { return ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || c == '_' || c == '$' || c == '\\' || c > 126); } } }
39.476839
152
0.29093
[ "MIT" ]
51Degrees/Dnn.Platform
DNN Platform/Components/ClientDependency/Source/CompositeFiles/JSMin.cs
14,490
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using Plugin.Bright.Serialization; using System.Collections.Generic; namespace cfg.ai { public sealed partial class MoveToTarget : ai.Task { public MoveToTarget(ByteBuf _buf) : base(_buf) { TargetActorKey = _buf.ReadString(); AcceptableRadius = _buf.ReadFloat(); } public static MoveToTarget DeserializeMoveToTarget(ByteBuf _buf) { return new ai.MoveToTarget(_buf); } public string TargetActorKey { get; private set; } public float AcceptableRadius { get; private set; } public const int ID = 514987779; public override int GetTypeId() => ID; public override void Resolve(Dictionary<string, object> _tables) { base.Resolve(_tables); } public override void TranslateText(System.Func<string, string, string> translator) { base.TranslateText(translator); } public override string ToString() { return "{ " + "Id:" + Id + "," + "NodeName:" + NodeName + "," + "Decorators:" + Plugin.Bright.Common.StringUtil.CollectionToString(Decorators) + "," + "Services:" + Plugin.Bright.Common.StringUtil.CollectionToString(Services) + "," + "IgnoreRestartSelf:" + IgnoreRestartSelf + "," + "TargetActorKey:" + TargetActorKey + "," + "AcceptableRadius:" + AcceptableRadius + "," + "}"; } } }
28.459016
94
0.576037
[ "Apache-2.0" ]
StanRuaW/AshFramework
client/Editor/AshFramework/Assets/Config/output_code/ai/MoveToTarget.cs
1,736
C#
using System; using System.Collections.Generic; using System.Text; namespace FlexibleTypes.Enumerator { /// <summary> /// A custom enumerator that allows you to use any type for the Enumeration /// </summary> /// <typeparam name="T">The type that should be used for the Enumeration</typeparam> /// <example> /// <code> /// using TupleEnum = FlexibleTypes.Enumerator.IFlexibleEnumerator<System.Tuple<string, string>>; /// using FValue = FlexibleTypes.Enumerator.IFlexibleEnumerator<System.Tuple<string, string>>.FlexibleValue; /// using Value = System.Tuple<string, string>; /// /// namespace FlexibleTypes.Tests ///{ /// internal class Language : TupleEnum /// { /// public static readonly FValue EN = new Value("English", "EN"); /// public static readonly FValue FR = new Value("French", "FR"); /// public static readonly FValue ES = new Value("Spanish", "ES"); /// } ///} /// </code> /// </example> public interface FEnum<T> { /// <summary> /// Container class for the enum value /// </summary> public class FValue { /// <summary> /// Implicitly converts <see cref="FValue"/> to <typeparamref name="T"/> /// </summary> public static implicit operator T(FValue value) { return value.Value; } /// <summary> /// Implicitly converts <typeparamref name="T"/> to <see cref="FValue"/> /// </summary> public static implicit operator FValue(T value) { return new FValue(value); } /// <!--NO DOCS--> public T Value { get; private set; } /// <summary> /// Constructs a new enum value /// </summary> public FValue(T value) => Value = value; } } }
33.180328
113
0.522727
[ "MIT" ]
MillzyDev/FlexibleTypes
FlexibleTypes/Enumerator/FEnum.cs
2,026
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. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void Extract_Vector128_Int64_1() { var test = new ExtractTest__Extract_Vector128_Int64_1(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ExtractTest__Extract_Vector128_Int64_1 { private struct DataTable { private byte[] inArray1; private GCHandle inHandle1; private ulong alignment; public DataTable(Int64[] inArray1, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int64, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Int64> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); return testStruct; } public void RunStructFldScenario(ExtractTest__Extract_Vector128_Int64_1 testClass) { var result = AdvSimd.Extract(_fld1, ElementIndex); testClass.ValidateResult(_fld1, result); } public void RunStructFldScenario_Load(ExtractTest__Extract_Vector128_Int64_1 testClass) { fixed (Vector128<Int64>* pFld1 = &_fld1) { var result = AdvSimd.Extract(AdvSimd.LoadVector128((Int64*)pFld1), ElementIndex); testClass.ValidateResult(_fld1, result); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static readonly byte ElementIndex = 1; private static Int64[] _data1 = new Int64[Op1ElementCount]; private static Vector128<Int64> _clsVar1; private Vector128<Int64> _fld1; private DataTable _dataTable; static ExtractTest__Extract_Vector128_Int64_1() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); } public ExtractTest__Extract_Vector128_Int64_1() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } _dataTable = new DataTable(_data1, LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Extract( Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr), ElementIndex ); ValidateResult(_dataTable.inArray1Ptr, result); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Extract( AdvSimd.LoadVector128((Int64*)(_dataTable.inArray1Ptr)), ElementIndex ); ValidateResult(_dataTable.inArray1Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Extract), new Type[] { typeof(Vector128<Int64>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr), ElementIndex }); ValidateResult(_dataTable.inArray1Ptr, (Int64)result); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Extract), new Type[] { typeof(Vector128<Int64>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Int64*)(_dataTable.inArray1Ptr)), ElementIndex }); ValidateResult(_dataTable.inArray1Ptr, (Int64)result); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Extract(_clsVar1, ElementIndex); ValidateResult(_clsVar1, result); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Int64>* pClsVar1 = &_clsVar1) { var result = AdvSimd.Extract(AdvSimd.LoadVector128((Int64*)pClsVar1), ElementIndex); ValidateResult(_clsVar1, result); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr); var result = AdvSimd.Extract(op1, ElementIndex); ValidateResult(op1, result); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((Int64*)(_dataTable.inArray1Ptr)); var result = AdvSimd.Extract(op1, ElementIndex); ValidateResult(op1, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ExtractTest__Extract_Vector128_Int64_1(); var result = AdvSimd.Extract(test._fld1, ElementIndex); ValidateResult(test._fld1, result); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new ExtractTest__Extract_Vector128_Int64_1(); fixed (Vector128<Int64>* pFld1 = &test._fld1) { var result = AdvSimd.Extract(AdvSimd.LoadVector128((Int64*)(pFld1)), ElementIndex); ValidateResult(test._fld1, result); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Extract(_fld1, ElementIndex); ValidateResult(_fld1, result); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Int64>* pFld1 = &_fld1) { var result = AdvSimd.Extract(AdvSimd.LoadVector128((Int64*)(pFld1)), ElementIndex); ValidateResult(_fld1, result); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Extract(test._fld1, ElementIndex); ValidateResult(test._fld1, result); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Extract( AdvSimd.LoadVector128((Int64*)&test._fld1), ElementIndex ); ValidateResult(test._fld1, result); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Int64> op1, Int64 result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1); ValidateResult(inArray1, result, method); } private void ValidateResult(void* op1, Int64 result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int64>>()); ValidateResult(inArray1, result, method); } private void ValidateResult(Int64[] firstOp, Int64 result, [CallerMemberName] string method = "") { bool succeeded = true; if (firstOp[ElementIndex] != result) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Extract)}(Vector128<Int64>, 1): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: {result}"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
35.631347
187
0.567127
[ "MIT" ]
06needhamt/runtime
src/coreclr/tests/src/JIT/HardwareIntrinsics/Arm/AdvSimd/Extract.Vector128.Int64.1.cs
16,141
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Newtonsoft.Json; namespace EF7TEST.Models { public class Customer { // Primary Key public int Id { get; set; } [DataType(DataType.EmailAddress)] public string Email { get; set; } public string Password { get; set; } [StringLength(50)] public string Name { get; set; } public DateTime RegisterOn { get; set; } // Navigation Properties [JsonIgnore] public virtual ICollection<Order> Oreders { get; set; } } }
26.807692
63
0.655667
[ "MIT" ]
boming0529/EF7Test
Models/Customer.cs
699
C#
using System; using Xamarin.Forms; using Xamarin.Forms.Xaml; [assembly: XamlCompilation(XamlCompilationOptions.Compile)] namespace PolohovaciPrvky { public partial class App : Application { public App() { InitializeComponent(); MainPage = new MainPage(); } protected override void OnStart() { // Handle when your app starts } protected override void OnSleep() { // Handle when your app sleeps } protected override void OnResume() { // Handle when your app resumes } } }
19.515152
59
0.557453
[ "MIT" ]
PetrVobornik/prednasky
Xamarin.Forms/03-Layout/PolohovaciPrvky/PolohovaciPrvky/PolohovaciPrvky/App.xaml.cs
646
C#
/* * Copyright 2014, 2015 Dominick Baier, Brock Allen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; namespace Thinktecture.IdentityServer.Core.Models { /// <summary> /// Models a refresh token. /// </summary> public class RefreshToken : ITokenMetadata { /// <summary> /// Initializes a new instance of the <see cref="RefreshToken"/> class. /// </summary> public RefreshToken() { Version = 3; } /// <summary> /// Gets the client identifier. /// </summary> /// <value> /// The client identifier. /// </value> public string ClientId { get { return AccessToken.ClientId; } } /// <summary> /// Gets or sets the creation time. /// </summary> /// <value> /// The creation time. /// </value> public DateTimeOffset CreationTime { get; set; } /// <summary> /// Gets or sets the life time. /// </summary> /// <value> /// The life time. /// </value> public int LifeTime { get; set; } /// <summary> /// Gets or sets the access token. /// </summary> /// <value> /// The access token. /// </value> public Token AccessToken { get; set; } /// <summary> /// Gets or sets the version number. /// </summary> /// <value> /// The version. /// </value> public int Version { get; set; } /// <summary> /// Gets the subject identifier. /// </summary> /// <value> /// The subject identifier. /// </value> public string SubjectId { get { return AccessToken.SubjectId; } } /// <summary> /// Gets the scopes. /// </summary> /// <value> /// The scopes. /// </value> public IEnumerable<string> Scopes { get { return AccessToken.Scopes; } } } }
27.103093
79
0.528338
[ "Apache-2.0" ]
AndersAbel/IdentityServer3
source/Core/Models/RefreshToken.cs
2,631
C#
#pragma warning disable CS1591 using Newtonsoft.Json; namespace Discord.API.Rest { [JsonObject(MemberSerialization = MemberSerialization.OptIn)] internal class GuildPruneParams { [JsonProperty("days")] public int Days { get; } [JsonProperty("include_roles")] public ulong[] IncludeRoleIds { get; } public GuildPruneParams(int days, ulong[] includeRoleIds) { Days = days; IncludeRoleIds = includeRoleIds; } } }
24.238095
65
0.626719
[ "MIT" ]
KrAyXMaximum/DNetPlus
DNetPlus/Rest/API/Rest/GuildPruneParams.cs
511
C#
using System; /* Copyright (c) Bendyline LLC. All rights reserved. Licensed under the Apache License, Version 2.0. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. */ using System.IO; namespace Bendyline.FlightSimulator.Data { public class RectangularVegetationArea : Record { private Vertex firstPoint; private Vertex secondPoint; private Guid vegetationType; public override RecordType RecordType { get { return RecordType.RectangularVegetationAreaVGRE; } set { base.RecordType = value; } } public Vertex FirstPoint { get { return this.firstPoint; } set { this.firstPoint = value; } } public Vertex SecondPoint { get { return this.secondPoint; } set { this.secondPoint = value; } } public Guid VegetationType { get { return this.vegetationType; } set { this.vegetationType = value; } } public override int NodeSize { get { return 32; } } public RectangularVegetationArea() { this.firstPoint = new Vertex(-0.1f, -0.1f); this.secondPoint = new Vertex(0.1f, -0.1f); } public override void Load(Stream fs, int sectionSize) { this.vegetationType = ReadGuid(fs); this.firstPoint = new Vertex(); this.firstPoint.X = ReadFloat(fs); this.firstPoint.Y = ReadFloat(fs); this.secondPoint = new Vertex(); this.secondPoint.X = ReadFloat(fs); this.secondPoint.Y = ReadFloat(fs); } public override void Save(Stream s) { base.Save(s); this.WriteGuid(s, this.vegetationType); this.WriteFloat(s, this.firstPoint.X); this.WriteFloat(s, this.firstPoint.Y); this.WriteFloat(s, this.secondPoint.X); this.WriteFloat(s, this.secondPoint.Y); } } }
21.876106
100
0.476133
[ "Apache-2.0" ]
bendyline/FlightSimData
Data/RectangularVegetationArea.cs
2,474
C#
using System.Collections.Generic; using IOF.Models; namespace IOF { public interface IAccountRepository { Account Single(int clientId, int? accountId); /// <summary> /// Get accounts the user has added to the IOF system. /// </summary> IEnumerable<Account> GetActiveAccounts(int clientId); /// <summary> /// Get all accounts the user is currently assigned to and are available to be added to the IOF system. /// </summary> IEnumerable<Account> GetAvailableAccounts(int clientId); /// <summary> /// Get all accounts that any user has added to the IOF system. /// </summary> IEnumerable<Account> GetAllAccounts(); string GetShortCode(int? accountId); Account AddOrUpdate(int clientId, int accountId); void Delete(int clientId, int accountId); } }
27.90625
111
0.631579
[ "MIT" ]
lurienanofab/iof
IOF/IAccountRepository.cs
895
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using System.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 Azure Powershell")] [assembly: AssemblyCompany(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCompany)] [assembly: AssemblyProduct(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyProduct)] [assembly: AssemblyCopyright(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCopyright)] // 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)] [assembly: CLSCompliant(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.0")] [assembly: AssemblyVersion("2.12.0")] [assembly: AssemblyFileVersion("2.12.0")]
46.717391
104
0.695207
[ "MIT" ]
SimonWahlin/azure-powershell
src/RecoveryServices/RecoveryServices.Backup.Helpers/Properties/AssemblyInfo.cs
2,104
C#
namespace SIM.Adapters.WebServer { using System; using System.Linq; using Microsoft.Web.Administration; using Sitecore.Diagnostics.Base; using JetBrains.Annotations; using Sitecore.Diagnostics.Logging; using SIM.Extensions; #region #endregion public static class WebServerManager { #region Public Methods [NotNull] public static WebServerContext CreateContext() { return new WebServerContext(); } public static void DeleteWebsite([NotNull] long id) { Log.Info($"Deleting website {id}"); using (WebServerContext context = CreateContext()) { Site site = context.Sites.SingleOrDefault(s => s.Id == id); if (site != null) { DeleteWebsite(context, site); } } } [NotNull] public static string GetWebRootPath([NotNull] Site site) { Assert.ArgumentNotNull(site, nameof(site)); Application apps = site.Applications["/"]; if (apps != null) { VirtualDirectory vdirs = apps.VirtualDirectories["/"]; if (vdirs != null) { ConfigurationAttribute phpath = vdirs.Attributes["physicalPath"]; if (phpath != null) { var value = (string)phpath.Value; if (!string.IsNullOrEmpty(value)) { return value; } } } } throw new Exception($"IIS website {site.Id} seems to be corrupted or misconfigured"); } public static bool HostBindingExists([NotNull] string host) { Assert.ArgumentNotNull(host, nameof(host)); bool result; using (WebServerContext context = CreateContext()) { result = context.Sites.Any(site => site.Bindings.Any(binding => binding.Host.EqualsIgnoreCase(host))); } return result; } public static bool AddHostBinding([NotNull] string siteName, [NotNull] BindingInfo binding) { Assert.ArgumentNotNull(siteName, nameof(siteName)); Assert.ArgumentNotNull(binding, nameof(binding)); using (WebServerContext context = CreateContext()) { Site siteInfo = context.Sites.FirstOrDefault(site => site.Name.EqualsIgnoreCase(siteName)); if (HostBindingExists(binding.Host) || siteInfo == null) { return false; } var bindingInformation = $"{binding.IP}:{binding.Port}:{binding.Host}"; siteInfo.Bindings.Add(bindingInformation, binding.Protocol); context.CommitChanges(); } return true; } public static bool WebsiteExists([NotNull] string name) { Assert.ArgumentNotNull(name, nameof(name)); bool v; using (WebServerContext context = CreateContext()) { v = context.Sites.Any(s => s.Name.EqualsIgnoreCase(name)); } return v; } #endregion #region Methods private static void DeleteWebsite([NotNull] WebServerContext context, [NotNull] Site site) { Assert.ArgumentNotNull(context, nameof(context)); Assert.ArgumentNotNull(site, nameof(site)); foreach (Application application in site.Applications) { var applicationPoolName = application.ApplicationPoolName; ApplicationPool appplicationPool = context.ApplicationPools[applicationPoolName]; // Application is used only in the current website or isn't used at all if (appplicationPool != null && context.Sites.Count(s => s.ApplicationDefaults.ApplicationPoolName.EqualsIgnoreCase(applicationPoolName)) <= 1) { context.ApplicationPools.Remove(appplicationPool); } } context.Sites.Remove(site); context.CommitChanges(); } #endregion public sealed class WebServerContext : IDisposable { [NotNull] private ServerManager ServerManager { get; } = new ServerManager(); [NotNull] public ApplicationPoolCollection ApplicationPools => ServerManager.ApplicationPools.IsNotNull(); [NotNull] public SiteCollection Sites => ServerManager.Sites.IsNotNull(); public void CommitChanges() { ServerManager.CommitChanges(); } public void Dispose() { ServerManager.Dispose(); } } } }
26.895062
151
0.620611
[ "MIT" ]
AlenPelin/SimEx
src/SIM.Adapters/WebServer/WebServerManager.cs
4,359
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #nullable disable using System; using Microsoft.AspNetCore.Mvc.Razor; namespace Microsoft.AspNetCore.Mvc.RazorPages; public abstract class Page : RazorPageBase { public PageContext PageContext { get; set; } public virtual RedirectResult Redirect(string url) => throw new NotImplementedException(); public override void EnsureRenderedBodyOrSections() { } public override void BeginContext(int position, int length, bool isLiteral) { } public override void EndContext() { } public virtual bool TryValidateModel(object model) => throw new NotImplementedException(); public virtual bool TryValidateModel(object model, string prefix) => throw new NotImplementedException(); }
25.647059
109
0.743119
[ "MIT" ]
dotnet/razor-compiler
src/test/Microsoft.AspNetCore.Razor.Test.MvcShim.Version2_X/Microsoft.AspNetCore.Mvc.RazorPages/Page.cs
874
C#
using System; using System.Threading; using System.Threading.Tasks; using System.Reflection; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using SampleControl.Entities; using Uno.UI.Samples.Controls; using Uno.UI.Samples.Entities; using System.Runtime.InteropServices.WindowsRuntime; using System.Globalization; using Windows.UI.Xaml.Data; using Windows.ApplicationModel.Core; using Windows.UI.Core; using Windows.Storage; using Uno.Extensions; using Uno.Logging; using Microsoft.Extensions.Logging; using Windows.UI.Xaml; using System.IO; using Uno.Disposables; using System.ComponentModel; using System.Windows.Input; using Uno.UI.Common; #if XAMARIN || NETSTANDARD2_0 using Windows.UI.Xaml.Controls; #else using Windows.Graphics.Imaging; using Windows.Graphics.Display; using Windows.UI.Xaml.Media; using Windows.UI; using Windows.UI.Xaml.Controls; #endif namespace SampleControl.Presentation { public partial class SampleChooserViewModel : INotifyPropertyChanged { private void InitializeCommands() { #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed LogViewDumpCommand = new DelegateCommand(() => LogViewDump(CancellationToken.None)); ShowPreviousSectionCommand = new DelegateCommand(() => ShowPreviousSection(CancellationToken.None)); ShowNewSectionCommand = new DelegateCommand<string>(section => ShowNewSection(CancellationToken.None, ConvertSectionEnum(section))); ToggleFavoriteCommand = new DelegateCommand<SampleChooserContent>(sample => ToggleFavorite(CancellationToken.None, sample)); RecordAllTestsCommandCommand = new DelegateCommand(() => RecordAllTests(CancellationToken.None)); LoadPreviousTestCommand = new DelegateCommand(() => LoadPreviousTest(CancellationToken.None)) { CanExecuteEnabled = false }; ReloadCurrentTestCommand = new DelegateCommand(() => ReloadCurrentTest(CancellationToken.None)) { CanExecuteEnabled = false }; LoadNextTestCommand = new DelegateCommand(() => LoadNextTest(CancellationToken.None)) { CanExecuteEnabled = false }; ShowTestInformationCommand = new DelegateCommand(() => ShowTestInformation(CancellationToken.None)) { CanExecuteEnabled = false }; #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed } public ICommand LogViewDumpCommand { get; private set; } public ICommand ShowPreviousSectionCommand { get; private set; } public ICommand ShowNewSectionCommand { get; private set; } public ICommand ToggleFavoriteCommand { get; private set; } public ICommand RecordAllTestsCommandCommand { get; private set; } public ICommand LoadPreviousTestCommand { get; private set; } public ICommand ReloadCurrentTestCommand { get; private set; } public ICommand LoadNextTestCommand { get; private set; } public ICommand ShowTestInformationCommand { get; private set; } } }
43.202899
138
0.800067
[ "Apache-2.0" ]
AzureMentor/uno
src/SamplesApp/SamplesApp.UnitTests.Shared/Controls/UITests/Presentation/SampleChooserViewMode.Commands.cs
2,983
C#
using FluentAssertions; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using Xunit; namespace Lsp.Tests.Models { public class DocumentOnTypeFormattingRegistrationOptionsTests { [Theory] [JsonFixture] public void SimpleTest(string expected) { var model = new DocumentOnTypeFormattingRegistrationOptions { DocumentSelector = new DocumentSelector( new DocumentFilter { Language = "csharp" } ), FirstTriggerCharacter = "1", MoreTriggerCharacter = new[] { "1", "2" } }; var result = Fixture.SerializeObject(model); result.Should().Be(expected); var deresult = new Serializer(ClientVersion.Lsp3).DeserializeObject<DocumentOnTypeFormattingRegistrationOptions>(expected); deresult.Should().BeEquivalentTo(model); } } }
33.818182
135
0.632616
[ "MIT" ]
kamit9171/csharp-language-server-protocol
test/Lsp.Tests/Models/DocumentOnTypeFormattingRegistrationOptionsTests.cs
1,116
C#
namespace Foundation.Build.VersionControl.Vault { public class VaultResult { /// <summary> /// Gets or sets a value indicating whether the vault request was a success. /// </summary> /// <value> /// <c>true</c> if the vault request was successful; otherwise, <c>false</c>. /// </value> public bool Success { get; set; } public VaultFolder Folder { get; set; } } }
30.466667
88
0.551422
[ "Apache-2.0" ]
DavidMoore/Foundation
Code/Foundation/Build/VersionControl/Vault/VaultResult.cs
459
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.ComponentModel; using Pulumi; namespace Pulumi.AzureNative.Authorization { /// <summary> /// The recurrence type : weekly, monthly, etc. /// </summary> [EnumType] public readonly struct AccessReviewRecurrencePatternType : IEquatable<AccessReviewRecurrencePatternType> { private readonly string _value; private AccessReviewRecurrencePatternType(string value) { _value = value ?? throw new ArgumentNullException(nameof(value)); } public static AccessReviewRecurrencePatternType Weekly { get; } = new AccessReviewRecurrencePatternType("weekly"); public static AccessReviewRecurrencePatternType AbsoluteMonthly { get; } = new AccessReviewRecurrencePatternType("absoluteMonthly"); public static bool operator ==(AccessReviewRecurrencePatternType left, AccessReviewRecurrencePatternType right) => left.Equals(right); public static bool operator !=(AccessReviewRecurrencePatternType left, AccessReviewRecurrencePatternType right) => !left.Equals(right); public static explicit operator string(AccessReviewRecurrencePatternType value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is AccessReviewRecurrencePatternType other && Equals(other); public bool Equals(AccessReviewRecurrencePatternType other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode() ?? 0; public override string ToString() => _value; } /// <summary> /// The recurrence range type. The possible values are: endDate, noEnd, numbered. /// </summary> [EnumType] public readonly struct AccessReviewRecurrenceRangeType : IEquatable<AccessReviewRecurrenceRangeType> { private readonly string _value; private AccessReviewRecurrenceRangeType(string value) { _value = value ?? throw new ArgumentNullException(nameof(value)); } public static AccessReviewRecurrenceRangeType EndDate { get; } = new AccessReviewRecurrenceRangeType("endDate"); public static AccessReviewRecurrenceRangeType NoEnd { get; } = new AccessReviewRecurrenceRangeType("noEnd"); public static AccessReviewRecurrenceRangeType Numbered { get; } = new AccessReviewRecurrenceRangeType("numbered"); public static bool operator ==(AccessReviewRecurrenceRangeType left, AccessReviewRecurrenceRangeType right) => left.Equals(right); public static bool operator !=(AccessReviewRecurrenceRangeType left, AccessReviewRecurrenceRangeType right) => !left.Equals(right); public static explicit operator string(AccessReviewRecurrenceRangeType value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is AccessReviewRecurrenceRangeType other && Equals(other); public bool Equals(AccessReviewRecurrenceRangeType other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode() ?? 0; public override string ToString() => _value; } /// <summary> /// This specifies the behavior for the autoReview feature when an access review completes. /// </summary> [EnumType] public readonly struct DefaultDecisionType : IEquatable<DefaultDecisionType> { private readonly string _value; private DefaultDecisionType(string value) { _value = value ?? throw new ArgumentNullException(nameof(value)); } public static DefaultDecisionType Approve { get; } = new DefaultDecisionType("Approve"); public static DefaultDecisionType Deny { get; } = new DefaultDecisionType("Deny"); public static DefaultDecisionType Recommendation { get; } = new DefaultDecisionType("Recommendation"); public static bool operator ==(DefaultDecisionType left, DefaultDecisionType right) => left.Equals(right); public static bool operator !=(DefaultDecisionType left, DefaultDecisionType right) => !left.Equals(right); public static explicit operator string(DefaultDecisionType value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is DefaultDecisionType other && Equals(other); public bool Equals(DefaultDecisionType other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode() ?? 0; public override string ToString() => _value; } /// <summary> /// The policy assignment enforcement mode. Possible values are Default and DoNotEnforce. /// </summary> [EnumType] public readonly struct EnforcementMode : IEquatable<EnforcementMode> { private readonly string _value; private EnforcementMode(string value) { _value = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The policy effect is enforced during resource creation or update. /// </summary> public static EnforcementMode Default { get; } = new EnforcementMode("Default"); /// <summary> /// The policy effect is not enforced during resource creation or update. /// </summary> public static EnforcementMode DoNotEnforce { get; } = new EnforcementMode("DoNotEnforce"); public static bool operator ==(EnforcementMode left, EnforcementMode right) => left.Equals(right); public static bool operator !=(EnforcementMode left, EnforcementMode right) => !left.Equals(right); public static explicit operator string(EnforcementMode value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is EnforcementMode other && Equals(other); public bool Equals(EnforcementMode other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode() ?? 0; public override string ToString() => _value; } /// <summary> /// The policy exemption category. Possible values are Waiver and Mitigated. /// </summary> [EnumType] public readonly struct ExemptionCategory : IEquatable<ExemptionCategory> { private readonly string _value; private ExemptionCategory(string value) { _value = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// This category of exemptions usually means the scope is not applicable for the policy. /// </summary> public static ExemptionCategory Waiver { get; } = new ExemptionCategory("Waiver"); /// <summary> /// This category of exemptions usually means the mitigation actions have been applied to the scope. /// </summary> public static ExemptionCategory Mitigated { get; } = new ExemptionCategory("Mitigated"); public static bool operator ==(ExemptionCategory left, ExemptionCategory right) => left.Equals(right); public static bool operator !=(ExemptionCategory left, ExemptionCategory right) => !left.Equals(right); public static explicit operator string(ExemptionCategory value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is ExemptionCategory other && Equals(other); public bool Equals(ExemptionCategory other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode() ?? 0; public override string ToString() => _value; } /// <summary> /// The level of the lock. Possible values are: NotSpecified, CanNotDelete, ReadOnly. CanNotDelete means authorized users are able to read and modify the resources, but not delete. ReadOnly means authorized users can only read from a resource, but they can't modify or delete it. /// </summary> [EnumType] public readonly struct LockLevel : IEquatable<LockLevel> { private readonly string _value; private LockLevel(string value) { _value = value ?? throw new ArgumentNullException(nameof(value)); } public static LockLevel NotSpecified { get; } = new LockLevel("NotSpecified"); public static LockLevel CanNotDelete { get; } = new LockLevel("CanNotDelete"); public static LockLevel ReadOnly { get; } = new LockLevel("ReadOnly"); public static bool operator ==(LockLevel left, LockLevel right) => left.Equals(right); public static bool operator !=(LockLevel left, LockLevel right) => !left.Equals(right); public static explicit operator string(LockLevel value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is LockLevel other && Equals(other); public bool Equals(LockLevel other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode() ?? 0; public override string ToString() => _value; } /// <summary> /// The data type of the parameter. /// </summary> [EnumType] public readonly struct ParameterType : IEquatable<ParameterType> { private readonly string _value; private ParameterType(string value) { _value = value ?? throw new ArgumentNullException(nameof(value)); } public static ParameterType String { get; } = new ParameterType("String"); public static ParameterType Array { get; } = new ParameterType("Array"); public static ParameterType Object { get; } = new ParameterType("Object"); public static ParameterType Boolean { get; } = new ParameterType("Boolean"); public static ParameterType Integer { get; } = new ParameterType("Integer"); public static ParameterType Float { get; } = new ParameterType("Float"); public static ParameterType DateTime { get; } = new ParameterType("DateTime"); public static bool operator ==(ParameterType left, ParameterType right) => left.Equals(right); public static bool operator !=(ParameterType left, ParameterType right) => !left.Equals(right); public static explicit operator string(ParameterType value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is ParameterType other && Equals(other); public bool Equals(ParameterType other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode() ?? 0; public override string ToString() => _value; } /// <summary> /// The type of policy definition. Possible values are NotSpecified, BuiltIn, Custom, and Static. /// </summary> [EnumType] public readonly struct PolicyType : IEquatable<PolicyType> { private readonly string _value; private PolicyType(string value) { _value = value ?? throw new ArgumentNullException(nameof(value)); } public static PolicyType NotSpecified { get; } = new PolicyType("NotSpecified"); public static PolicyType BuiltIn { get; } = new PolicyType("BuiltIn"); public static PolicyType Custom { get; } = new PolicyType("Custom"); public static PolicyType Static { get; } = new PolicyType("Static"); public static bool operator ==(PolicyType left, PolicyType right) => left.Equals(right); public static bool operator !=(PolicyType left, PolicyType right) => !left.Equals(right); public static explicit operator string(PolicyType value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is PolicyType other && Equals(other); public bool Equals(PolicyType other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode() ?? 0; public override string ToString() => _value; } /// <summary> /// The principal type of the assigned principal ID. /// </summary> [EnumType] public readonly struct PrincipalType : IEquatable<PrincipalType> { private readonly string _value; private PrincipalType(string value) { _value = value ?? throw new ArgumentNullException(nameof(value)); } public static PrincipalType User { get; } = new PrincipalType("User"); public static PrincipalType Group { get; } = new PrincipalType("Group"); public static PrincipalType ServicePrincipal { get; } = new PrincipalType("ServicePrincipal"); public static PrincipalType ForeignGroup { get; } = new PrincipalType("ForeignGroup"); public static bool operator ==(PrincipalType left, PrincipalType right) => left.Equals(right); public static bool operator !=(PrincipalType left, PrincipalType right) => !left.Equals(right); public static explicit operator string(PrincipalType value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is PrincipalType other && Equals(other); public bool Equals(PrincipalType other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode() ?? 0; public override string ToString() => _value; } /// <summary> /// The identity type. This is the only required field when adding a system assigned identity to a resource. /// </summary> [EnumType] public readonly struct ResourceIdentityType : IEquatable<ResourceIdentityType> { private readonly string _value; private ResourceIdentityType(string value) { _value = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// Indicates that a system assigned identity is associated with the resource. /// </summary> public static ResourceIdentityType SystemAssigned { get; } = new ResourceIdentityType("SystemAssigned"); /// <summary> /// Indicates that no identity is associated with the resource or that the existing identity should be removed. /// </summary> public static ResourceIdentityType None { get; } = new ResourceIdentityType("None"); public static bool operator ==(ResourceIdentityType left, ResourceIdentityType right) => left.Equals(right); public static bool operator !=(ResourceIdentityType left, ResourceIdentityType right) => !left.Equals(right); public static explicit operator string(ResourceIdentityType value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is ResourceIdentityType other && Equals(other); public bool Equals(ResourceIdentityType other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode() ?? 0; public override string ToString() => _value; } }
46.38
283
0.690877
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Authorization/Enums.cs
16,233
C#
namespace Lykke.Service.GoogleAnalyticsWrapper.Core.Domain.GaTraffic { public interface IGaTraffic { string ClientId { get; } string Source { get; } string Medium { get; } string Campaign { get; } string Keyword { get; } string Content { get; } } }
23.846154
69
0.590323
[ "MIT" ]
JTOne123/Lykke.Service.GoogleAnalyticsWrapper
src/Lykke.Service.GoogleAnalyticsWrapper.Core/Domain/GaTraffic/IGaTraffic.cs
312
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SummerBoot.Feign { [AttributeUsage(AttributeTargets.Method,Inherited = true,AllowMultiple = false)] public abstract class HttpMappingAttribute:Attribute { public string Value { get; } protected HttpMappingAttribute(string value) { Value = value; } } }
22.210526
84
0.684834
[ "MIT" ]
TripleView/SummerBoot
SummerBoot/Feign/HttpMappingAttribute.cs
424
C#
#region License /* Copyright (c) 2006 Leslie Sanford * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion #region Contact /* * Leslie Sanford * Email: jabberdabber@hotmail.com */ #endregion using System; using System.Collections; using System.Collections.Generic; namespace Sanford.StateMachineToolkit { public abstract partial class StateMachine<TState, TEvent, TArgs> { /// <summary> /// The SubstateCollection class represents a collection of substates. /// Each <see cref="State"/> has a <see cref="State.Substates"/> /// property of the SubstateCollection type. /// Substates are added and removed to a <see cref="State"/> via this property.<para/> /// Substates are not represented by their own class. The <see cref="State"/> class /// performs double duty, playing the role of substates and superstates when necessary. /// Whether or not a <see cref="State"/> is a substate depends on whether or not /// it has been added to another State's <see cref="State.Substates"/> collection. /// And whether or not a State is a superstate depends on whether or not any States have /// been added to its <see cref="State.Substates"/> collection.<para/> /// There are some restrictions on which States can be added as substates to another <see cref="State"/>. /// The most obvious one is that a <see cref="State"/> cannot be added to its own /// <see cref="State.Substates"/> collection; /// a <see cref="State"/> cannot be a substate to itself. /// Also, a <see cref="State"/> can only be the direct substate of one other /// <see cref="State"/>; you cannot add a <see cref="State"/> to the /// <see cref="State.Substates"/> collection of more than one <see cref="State"/>. /// </summary> private sealed class SubstateCollection : IEnumerable<State> { #region SubstateCollection Members #region Fields // The owner of the collection. The States in the collection are // substates to this State. private readonly State m_owner; // The collection of substates. private readonly List<State> m_substates = new List<State>(); #endregion #region Construction /// <summary> /// Initializes a new instance of the SubstateCollection with the /// specified owner. /// </summary> /// <param name="owner"> /// The owner of the collection. /// </param> public SubstateCollection(State owner) { m_owner = owner; } #endregion #region Methods /// <summary> /// Adds the specified State to the collection. /// </summary> /// <param name="substate"> /// The State to add to the collection. /// </param> public void Add(State substate) { #region Preconditions if (m_owner == substate) { throw new ArgumentException( "State cannot be a substate to itself."); } if (m_substates.Contains(substate)) { throw new ArgumentException( "State is already a substate to this state."); } if (substate.Superstate != null) { throw new ArgumentException( "State is already a substate to another State."); } #endregion substate.Superstate = m_owner; m_substates.Add(substate); } /// <summary> /// Removes the specified State from the collection. /// </summary> /// <param name="substate"> /// The State to remove from the collection. /// </param> public void Remove(State substate) { if (!m_substates.Contains(substate)) return; substate.Superstate = null; m_substates.Remove(substate); if (m_owner.InitialState == substate) { m_owner.InitialState = null; } } #endregion #endregion #region IEnumerable Members /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{State}"/> that can be used to iterate through the collection. /// </returns> public IEnumerator<State> GetEnumerator() { return m_substates.GetEnumerator(); } #endregion IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Clear() { foreach (State substate in m_substates) { substate.Superstate = null; } m_substates.Clear(); m_owner.InitialState = null; } } } }
37.022222
115
0.546819
[ "Apache-2.0" ]
OmerMor/StateMachineToolkit
src/StateMachineToolkit/SubstateCollection.cs
6,664
C#
//----------------------------------------------------------------------- // <copyright file="MatchBuilderSignatureTests.cs" company="Akka.NET Project"> // Copyright (C) 2009-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using Akka.Tools.MatchHandler; using Xunit; namespace Akka.Tests.MatchHandler { public class MatchBuilderSignatureTests { [Fact] public void GetHashCode_should_return_same_value_for_empty_and_null_signatures() { var nullSignature = new MatchBuilderSignature(null); var emptySignature = new MatchBuilderSignature(new object[0]); Assert.Equal(nullSignature.GetHashCode(), emptySignature.GetHashCode()); } [Fact] public void GetHashCode_should_be_same_for_different_instances_containing_same_1_element() { var item = new object(); var signature1 = new MatchBuilderSignature(new[] { item }); var signature2 = new MatchBuilderSignature(new[] { item }); Assert.Equal(signature1.GetHashCode(), signature2.GetHashCode()); } [Fact] public void GetHashCode_should_be_same_for_different_instances_containing_same_elements() { var item1 = new object(); var item2 = new object(); var item3 = new object(); var item4 = new object(); var signature1 = new MatchBuilderSignature(new[] { item1, item2, item3, item4 }); var signature2 = new MatchBuilderSignature(new[] { item1, item2, item3, item4 }); Assert.Equal(signature1.GetHashCode(), signature2.GetHashCode()); } [Fact] public void GetHashCode_should_be_different_when_elements_differs() { var item1 = new object(); var item2 = new object(); var item3 = new object(); var item4 = new object(); var signature1 = new MatchBuilderSignature(new[] { item1, item2, item3, item4 }); var signature2 = new MatchBuilderSignature(new[] { item4, item2, item3, item4 }); Assert.NotEqual(signature1.GetHashCode(), signature2.GetHashCode()); } [Fact] public void GetHashCode_should_be_different_when_order_differs() { var item1 = new object(); var item2 = new object(); var item3 = new object(); var item4 = new object(); var signature1 = new MatchBuilderSignature(new[] { item1, item2, item3, item4 }); var signature2 = new MatchBuilderSignature(new[] { item4, item3, item2, item1 }); Assert.NotEqual(signature1.GetHashCode(), signature2.GetHashCode()); } [Fact] public void GetHashCode_should_be_different_when_same_elements_but_fewer() { var item1 = new object(); var item2 = new object(); var item3 = new object(); var item4 = new object(); var signature1 = new MatchBuilderSignature(new[] { item1, item2, item3, item4 }); var signature2 = new MatchBuilderSignature(new[] { item1, item2 }); Assert.NotEqual(signature1.GetHashCode(), signature2.GetHashCode()); } [Fact] public void Equals_with_null_should_be_false() { var signature = new MatchBuilderSignature(new object[0]); Assert.False(signature.Equals((object)null)); Assert.False(signature.Equals(null)); } [Fact] public void Equals_with_same_should_be_true() { var signature = new MatchBuilderSignature(new object[0]); Assert.True(signature.Equals((object)signature)); Assert.True(signature.Equals(signature)); } [Fact] public void Equals_with_different_type_should_be_false() { var signature = new MatchBuilderSignature(new object[0]); Assert.False(signature.Equals(new object())); } [Fact] public void Equals_with_two_null_element_signatures_should_be_true() { var signature1 = new MatchBuilderSignature(null); var signature2 = new MatchBuilderSignature(null); Assert.True(signature1.Equals(signature2)); } [Fact] public void Equals_with_one_null_element_signature_and_one_empty_element_signature_should_be_true() { var signature1 = new MatchBuilderSignature(null); var signature2 = new MatchBuilderSignature(new object[0]); Assert.True(signature1.Equals(signature2)); Assert.True(signature2.Equals(signature1)); } [Fact] public void Equals_with_one_null_element_signature_and_one_element_signature_should_be_false() { var signature1 = new MatchBuilderSignature(null); var signature2 = new MatchBuilderSignature(new object[] { 4711 }); Assert.False(signature1.Equals(signature2)); Assert.False(signature2.Equals(signature1)); } [Fact] public void Equals_with_same_elements_in_signature_should_be_true() { var obj = new object(); var signature1 = new MatchBuilderSignature(new object[] { 4711, "42", obj }); var signature2 = new MatchBuilderSignature(new object[] { 4711, "42", obj }); Assert.True(signature1.Equals(signature2)); Assert.True(signature2.Equals(signature1)); } [Fact] public void Equals_with_same_elements_in_signature_but_fewer_in_one_should_be_false() { var signature1 = new MatchBuilderSignature(new object[] { 4711, "42", new object() }); var signature2 = new MatchBuilderSignature(new object[] { 4711, "42" }); Assert.False(signature1.Equals(signature2)); Assert.False(signature2.Equals(signature1)); } } }
39.954545
107
0.605396
[ "Apache-2.0" ]
Flubik/akka.net
src/core/Akka.Tests/MatchHandler/MatchBuilderSignatureTests.cs
6,155
C#
using System; using System.Collections.Generic; namespace Application.Common.Interfaces { public interface ICallContext { Guid CorrelationId { get; set; } string FunctionName { get; set; } string AuthenticationType { get; set; } IDictionary<string, string> AdditionalProperties { get; } bool UserRequiresAuthorization { get; set; } string UserBearerAuthorizationToken { get; set; } int UserId { get; set; } string Username { get; set; } string UserAccountXAddress { get; set; } string UserAccountSecret { get; set; } string UserAccountClassicAddress { get; set; } string UserAccountAddress { get; set; } } }
26.740741
65
0.641274
[ "MIT" ]
mecvillarina/Vider
src/backend/Application/Common/Interfaces/ICallContext.cs
722
C#
using System; using System.Xml.Serialization; using System.Collections.Generic; namespace Aop.Api.Response { /// <summary> /// KoubeiContentContentstatusModifyResponse. /// </summary> public class KoubeiContentContentstatusModifyResponse : AopResponse { /// <summary> /// 口碑内容的唯一id /// </summary> [XmlArray("data")] [XmlArrayItem("string")] public List<string> Data { get; set; } /// <summary> /// 全链路唯一id,由服务系统提供 /// </summary> [XmlElement("trace_id")] public string TraceId { get; set; } } }
24.346154
72
0.562401
[ "Apache-2.0" ]
554393109/alipay-sdk-net-all
AlipaySDKNet.Standard/Response/KoubeiContentContentstatusModifyResponse.cs
671
C#
using System; using System.Collections.Generic; using System.Text; namespace MilitaryElite.IO.Contracts { public interface IReader { string ReadLine(); } }
14.833333
36
0.696629
[ "MIT" ]
StelaKaneva/Csharp-OOP
InterfacesAndAbstraction/Exercise/MilitaryElite/MilitaryElite/MilitaryElite/IO/Contracts/IReader.cs
180
C#
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using P01_StudentSystem.Data.Models; using System; using System.Collections.Generic; using System.Text; namespace P01_StudentSystem.Data.Configurations { public class HomeworkConfiguration : IEntityTypeConfiguration<Homework> { public void Configure(EntityTypeBuilder<Homework> homework) { homework.HasKey(h => h.HomeworkId); homework.Property(h => h.Content) .IsRequired(true) .IsUnicode(false); homework.Property(h => h.SubmissionTime) .IsRequired(true); homework .HasOne(h => h.Student) .WithMany(s => s.HomeworkSubmissions) .HasForeignKey(h => h.StudentId) .OnDelete(DeleteBehavior.Restrict); homework .HasOne(h => h.Course) .WithMany(c => c.HomeworkSubmissions) .HasForeignKey(h => h.CourseId) .OnDelete(DeleteBehavior.Restrict); } } }
29.263158
75
0.597122
[ "MIT" ]
DeyanDanailov/EntityFrameworkCore
EntityRelations/P01_StudentSystem/Data/Configurations/HomeworkConfiguration.cs
1,114
C#
/* * Copyright (c) 2008, DIaLOGIKa * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of DIaLOGIKa nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY DIaLOGIKa ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL DIaLOGIKa BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Text; using DIaLOGIKa.b2xtranslator.StructuredStorage.Common; namespace DIaLOGIKa.b2xtranslator.StructuredStorage.Writer { /// <summary> /// Abstract class of a Fat in a compound file /// Author: math /// </summary> abstract class AbstractFat { protected List<UInt32> _entries = new List<UInt32>(); protected UInt32 _currentEntry = 0; protected StructuredStorageContext _context; /// <summary> /// Constructor /// <param name="context">the current context</param> /// </summary> protected AbstractFat(StructuredStorageContext context) { _context = context; } /// <summary> /// Write a chain to the fat. /// </summary> /// <param name="entryCount">number of entries in the chain</param> /// <returns></returns> internal UInt32 writeChain(UInt32 entryCount) { if (entryCount == 0) { return SectorId.FREESECT; } UInt32 startSector = _currentEntry; for (int i = 0; i < entryCount - 1; i++) { _currentEntry++; _entries.Add(_currentEntry); } _currentEntry++; _entries.Add(SectorId.ENDOFCHAIN); return startSector; } abstract internal void write(); } }
35.193182
81
0.637068
[ "BSD-3-Clause" ]
datadiode/B2XTranslator
src/Common/StructuredStorage/Writer/AbstractFat.cs
3,097
C#
namespace SFA.DAS.ForecastingTool.Core.Models { public class Apprenticeship { public string Code { get; set; } public string Name { get; set; } public int Price { get; set; } public int Duration { get; set; } } }
25.6
45
0.59375
[ "MIT" ]
SkillsFundingAgency/das-estimate-apprenticeship-funding
src/SFA.DAS.ForecastingTool.Core/Models/Standard.cs
256
C#
// ***************************************************************************** // BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE) // © Component Factory Pty Ltd, 2006 - 2016, All rights reserved. // The software and associated documentation supplied hereunder are the // proprietary information of Component Factory Pty Ltd, 13 Swallows Close, // Mornington, Vic 3931, Australia and are supplied subject to license terms. // // Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.490) // Version 5.490.0.0 www.ComponentFactory.com // ***************************************************************************** using System.Drawing; using System.ComponentModel; namespace ComponentFactory.Krypton.Toolkit { /// <summary> /// Storage for drag and drop values. /// </summary> public class PaletteDragDrop : Storage, IPaletteDragDrop { #region Instance Fields private IPalette _inherit; private PaletteDragFeedback _feedback; private Color _solidBack; private Color _solidBorder; private float _solidOpacity; private Color _dropDockBack; private Color _dropDockBorder; private Color _dropDockActive; private Color _dropDockInactive; #endregion #region Identity /// <summary> /// Initialize a new instance of the PaletteDragDrop class. /// </summary> /// <param name="inherit">Source for inheriting values.</param> /// <param name="needPaint">Delegate for notifying paint requests.</param> public PaletteDragDrop(IPalette inherit, NeedPaintHandler needPaint) { // Remember inheritance _inherit = inherit; // Store the provided paint notification delegate NeedPaint = needPaint; // Set default values _feedback = PaletteDragFeedback.Inherit; _solidBack = Color.Empty; _solidBorder = Color.Empty; _solidOpacity = -1.0f; _dropDockBack = Color.Empty; _dropDockBorder = Color.Empty; _dropDockActive = Color.Empty; _dropDockInactive = Color.Empty; } #endregion #region IsDefault /// <summary> /// Gets a value indicating if all values are default. /// </summary> [Browsable(false)] public override bool IsDefault => ((Feedback == PaletteDragFeedback.Inherit) && (SolidBack == Color.Empty) && (SolidBorder == Color.Empty) && (SolidOpacity == -1.0f) && (DropDockBack == Color.Empty) && (DropDockBorder == Color.Empty) && (DropDockActive == Color.Empty) && (DropDockInactive == Color.Empty)); #endregion #region SetInherit /// <summary> /// Sets the inheritence parent. /// </summary> public void SetInherit(IPalette inherit) { _inherit = inherit; } #endregion #region PopulateFromBase /// <summary> /// Populate values from the base palette. /// </summary> public void PopulateFromBase() { Feedback = GetDragDropFeedback(); SolidBack = GetDragDropSolidBack(); SolidBorder = GetDragDropSolidBorder(); SolidOpacity = GetDragDropSolidOpacity(); DropDockBack = GetDragDropDockBack(); DropDockBorder = GetDragDropDockBorder(); DropDockActive = GetDragDropDockBorder(); DropDockInactive = GetDragDropDockInactive(); } #endregion #region Feedback /// <summary> /// Gets and sets the feedback drawing method used. /// </summary> [KryptonPersist(false)] [Category("Visuals")] [Description("Feedback drawing method used.")] [DefaultValue(typeof(PaletteDragFeedback), "Inherit")] [RefreshPropertiesAttribute(RefreshProperties.All)] public PaletteDragFeedback Feedback { get => _feedback; set { if (_feedback != value) { _feedback = value; PerformNeedPaint(); } } } /// <summary> /// Resets the Feedback property to its default value. /// </summary> public void ResetFeedback() { Feedback = PaletteDragFeedback.Inherit; } /// <summary> /// Gets the feedback drawing method used. /// </summary> /// <returns>Color value.</returns> public PaletteDragFeedback GetDragDropFeedback() => Feedback != PaletteDragFeedback.Inherit ? Feedback : _inherit.GetDragDropFeedback(); #endregion #region SolidBack /// <summary> /// Gets and sets the background color for a solid drag drop area. /// </summary> [KryptonPersist(false)] [Category("Visuals")] [Description("Background color for a solid drag drop area.")] [DefaultValue(typeof(Color), "")] [RefreshPropertiesAttribute(RefreshProperties.All)] public Color SolidBack { get => _solidBack; set { if (_solidBack != value) { _solidBack = value; PerformNeedPaint(); } } } /// <summary> /// Resets the SolidBack property to its default value. /// </summary> public void ResetSolidBack() => SolidBack = Color.Empty; /// <summary> /// Gets the background color for a solid drag drop area. /// </summary> /// <returns>Color value.</returns> public Color GetDragDropSolidBack() => SolidBack != Color.Empty ? SolidBack : _inherit.GetDragDropSolidBack(); #endregion #region SolidBorder /// <summary> /// Gets and sets the border color for a solid drag drop area. /// </summary> [KryptonPersist(false)] [Category("Visuals")] [Description("Border color for a solid drag drop area.")] [DefaultValue(typeof(Color), "")] [RefreshPropertiesAttribute(RefreshProperties.All)] public Color SolidBorder { get => _solidBorder; set { if (_solidBorder != value) { _solidBorder = value; PerformNeedPaint(); } } } /// <summary> /// Resets the SolidBorder property to its default value. /// </summary> public void ResetSolidBorder() => SolidBorder = Color.Empty; /// <summary> /// Gets the border color for a solid drag drop area. /// </summary> /// <returns>Color value.</returns> public Color GetDragDropSolidBorder() => SolidBorder != Color.Empty ? SolidBorder : _inherit.GetDragDropSolidBorder(); #endregion #region SolidOpacity /// <summary> /// Gets and sets the opacity of the solid area. /// </summary> [KryptonPersist(false)] [Category("Visuals")] [Description("Opacity for the solid drag drop area.")] [DefaultValue(-1.0f)] [RefreshPropertiesAttribute(RefreshProperties.All)] public float SolidOpacity { get => _solidOpacity; set { if (_solidOpacity != value) { _solidOpacity = value; PerformNeedPaint(); } } } /// <summary> /// Resets the SolidOpacity property to its default value. /// </summary> public void ResetSolidOpacity() => SolidOpacity = -1.0f; /// <summary> /// Gets the opacity of the solid area. /// </summary> /// <returns>Opacity ranging from 0 to 1.</returns> public virtual float GetDragDropSolidOpacity() => SolidOpacity >= 0.0f ? SolidOpacity : _inherit.GetDragDropSolidOpacity(); #endregion #region DropDockBack /// <summary> /// Gets and sets the background color for the docking indicators area. /// </summary> [KryptonPersist(false)] [Category("Visuals")] [Description("Background color for the docking indicators area.")] [DefaultValue(typeof(Color), "")] [RefreshPropertiesAttribute(RefreshProperties.All)] public Color DropDockBack { get => _dropDockBack; set { if (_dropDockBack != value) { _dropDockBack = value; PerformNeedPaint(); } } } /// <summary> /// Resets the DropDockBack property to its default value. /// </summary> public void ResetDropDockBack() => DropDockBack = Color.Empty; /// <summary> /// Gets the background color for the docking indicators area. /// </summary> /// <returns>Color value.</returns> public Color GetDragDropDockBack() => DropDockBack != Color.Empty ? DropDockBack : _inherit.GetDragDropDockBack(); #endregion #region DropDockBorder /// <summary> /// Gets and sets the border color for the docking indicators area. /// </summary> [KryptonPersist(false)] [Category("Visuals")] [Description("Border color for the docking indicators area.")] [DefaultValue(typeof(Color), "")] [RefreshPropertiesAttribute(RefreshProperties.All)] public Color DropDockBorder { get => _dropDockBorder; set { if (_dropDockBorder != value) { _dropDockBorder = value; PerformNeedPaint(); } } } /// <summary> /// Resets the DropDockBorder property to its default value. /// </summary> public void ResetDropDockBorder() => DropDockBorder = Color.Empty; /// <summary> /// Gets the border color for the docking indicators area. /// </summary> /// <returns>Color value.</returns> public Color GetDragDropDockBorder() => DropDockBorder != Color.Empty ? DropDockBorder : _inherit.GetDragDropDockBorder(); #endregion #region DropDockActive /// <summary> /// Gets and sets the active color for docking indicators. /// </summary> [KryptonPersist(false)] [Category("Visuals")] [Description("Sctive color for docking indicators..")] [DefaultValue(typeof(Color), "")] [RefreshPropertiesAttribute(RefreshProperties.All)] public Color DropDockActive { get => _dropDockActive; set { if (_dropDockActive != value) { _dropDockActive = value; PerformNeedPaint(); } } } /// <summary> /// Resets the DropDockActive property to its default value. /// </summary> public void ResetDropDockActive() => DropDockActive = Color.Empty; /// <summary> /// Gets the active color for docking indicators. /// </summary> /// <returns>Color value.</returns> public Color GetDragDropDockActive() => DropDockActive != Color.Empty ? DropDockActive : _inherit.GetDragDropDockActive(); #endregion #region DropDockInactive /// <summary> /// Gets and sets the inactive color for docking indicators. /// </summary> [KryptonPersist(false)] [Category("Visuals")] [Description("Inactive color for docking indicators.")] [DefaultValue(typeof(Color), "")] [RefreshPropertiesAttribute(RefreshProperties.All)] public Color DropDockInactive { get => _dropDockInactive; set { if (_dropDockInactive != value) { _dropDockInactive = value; PerformNeedPaint(); } } } /// <summary> /// Resets the DropDockInactive property to its default value. /// </summary> public void ResetDropDockInactive() => DropDockInactive = Color.Empty; /// <summary> /// Gets the inactive color for docking indicators. /// </summary> /// <returns>Color value.</returns> public Color GetDragDropDockInactive() => DropDockInactive != Color.Empty ? DropDockInactive : _inherit.GetDragDropDockInactive(); #endregion } }
33.411911
157
0.534571
[ "BSD-3-Clause" ]
Carko/Krypton-Toolkit-Suite-NET-Core
Source/Krypton Components/ComponentFactory.Krypton.Toolkit/Palette Base/PaletteDragDrop/PaletteDragDrop.cs
13,468
C#
using ClientCore; using ClientGUI; using Microsoft.Xna.Framework; using Rampastring.XNAUI; using Rampastring.XNAUI.XNAControls; using System; using System.IO; using Updater; namespace DTAConfig.OptionPanels { class UpdaterOptionsPanel : XNAOptionsPanel { public UpdaterOptionsPanel(WindowManager windowManager, UserINISettings iniSettings) : base(windowManager, iniSettings) { } public event EventHandler OnForceUpdate; private XNAListBox lbUpdateServerList; private XNAClientCheckBox chkAutoCheck; private XNAClientButton btnForceUpdate; public override void Initialize() { base.Initialize(); Name = "UpdaterOptionsPanel"; var lblDescription = new XNALabel(WindowManager); lblDescription.Name = "lblDescription"; lblDescription.ClientRectangle = new Rectangle(12, 12, 0, 0); lblDescription.Text = "To change download server priority, select a server from the list and" + Environment.NewLine + "use the Move Up / Down buttons to change its priority."; lbUpdateServerList = new XNAListBox(WindowManager); lbUpdateServerList.Name = "lblUpdateServerList"; lbUpdateServerList.ClientRectangle = new Rectangle(lblDescription.X, lblDescription.Bottom + 12, Width - 24, 100); lbUpdateServerList.BackgroundTexture = AssetLoader.CreateTexture(new Color(0, 0, 0, 128), 2, 2); lbUpdateServerList.PanelBackgroundDrawMode = PanelBackgroundImageDrawMode.STRETCHED; var btnMoveUp = new XNAClientButton(WindowManager); btnMoveUp.Name = "btnMoveUp"; btnMoveUp.ClientRectangle = new Rectangle(lbUpdateServerList.X, lbUpdateServerList.Bottom + 12, 133, 23); btnMoveUp.Text = "Move Up"; btnMoveUp.LeftClick += btnMoveUp_LeftClick; var btnMoveDown = new XNAClientButton(WindowManager); btnMoveDown.Name = "btnMoveDown"; btnMoveDown.ClientRectangle = new Rectangle( lbUpdateServerList.Right - 133, btnMoveUp.Y, 133, 23); btnMoveDown.Text = "Move Down"; btnMoveDown.LeftClick += btnMoveDown_LeftClick; chkAutoCheck = new XNAClientCheckBox(WindowManager); chkAutoCheck.Name = "chkAutoCheck"; chkAutoCheck.ClientRectangle = new Rectangle(lblDescription.X, btnMoveUp.Bottom + 24, 0, 0); chkAutoCheck.Text = "Check for updates automatically"; btnForceUpdate = new XNAClientButton(WindowManager); btnForceUpdate.Name = "btnForceUpdate"; btnForceUpdate.ClientRectangle = new Rectangle(btnMoveDown.X, btnMoveDown.Bottom + 24, 133, 23); btnForceUpdate.Text = "Force Update"; btnForceUpdate.LeftClick += BtnForceUpdate_LeftClick; AddChild(lblDescription); AddChild(lbUpdateServerList); AddChild(btnMoveUp); AddChild(btnMoveDown); AddChild(chkAutoCheck); AddChild(btnForceUpdate); } private void BtnForceUpdate_LeftClick(object sender, EventArgs e) { var msgBox = new XNAMessageBox(WindowManager, "Force Update Confirmation", "WARNING: Force update will result in files being re-verified" + Environment.NewLine + "and re-downloaded. While this may fix problems with game" + Environment.NewLine + "files, this also may delete some custom modifications" + Environment.NewLine + "made to this installation. Use at your own risk!" + Environment.NewLine + Environment.NewLine + "If you proceed, the options window will close and the" + Environment.NewLine + "client will proceed to checking for updates." + Environment.NewLine + Environment.NewLine + "Do you really want to force update?" + Environment.NewLine, XNAMessageBoxButtons.YesNo); msgBox.Show(); msgBox.YesClickedAction = ForceUpdateMsgBox_YesClicked; } private void ForceUpdateMsgBox_YesClicked(XNAMessageBox obj) { CUpdater.ClearVersionInfo(); OnForceUpdate?.Invoke(this, EventArgs.Empty); } private void btnMoveUp_LeftClick(object sender, EventArgs e) { int selectedIndex = lbUpdateServerList.SelectedIndex; if (selectedIndex < 1) return; var tmp = lbUpdateServerList.Items[selectedIndex - 1]; lbUpdateServerList.Items[selectedIndex - 1] = lbUpdateServerList.Items[selectedIndex]; lbUpdateServerList.Items[selectedIndex] = tmp; lbUpdateServerList.SelectedIndex--; UpdateMirror umtmp = CUpdater.UPDATEMIRRORS[selectedIndex - 1]; CUpdater.UPDATEMIRRORS[selectedIndex - 1] = CUpdater.UPDATEMIRRORS[selectedIndex]; CUpdater.UPDATEMIRRORS[selectedIndex] = umtmp; } private void btnMoveDown_LeftClick(object sender, EventArgs e) { int selectedIndex = lbUpdateServerList.SelectedIndex; if (selectedIndex > lbUpdateServerList.Items.Count - 2 || selectedIndex < 0) return; var tmp = lbUpdateServerList.Items[selectedIndex + 1]; lbUpdateServerList.Items[selectedIndex + 1] = lbUpdateServerList.Items[selectedIndex]; lbUpdateServerList.Items[selectedIndex] = tmp; lbUpdateServerList.SelectedIndex++; UpdateMirror umtmp = CUpdater.UPDATEMIRRORS[selectedIndex + 1]; CUpdater.UPDATEMIRRORS[selectedIndex + 1] = CUpdater.UPDATEMIRRORS[selectedIndex]; CUpdater.UPDATEMIRRORS[selectedIndex] = umtmp; } public override void Load() { base.Load(); lbUpdateServerList.Clear(); foreach (var updaterMirror in CUpdater.UPDATEMIRRORS) lbUpdateServerList.AddItem(updaterMirror.Name + (!string.IsNullOrEmpty(updaterMirror.Location) ? " (" + updaterMirror.Location + ")" : "")); chkAutoCheck.Checked = IniSettings.CheckForUpdates; } public override bool Save() { bool restartRequired = base.Save(); IniSettings.CheckForUpdates.Value = chkAutoCheck.Checked; IniSettings.SettingsIni.EraseSectionKeys("DownloadMirrors"); int id = 0; foreach (UpdateMirror um in CUpdater.UPDATEMIRRORS) { IniSettings.SettingsIni.SetStringValue("DownloadMirrors", id.ToString(), um.Name); id++; } return restartRequired; } public override void ToggleMainMenuOnlyOptions(bool enable) { btnForceUpdate.AllowClick = enable; } } }
41.28
114
0.615449
[ "MIT" ]
Metadorius/xna-cncnet-client
DTAConfig/OptionPanels/UpdaterOptionsPanel.cs
7,050
C#
namespace EnvironmentAssessment.Common.VimApi { public class ClusterDrsFaultsFaultsByVm_LinkedView { protected VirtualMachine _vm; public VirtualMachine Vm { get { return this._vm; } set { this._vm = value; } } } }
13.263158
51
0.670635
[ "MIT" ]
octansIt/environmentassessment
EnvironmentAssessment.Wizard/Common/VimApi/C/ClusterDrsFaultsFaultsByVm_LinkedView.cs
252
C#
// Copyright 2012-2013 Chris Patterson // // 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 Taskell { using System; using System.Runtime.Serialization; [Serializable] public class TaskComposerException : TaskellException { public TaskComposerException() { } public TaskComposerException(string message) : base(message) { } public TaskComposerException(string message, Exception innerException) : base(message, innerException) { } protected TaskComposerException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
31.475
122
0.651311
[ "Apache-2.0" ]
phatboyg/Taskell
src/Taskell/TaskComposerException.cs
1,261
C#
using Locust.Caching; using Locust.ServiceModel; using Locust.ServiceModel.Babbage; using Locust.Modules.Setting.Model; using AppSettingCategory = Locust.Modules.Setting.Model.AppSettingCategory.Full; namespace Locust.Modules.Setting.Strategies { public abstract partial class AppSettingCategoryGetByCodeStrategyBase : BabbageItemFetcherStrategy<AppSettingCategoryGetByCodeResponse, AppSettingCategory, AppSettingCategoryGetByCodeStatus, AppSettingCategoryGetByCodeRequest, AppSettingCategoryGetByCodeContext> { protected void Init(ICacheFactory iCacheFactory) { } } }
38.933333
263
0.85274
[ "MIT" ]
mansoor-omrani/Locust.NET
Modules/Locust.Modules.Setting/Service/AppSettingCategory/GetByCode/StrategyBase.Customized.cs
584
C#
namespace ODMIdentity.STS.Identity.Configuration { public class CertificateConfiguration { public bool UseTemporarySigningKeyForDevelopment { get; set; } public bool UseSigningCertificateThumbprint { get; set; } public string SigningCertificateThumbprint { get; set; } public bool UseSigningCertificatePfxFile { get; set; } public string SigningCertificatePfxFilePath { get; set; } public string SigningCertificatePfxFilePassword { get; set; } public bool UseValidationCertificateThumbprint { get; set; } public string ValidationCertificateThumbprint { get; set; } public bool UseValidationCertificatePfxFile { get; set; } public string ValidationCertificatePfxFilePath { get; set; } public string ValidationCertificatePfxFilePassword { get; set; } } }
31.428571
76
0.7
[ "MIT" ]
omikolaj/IdentityServer4-Admin
ODMIdentity/src/ODMIdentity.STS.Identity/Configuration/CertificateConfiguration.cs
882
C#
namespace MyFitnessApp.Web.ViewModels.Foods { using System.ComponentModel.DataAnnotations; using MyFitnessApp.Data.Models; using static MyFitnessApp.Common.DataConstants; public class AddFoodInputModel { public string Name { get; set; } // Dropdown Menu [Display(Name = "Meal name")] public MealName MealName { get; set; } [Required(ErrorMessage = "The field is required")] [Range(FoodQuantityInGramsMinValue, FoodQuantityInGramsMaxValue, ErrorMessage ="Quantity must be in range between 1 and 5000")] [Display(Name = "Quantity in grams")] public double ServingSize { get; set; } } }
29.478261
135
0.674041
[ "MIT" ]
GeorgiGradev/MyFitnessApp
MyFitnessApp/Web/MyFitnessApp.Web.ViewModels/Foods/AddFoodInputModel.cs
680
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("06.TheBiggestOfFiveNumbers")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("06.TheBiggestOfFiveNumbers")] [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("aa7060f4-c69a-4fc9-9b98-dbb373f14f07")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.513514
84
0.748772
[ "MIT" ]
VelislavLeonov/Telerik-Akademy
HomeworkConditionalStatements/06.TheBiggestOfFiveNumbers/Properties/AssemblyInfo.cs
1,428
C#
using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace ExpandedContent.Utilities { static class DescriptionTools { private static readonly EncyclopediaEntry[] EncyclopediaEntries = new EncyclopediaEntry[] { new EncyclopediaEntry { Entry = "Strength", Patterns = { "Strength" } }, new EncyclopediaEntry { Entry = "Dexterity", Patterns = { "Dexterity" } }, new EncyclopediaEntry { Entry = "Constitution", Patterns = { "Constitution" } }, new EncyclopediaEntry { Entry = "Intelligence", Patterns = { "Intelligence" } }, new EncyclopediaEntry { Entry = "Wisdom", Patterns = { "Wisdom" } }, new EncyclopediaEntry { Entry = "Charisma", Patterns = { "Charisma" } }, new EncyclopediaEntry { Entry = "Ability_Scores", Patterns = { "Ability Scores?" } }, new EncyclopediaEntry { Entry = "Athletics", Patterns = { "Athletics" } }, new EncyclopediaEntry { Entry = "Persuasion", Patterns = { "Persuasion" } }, new EncyclopediaEntry { Entry = "Knowledge_World", Patterns = { @"Knowledge \(?World\)?" } }, new EncyclopediaEntry { Entry = "Knowledge_Arcana", Patterns = { @"Knowledge \(?Arcana\)?" } }, new EncyclopediaEntry { Entry = "Lore_Nature", Patterns = { @"Lore \(?Nature\)?" } }, new EncyclopediaEntry { Entry = "Lore_Religion", Patterns = { @"Lore \(?Religion\)?" } }, new EncyclopediaEntry { Entry = "Mobility", Patterns = { "Mobility" } }, new EncyclopediaEntry { Entry = "Perception", Patterns = { "Perception" } }, new EncyclopediaEntry { Entry = "Stealth", Patterns = { "Stealth" } }, new EncyclopediaEntry { Entry = "Trickery", Patterns = { "Trickery" } }, new EncyclopediaEntry { Entry = "Use_Magic_Device", Patterns = { "Use Magic Device", "UMD" } }, new EncyclopediaEntry { Entry = "Race", Patterns = { "Race" } }, new EncyclopediaEntry { Entry = "Alignment", Patterns = { "Alignment" } }, new EncyclopediaEntry { Entry = "Caster_Level", Patterns = { "Caster Level", "CL" } }, new EncyclopediaEntry { Entry = "DC", Patterns = { "DC" } }, new EncyclopediaEntry { Entry = "Saving_Throw", Patterns = { "Saving Throw", "Reflex Save", "Will Save", "Fortitude Save" } }, new EncyclopediaEntry { Entry = "Spell_Resistance", Patterns = { "Spell Resistance" } }, new EncyclopediaEntry { Entry = "Spell_Fail_Chance", Patterns = { "Arcane Spell Failure" } }, new EncyclopediaEntry { Entry = "Concentration_Checks", Patterns = { "Concentration Checks?" } }, new EncyclopediaEntry { Entry = "Concealment", Patterns = { "Concealment" } }, new EncyclopediaEntry { Entry = "Bonus", Patterns = {"Bonus(es)?"} }, new EncyclopediaEntry { Entry = "Speed", Patterns = { "Speed" } }, new EncyclopediaEntry { Entry = "Flat_Footed_AC", Patterns = { "Flat Footed AC", "Flat Footed Armor Class" } }, new EncyclopediaEntry { Entry = "Flat_Footed", Patterns = { "Flat Footed", "Flat-Footed" } }, new EncyclopediaEntry { Entry = "Armor_Class", Patterns = { "Armor Class", "AC" } }, new EncyclopediaEntry { Entry = "Armor_Check_Penalty", Patterns = { "Armor Check Penalty" } }, new EncyclopediaEntry { Entry = "Damage_Reduction", Patterns = { "DR" } }, new EncyclopediaEntry { Entry = "Free_Action", Patterns = { "Free Action" } }, new EncyclopediaEntry { Entry = "Swift_Action", Patterns = { "Swift Action" } }, new EncyclopediaEntry { Entry = "Standard_Actions", Patterns = { "Standard Action" } }, new EncyclopediaEntry { Entry = "Full_Round_Action", Patterns = { "Full Round Action" } }, new EncyclopediaEntry { Entry = "Skills", Patterns = { "Skills? Checks?", "Skills?" } }, new EncyclopediaEntry { Entry = "Combat_Maneuvers", Patterns = { "Combat Maneuvers?" } }, new EncyclopediaEntry { Entry = "CMB", Patterns = { "Combat Maneuver Bonus", "CMB" } }, new EncyclopediaEntry { Entry = "CMD", Patterns = { "Combat Maneuver Defense", "CMD" } }, new EncyclopediaEntry { Entry = "BAB", Patterns = { "Base Attack Bonus", "BAB" } }, new EncyclopediaEntry { Entry = "Incorporeal_Touch_Attack", Patterns = { "Incorporeal Touch Attacks?" } }, new EncyclopediaEntry { Entry = "TouchAttack", Patterns = { "Touch Attacks?" } }, new EncyclopediaEntry { Entry = "NaturalAttack", Patterns = { "Natural Attacks?", "Natural Weapons?" } }, new EncyclopediaEntry { Entry = "Attack_Of_Opportunity", Patterns = { "Attacks? Of Opportunity", "AoO" } }, new EncyclopediaEntry { Entry = "Penalty", Patterns = { "Penalty" } }, new EncyclopediaEntry { Entry = "Check", Patterns = { "Checks?" } }, new EncyclopediaEntry { Entry = "Spells", Patterns = { "Spells?" } }, new EncyclopediaEntry { Entry = "Attack", Patterns = { "Attacks?" } }, new EncyclopediaEntry { Entry = "Feat", Patterns = { "Feats?" } }, new EncyclopediaEntry { Entry = "Charge", Patterns = { "Charge" } }, new EncyclopediaEntry { Entry = "Critical", Patterns = { "Critical Hit" } }, new EncyclopediaEntry { Entry = "Fast_Healing", Patterns = { "Fast Healing" } }, new EncyclopediaEntry { Entry = "Temporary_HP", Patterns = { "Temporary HP" } }, new EncyclopediaEntry { Entry = "Flanking", Patterns = { "Flanking", "Flanked" } }, new EncyclopediaEntry { Entry = "Magic_School", Patterns = { "School of Magic" } }, new EncyclopediaEntry { Entry = "Damage_Type", Patterns = { "Bludgeoning", "Piercing", "Slashing" } }, new EncyclopediaEntry { Entry = "Damage", Patterns = { "damage", "damage rolls?" } }, new EncyclopediaEntry { Entry = "Dice", Patterns = { "rolls?", "rolled" } } }; public static string TagEncyclopediaEntries(string description) { var result = description; result = result.StripHTML(); foreach (var entry in EncyclopediaEntries) { foreach (var pattern in entry.Patterns) { result = result.ApplyTags(pattern, entry); } } return result; } private class EncyclopediaEntry { public string Entry = ""; public List<string> Patterns = new List<string>(); public string Tag(string keyword) { return $"{{g|Encyclopedia:{Entry}}}{keyword}{{/g}}"; } } private static string ApplyTags(this string str, string from, EncyclopediaEntry entry) { var pattern = from.EnforceSolo().ExcludeTagged(); var matches = Regex.Matches(str, pattern, RegexOptions.IgnoreCase) .OfType<Match>() .Select(m => m.Value) .Distinct(); var firstMatch = matches.FirstOrDefault(); if (!string.IsNullOrEmpty(firstMatch)) { var resultPattern = new Regex(Regex.Escape(firstMatch).EnforceSolo().ExcludeTagged(), RegexOptions.IgnoreCase); str = resultPattern.Replace(str, entry.Tag(firstMatch), 1); } /* foreach (string match in matches) { str = Regex.Replace(str, Regex.Escape(match).EnforceSolo().ExcludeTagged(), entry.Tag(match), RegexOptions.IgnoreCase); } */ return str; } public static string StripHTML(this string str) { return Regex.Replace(str, "<.*?>", string.Empty); } public static string StripEncyclopediaTags(this string str) { return Regex.Replace(str, "{.*?}", string.Empty); } private static string ExcludeTagged(this string str) { return $"{@"(?<!{g\|Encyclopedia:\w+}[^}]*)"}{str}{@"(?![^{]*{\/g})"}"; } private static string EnforceSolo(this string str) { return $"{@"(?<![\w>]+)"}{str}{@"(?![^\s\.,""'<)]+)"}"; } } }
33.420168
135
0.40466
[ "MIT" ]
ka-dyn/ExpandedContent
ExpandedContent/Utilities/DescriptionTools.cs
11,933
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Practica2Creev { public partial class Form1 : Form { Form2 N = new Form2(); int x; int y; String texto; Image fondoRed; Image Rombo; int maxX; int maxY; bool mover; bool cambiomaximo; public Form1() { InitializeComponent(); fondoRed = Image.FromFile("Recursos\\red.png"); Rombo = Image.FromFile("Recursos\\rombo.png"); maxX = 1224; maxY = 592; cambiomaximo = false; objeto.BackColor = (Color.Black); } private void pictureBox1_Paint(object sender, PaintEventArgs e) { Graphics g = e.Graphics; g.DrawImage(fondoRed, 0,0, 500,473); g.DrawImage(Rombo, 510, 0, 400, 447); } private void panel1_Paint(object sender, PaintEventArgs e) { } private void objeto_Paint(object sender, PaintEventArgs e) { } private void pictureBox1_MouseMove(object sender, MouseEventArgs e) { texto = N.DevNombre(); label4.Text = texto; if (mover == true) { Point mouseMoveLocation = new Point(e.X, e.Y); x = e.X; y = e.Y; colision(); objeto.Location = new System.Drawing.Point(x, y); if (x <= 500 && y<=473) { cambiomaximo = true; } if (cambiomaximo) { maxX = 370; maxY = 390; } colision(); } } public void colision() { if (x >= maxX) { x = maxX; } if (y >= maxY) { y = maxY; } } private void panel1_Click(object sender, EventArgs e) { mover = true; } private void label1_Click(object sender, EventArgs e) { mover = true; } private void panel2_Click(object sender, EventArgs e) { MessageBox.Show("Color cambiado"); var rand = new Random(); int color = rand.Next(6); switch(color) { case 1: objeto.BackColor = (Color.Red); break; case 2: objeto.BackColor = (Color.Blue); break; case 3: objeto.BackColor = (Color.Green); break; case 4: objeto.BackColor = (Color.Yellow); break; case 5: objeto.BackColor = (Color.Cyan); break; } texto = N.DevNombre(); label4.Text = texto; } private void label2_Click(object sender, EventArgs e) { MessageBox.Show("Color cambiado"); var rand = new Random(); int color = rand.Next(6); switch (color) { case 1: objeto.BackColor = (Color.Red); break; case 2: objeto.BackColor = (Color.Blue); break; case 3: objeto.BackColor = (Color.Green); break; case 4: objeto.BackColor = (Color.Yellow); break; case 5: objeto.BackColor = (Color.Cyan); break; } } private void panel3_Paint(object sender, PaintEventArgs e) { } private void panel3_Click(object sender, EventArgs e) { N.Show(); N.Enabled = true; } private void label3_Click(object sender, EventArgs e) { N.Show(); N.Enabled = true; } private void pictureBox1_Click(object sender, EventArgs e) { } private void Form1_KeyPress(object sender, KeyPressEventArgs e) { Console.WriteLine(e.KeyChar.ToString()); if (e.KeyChar == 'a' || e.KeyChar == 'A') { MessageBox.Show("Color cambiado"); var rand = new Random(); int color = rand.Next(6); switch (color) { case 1: objeto.BackColor = (Color.Red); break; case 2: objeto.BackColor = (Color.Blue); break; case 3: objeto.BackColor = (Color.Green); break; case 4: objeto.BackColor = (Color.Yellow); break; case 5: objeto.BackColor = (Color.Cyan); break; } } if (e.KeyChar == 's' || e.KeyChar == 'S') { N.Show(); N.Enabled = true; } if (e.KeyChar == 'w' || e.KeyChar == 'W') { mover = true; } } private void Form1_Load(object sender, EventArgs e) { } } }
25.605932
75
0.395002
[ "MIT" ]
JonatanYah/TAP-4A-ISC
Practicas/C#/Practica2Creev/Form1.cs
6,045
C#
using System; namespace WorldSim { class Program { static void Main(string[] args) { Renderer renderer = new Renderer(2000, 2000); Country newCountry = new Country(); newCountry.GenerateTowns(); renderer.RenderCountry(newCountry); renderer.Save(); } } }
18.631579
57
0.542373
[ "MIT" ]
jccit/WorldSim
WorldSim/Program.cs
356
C#
using System; using System.Collections.Generic; using System.Text; namespace StrategyPattern { public class Person { public Person(string name, int age) { this.Name = name; this.Age = age; } public string Name { get; } public int Age { get; } public override string ToString() { return $"{this.Name} {this.Age}"; } } }
17.48
45
0.524027
[ "MIT" ]
steelpr/CSharp-Fundamentals
C# OOP Advanced - March 2018/IteratorsAndComparators/StrategyPattern/Person.cs
439
C#
using System; using Xunit; using Statistics; using System.Collections.Generic; using System.Linq; namespace Statistics.Test { public class StatsUnitTest { [Fact] public void ReportsAverageMinMax() { var statsComputer = new StatsComputer(); var computedStats = statsComputer.CalculateStatistics(new List<double>{1.5, 8.9, 3.2, 4.5}); float epsilon = 0.001F; Assert.True(Math.Abs(computedStats.average - 4.525) <= epsilon); Assert.True(Math.Abs(computedStats.max - 8.9) <= epsilon); Assert.True(Math.Abs(computedStats.min - 1.5) <= epsilon); } [Fact] public void ReportsNaNForEmptyInput() { var statsComputer = new StatsComputer(); var computedStats = statsComputer.CalculateStatistics(new List<double>{}); //All fields of computedStats (average, max, min) must be //Double.NaN (not-a-number), as described in //https://docs.microsoft.com/en-us/dotnet/api/system.double.nan?view=netcore-3.1 Assert.True(double.IsNaN(computedStats.average)); Assert.True(double.IsNaN(computedStats.max)); Assert.True(double.IsNaN(computedStats.min)); } } }
35.888889
104
0.613777
[ "MIT" ]
Engin-Boot/statisticker-cs-patreshubham94
Statistics.Test/StatsUnitTest.cs
1,292
C#
#region using System; #endregion namespace Vermeil.Core.Logging { internal class LogItem { public LogItem(string message, LogType logType, string exception = null) { Message = message; LogType = logType; Exception = exception; } public string Message { get; set; } public LogType LogType { get; set; } public string Exception { get; set; } public override string ToString() { return (Exception == null ? string.Format("[{0}]\t: {1}\t > {2}", DateTime.Now, LogType, Message) : string.Format("[{0}]\t: {1}\t > {2}\n--------\n{3}\n--------", DateTime.Now, LogType, Message, Exception)); } } }
24.78125
126
0.504414
[ "MIT", "Unlicense" ]
dotcypress/Vermeil
Vermeil.Core/Logging/LogItem.cs
795
C#
//********************************* bs::framework - Copyright 2018-2019 Marko Pintera ************************************// //*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********// using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace bs { /** @addtogroup Rendering * @{ */ /// <summary>Settings that control rendering for a specific camera (view).</summary> [ShowInInspector] public partial class RenderSettings : ScriptObject { private RenderSettings(bool __dummy0) { } public RenderSettings() { Internal_RenderSettings(this); } /// <summary>Parameters used for customizing the gaussian depth of field effect.</summary> [ShowInInspector] [NotNull] [PassByCopy] [NativeWrapper] public DepthOfFieldSettings DepthOfField { get { return Internal_getdepthOfField(mCachedPtr); } set { Internal_setdepthOfField(mCachedPtr, value); } } /// <summary> /// Determines should automatic exposure be applied to the HDR image. When turned on the average scene brightness will be /// calculated and used to automatically expose the image to the optimal range. Use the parameters provided by /// autoExposure to customize the automatic exposure effect. You may also use exposureScale to manually adjust the /// automatic exposure. When automatic exposure is turned off you can use exposureScale to manually set the exposure. /// </summary> [ShowInInspector] [NativeWrapper] public bool EnableAutoExposure { get { return Internal_getenableAutoExposure(mCachedPtr); } set { Internal_setenableAutoExposure(mCachedPtr, value); } } /// <summary>Parameters used for customizing automatic scene exposure.</summary> [ShowInInspector] [NotNull] [PassByCopy] [NativeWrapper] public AutoExposureSettings AutoExposure { get { return Internal_getautoExposure(mCachedPtr); } set { Internal_setautoExposure(mCachedPtr, value); } } /// <summary> /// Determines should the image be tonemapped. Tonemapping converts an HDR image into LDR image by applying a filmic /// curve to the image, simulating the effect of film cameras. Filmic curve improves image quality by tapering off lows /// and highs, preventing under- and over-exposure. This is useful if an image contains both very dark and very bright /// areas, in which case the global exposure parameter would leave some areas either over- or under-exposed. Use /// #tonemapping to customize how tonemapping performed. /// /// If this is disabled, then color grading and white balancing will not be enabled either. Only relevant for HDR images. /// </summary> [ShowInInspector] [NativeWrapper] public bool EnableTonemapping { get { return Internal_getenableTonemapping(mCachedPtr); } set { Internal_setenableTonemapping(mCachedPtr, value); } } /// <summary>Parameters used for customizing tonemapping.</summary> [ShowInInspector] [NotNull] [PassByCopy] [NativeWrapper] public TonemappingSettings Tonemapping { get { return Internal_gettonemapping(mCachedPtr); } set { Internal_settonemapping(mCachedPtr, value); } } /// <summary> /// Parameters used for customizing white balancing. White balancing converts a scene illuminated by a light of the /// specified temperature into a scene illuminated by a standard D65 illuminant (average midday light) in order to /// simulate the effects of chromatic adaptation of the human visual system. /// </summary> [ShowInInspector] [NotNull] [PassByCopy] [NativeWrapper] public WhiteBalanceSettings WhiteBalance { get { return Internal_getwhiteBalance(mCachedPtr); } set { Internal_setwhiteBalance(mCachedPtr, value); } } /// <summary>Parameters used for customizing color grading.</summary> [ShowInInspector] [NotNull] [PassByCopy] [NativeWrapper] public ColorGradingSettings ColorGrading { get { return Internal_getcolorGrading(mCachedPtr); } set { Internal_setcolorGrading(mCachedPtr, value); } } /// <summary>Parameters used for customizing screen space ambient occlusion.</summary> [ShowInInspector] [NotNull] [PassByCopy] [NativeWrapper] public AmbientOcclusionSettings AmbientOcclusion { get { return Internal_getambientOcclusion(mCachedPtr); } set { Internal_setambientOcclusion(mCachedPtr, value); } } /// <summary>Parameters used for customizing screen space reflections.</summary> [ShowInInspector] [NotNull] [PassByCopy] [NativeWrapper] public ScreenSpaceReflectionsSettings ScreenSpaceReflections { get { return Internal_getscreenSpaceReflections(mCachedPtr); } set { Internal_setscreenSpaceReflections(mCachedPtr, value); } } /// <summary>Parameters used for customizing the bloom effect.</summary> [ShowInInspector] [NotNull] [PassByCopy] [NativeWrapper] public BloomSettings Bloom { get { return Internal_getbloom(mCachedPtr); } set { Internal_setbloom(mCachedPtr, value); } } /// <summary>Parameters used for customizing the screen space lens flare effect.</summary> [ShowInInspector] [NotNull] [PassByCopy] [NativeWrapper] public ScreenSpaceLensFlareSettings ScreenSpaceLensFlare { get { return Internal_getscreenSpaceLensFlare(mCachedPtr); } set { Internal_setscreenSpaceLensFlare(mCachedPtr, value); } } /// <summary>Enables the fast approximate anti-aliasing effect.</summary> [ShowInInspector] [NativeWrapper] public bool EnableFXAA { get { return Internal_getenableFXAA(mCachedPtr); } set { Internal_setenableFXAA(mCachedPtr, value); } } /// <summary> /// Log2 value to scale the eye adaptation by (for example 2^0 = 1). Smaller values yield darker image, while larger /// yield brighter image. Allows you to customize exposure manually, applied on top of eye adaptation exposure (if /// enabled). In range [-8, 8]. /// </summary> [ShowInInspector] [Range(-8f, 8f, true)] [NativeWrapper] public float ExposureScale { get { return Internal_getexposureScale(mCachedPtr); } set { Internal_setexposureScale(mCachedPtr, value); } } /// <summary> /// Gamma value to adjust the image for. Larger values result in a brighter image. When tonemapping is turned on the best /// gamma curve for the output device is chosen automatically and this value can by used to merely tweak that curve. If /// tonemapping is turned off this is the exact value of the gamma curve that will be applied. /// </summary> [ShowInInspector] [Range(1f, 3f, true)] [NativeWrapper] public float Gamma { get { return Internal_getgamma(mCachedPtr); } set { Internal_setgamma(mCachedPtr, value); } } /// <summary> /// High dynamic range allows light intensity to be more correctly recorded when rendering by allowing for a larger range /// of values. The stored light is then converted into visible color range using exposure and a tone mapping operator. /// </summary> [ShowInInspector] [NativeWrapper] public bool EnableHDR { get { return Internal_getenableHDR(mCachedPtr); } set { Internal_setenableHDR(mCachedPtr, value); } } /// <summary> /// Determines if scene objects will be lit by lights. If disabled everything will be rendered using their albedo texture /// with no lighting applied. /// </summary> [ShowInInspector] [NativeWrapper] public bool EnableLighting { get { return Internal_getenableLighting(mCachedPtr); } set { Internal_setenableLighting(mCachedPtr, value); } } /// <summary>Determines if shadows cast by lights should be rendered. Only relevant if lighting is turned on.</summary> [ShowInInspector] [NativeWrapper] public bool EnableShadows { get { return Internal_getenableShadows(mCachedPtr); } set { Internal_setenableShadows(mCachedPtr, value); } } /// <summary>Parameters used for customizing shadow rendering.</summary> [ShowInInspector] [NotNull] [PassByCopy] [NativeWrapper] public ShadowSettings ShadowSettings { get { return Internal_getshadowSettings(mCachedPtr); } set { Internal_setshadowSettings(mCachedPtr, value); } } /// <summary>Determines if indirect lighting (e.g. from light probes or the sky) is rendered.</summary> [ShowInInspector] [NativeWrapper] public bool EnableIndirectLighting { get { return Internal_getenableIndirectLighting(mCachedPtr); } set { Internal_setenableIndirectLighting(mCachedPtr, value); } } /// <summary> /// Signals the renderer to only render overlays (like GUI), and not scene objects. Such rendering doesn&apos;t require /// depth buffer or multi-sampled render targets and will not render any scene objects. This can improve performance and /// memory usage for overlay-only views. /// </summary> [ShowInInspector] [NativeWrapper] public bool OverlayOnly { get { return Internal_getoverlayOnly(mCachedPtr); } set { Internal_setoverlayOnly(mCachedPtr, value); } } /// <summary> /// If enabled the camera will use the skybox for rendering the background. A skybox has to be present in the scene. When /// disabled the camera will use the clear color for rendering the background. /// </summary> [ShowInInspector] [NativeWrapper] public bool EnableSkybox { get { return Internal_getenableSkybox(mCachedPtr); } set { Internal_setenableSkybox(mCachedPtr, value); } } /// <summary> /// The absolute base cull-distance for objects rendered through this camera in world units. Objects will use this /// distance and apply their own factor to it to determine whether they should be visible. /// </summary> [ShowInInspector] [NativeWrapper] public float CullDistance { get { return Internal_getcullDistance(mCachedPtr); } set { Internal_setcullDistance(mCachedPtr, value); } } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_RenderSettings(RenderSettings managedInstance); [MethodImpl(MethodImplOptions.InternalCall)] private static extern DepthOfFieldSettings Internal_getdepthOfField(IntPtr thisPtr); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_setdepthOfField(IntPtr thisPtr, DepthOfFieldSettings value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool Internal_getenableAutoExposure(IntPtr thisPtr); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_setenableAutoExposure(IntPtr thisPtr, bool value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern AutoExposureSettings Internal_getautoExposure(IntPtr thisPtr); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_setautoExposure(IntPtr thisPtr, AutoExposureSettings value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool Internal_getenableTonemapping(IntPtr thisPtr); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_setenableTonemapping(IntPtr thisPtr, bool value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern TonemappingSettings Internal_gettonemapping(IntPtr thisPtr); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_settonemapping(IntPtr thisPtr, TonemappingSettings value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern WhiteBalanceSettings Internal_getwhiteBalance(IntPtr thisPtr); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_setwhiteBalance(IntPtr thisPtr, WhiteBalanceSettings value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern ColorGradingSettings Internal_getcolorGrading(IntPtr thisPtr); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_setcolorGrading(IntPtr thisPtr, ColorGradingSettings value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern AmbientOcclusionSettings Internal_getambientOcclusion(IntPtr thisPtr); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_setambientOcclusion(IntPtr thisPtr, AmbientOcclusionSettings value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern ScreenSpaceReflectionsSettings Internal_getscreenSpaceReflections(IntPtr thisPtr); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_setscreenSpaceReflections(IntPtr thisPtr, ScreenSpaceReflectionsSettings value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern BloomSettings Internal_getbloom(IntPtr thisPtr); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_setbloom(IntPtr thisPtr, BloomSettings value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern ScreenSpaceLensFlareSettings Internal_getscreenSpaceLensFlare(IntPtr thisPtr); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_setscreenSpaceLensFlare(IntPtr thisPtr, ScreenSpaceLensFlareSettings value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool Internal_getenableFXAA(IntPtr thisPtr); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_setenableFXAA(IntPtr thisPtr, bool value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern float Internal_getexposureScale(IntPtr thisPtr); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_setexposureScale(IntPtr thisPtr, float value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern float Internal_getgamma(IntPtr thisPtr); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_setgamma(IntPtr thisPtr, float value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool Internal_getenableHDR(IntPtr thisPtr); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_setenableHDR(IntPtr thisPtr, bool value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool Internal_getenableLighting(IntPtr thisPtr); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_setenableLighting(IntPtr thisPtr, bool value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool Internal_getenableShadows(IntPtr thisPtr); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_setenableShadows(IntPtr thisPtr, bool value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern ShadowSettings Internal_getshadowSettings(IntPtr thisPtr); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_setshadowSettings(IntPtr thisPtr, ShadowSettings value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool Internal_getenableIndirectLighting(IntPtr thisPtr); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_setenableIndirectLighting(IntPtr thisPtr, bool value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool Internal_getoverlayOnly(IntPtr thisPtr); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_setoverlayOnly(IntPtr thisPtr, bool value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool Internal_getenableSkybox(IntPtr thisPtr); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_setenableSkybox(IntPtr thisPtr, bool value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern float Internal_getcullDistance(IntPtr thisPtr); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_setcullDistance(IntPtr thisPtr, float value); } /** @} */ }
41.949868
124
0.772313
[ "MIT" ]
BugBiteSquared/bsf
Source/Scripting/bsfSharp/Generated/RenderSettings.generated.cs
15,899
C#
using System; namespace Visitor { class Program { static void Main(string[] args) { Sample.ObjectStructure structure = new Sample.ObjectStructure(); var tv1 = new Sample.Television(); tv1.Size = 100; tv1.State = 100; var tv2 = new Sample.Television(); tv2.State = 200; tv2.Size = 200; structure.Add(tv1); structure.Add(tv2); var computer1 = new Sample.Computer(); computer1.Size = 100; computer1.State = 100; var computer2 = new Sample.Computer(); computer2.State = 90; computer2.Size = 101; structure.Add(computer1); structure.Add(computer2); Sample.SizeVisitor sizeVisitor = new Sample.SizeVisitor(); Sample.StateVisitor stateVisitor = new Sample.StateVisitor(); structure.Operate(stateVisitor); structure.Operate(sizeVisitor); Console.Read(); } } }
22.702128
76
0.533271
[ "Apache-2.0" ]
Yang-Onion/DesignPatternDemos
DesignPatterns/Visitor/Program.cs
1,069
C#
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. */ using log4net; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using RecurringIntegrationsScheduler.Common.JobSettings; using RecurringIntegrationsScheduler.Common.Properties; using RecurringIntegrationsScheduler.Common.Contracts; using System; using System.IO; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using System.Web; using UrlCombineLib; namespace RecurringIntegrationsScheduler.Common.Helpers { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")] public class HttpClientHelper : IDisposable { private readonly Settings _settings; private readonly HttpClient _httpClient; private readonly AuthenticationHelper _authenticationHelper; private bool _disposed; /// <summary> /// The log /// </summary> private static readonly ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Initializes a new instance of the <see cref="HttpClientHelper"/> class. /// </summary> /// <param name="jobSettings">Job settings</param> public HttpClientHelper(Settings jobSettings) { log4net.Config.XmlConfigurator.Configure(); _settings = jobSettings; //Use Tls1.2 as default transport layer ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; var httpClientHandler = new HttpClientHandler { AllowAutoRedirect = false, UseCookies = false, AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }; _httpClient = new HttpClient(new HttpRetryHandler(httpClientHandler, _settings.RetryCount, _settings.RetryDelay)) { Timeout = TimeSpan.FromMinutes(60) //Timeout for large uploads or downloads }; _authenticationHelper = new AuthenticationHelper(_settings); if(_settings.LogVerbose || Log.IsDebugEnabled) { Log.Debug($@"Job: {_settings.JobKey}. HttpClientHelper was successfully initialized. Request retry count: {_settings.RetryCount}. Delay between retries: {_settings.RetryDelay} seconds."); } } /// <summary> /// Post request for files /// </summary> /// <param name="uri">Enqueue endpoint URI</param> /// <param name="bodyStream">Body stream</param> /// <param name="externalidentifier">ActivityMessage context</param> /// <returns></returns> public async Task<HttpResponseMessage> PostStreamRequestAsync(Uri uri, Stream bodyStream, string externalidentifier = null) { _httpClient.DefaultRequestHeaders.Clear(); _httpClient.DefaultRequestHeaders.Add("Authorization", await _authenticationHelper.GetValidAuthenticationHeader()); if (!string.IsNullOrEmpty(externalidentifier)) { _httpClient.DefaultRequestHeaders.Add("x-ms-dyn-externalidentifier", externalidentifier); } if (bodyStream != null) { if (_settings.LogVerbose || Log.IsDebugEnabled) { Log.Debug($@"Job: {_settings.JobKey}. HttpClientHelper.PostStreamRequestAsync is being called. Uri: {uri.AbsoluteUri}, Parameters: bodyStream is not null, externalidentifier: {externalidentifier}"); } return await _httpClient.PostAsync(uri, new StreamContent(bodyStream)); } else { Log.Error($"Job: {_settings.JobKey}. HttpClientHelper.PostStreamRequestAsync method was called with empty 'bodyStream' parameter."); return new HttpResponseMessage { Content = new StringContent(Resources.Request_failed_at_client, Encoding.ASCII), StatusCode = HttpStatusCode.PreconditionFailed }; } } /// <summary> /// Post request /// </summary> /// <param name="uri">Request Uri</param> /// <param name="bodyString">Body string</param> /// <param name="externalidentifier">Activity Message context</param> /// <returns>HTTP response</returns> public async Task<HttpResponseMessage> PostStringRequestAsync(Uri uri, string bodyString, string externalidentifier = null) { _httpClient.DefaultRequestHeaders.Clear(); _httpClient.DefaultRequestHeaders.Add("Authorization", await _authenticationHelper.GetValidAuthenticationHeader()); _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Add external correlation id header if specified and valid if (!string.IsNullOrEmpty(externalidentifier)) { _httpClient.DefaultRequestHeaders.Add("x-ms-dyn-externalidentifier", externalidentifier); } if (bodyString != null) { if (_settings.LogVerbose || Log.IsDebugEnabled) { Log.Debug($@"Job: {_settings.JobKey}. HttpClientHelper.PostStringRequestAsync is being called. Uri: {uri.AbsoluteUri}, Parameters: bodyString: {bodyString}, externalidentifier: {externalidentifier}"); } return await _httpClient.PostAsync(uri, new StringContent(bodyString, Encoding.UTF8, "application/json")); } else { Log.Error($"Job: {_settings.JobKey}. HttpClientHelper.PostStringRequestAsync method was called with empty 'bodyString' parameter."); return new HttpResponseMessage { Content = new StringContent(Resources.Request_failed_at_client, Encoding.ASCII), StatusCode = HttpStatusCode.PreconditionFailed }; } } /// <summary> /// Http Get request /// </summary> /// <param name="uri">Request Uri</param> /// <param name="addAuthorization">Add authorization header</param> /// <returns>Http response</returns> public async Task<HttpResponseMessage> GetRequestAsync(Uri uri, bool addAuthorization = true) { _httpClient.DefaultRequestHeaders.Clear(); if(addAuthorization) { _httpClient.DefaultRequestHeaders.Add("Authorization", await _authenticationHelper.GetValidAuthenticationHeader()); } if (_settings.LogVerbose || Log.IsDebugEnabled) { Log.Debug($@"Job: {_settings.JobKey}. HttpClientHelper.GetRequestAsync is being called. Uri: {uri.AbsoluteUri}, Parameters: addAuthorization: {addAuthorization}"); } return await _httpClient.GetAsync(uri); } /// <summary> /// Gets data job enqueue request Uri /// </summary> /// <returns> /// Data job enqueue request Uri /// </returns> public Uri GetEnqueueUri(string legalEntity = null) { var uploadSettings = _settings as UploadJobSettings; var enqueueUri = new UriBuilder(GetAosRequestUri(UrlCombine.Combine(ConnectorApiActions.EnqueuePath, uploadSettings.ActivityId.ToString()))); var query = HttpUtility.ParseQueryString(enqueueUri.Query); if (!string.IsNullOrEmpty(legalEntity)) { query["company"] = legalEntity; } else { if (!string.IsNullOrEmpty(uploadSettings.Company)) { query["company"] = uploadSettings.Company; } } if (!uploadSettings.IsDataPackage)// Individual file { // entity name is required query["entity"] = uploadSettings.EntityName; } if (_settings.LogVerbose || Log.IsDebugEnabled) { Log.Debug($@"Job: {_settings.JobKey}. HttpClientHelper.GetEnqueueUri is being called. Parameters: legalEntity: {legalEntity} Output: Generated Uri: {enqueueUri.Uri.AbsoluteUri} Generated query: {enqueueUri.Query}"); } enqueueUri.Query = query.ToString(); return enqueueUri.Uri; } /// <summary> /// Gets data job dequeue request Uri /// </summary> /// <returns> /// Data job dequeue request Uri /// </returns> public Uri GetDequeueUri() { var downloadSettings = _settings as DownloadJobSettings; var dequeueUri = new UriBuilder(GetAosRequestUri(UrlCombine.Combine(ConnectorApiActions.DequeuePath, downloadSettings.ActivityId.ToString()))).Uri; if (_settings.LogVerbose || Log.IsDebugEnabled) { Log.Debug($@"Job: {_settings.JobKey}. HttpClientHelper.GetDequeueUri is being called. Output: Generated Uri: {dequeueUri.AbsoluteUri}"); } return dequeueUri; } /// <summary> /// Gets file download acknowledgement request Uri /// </summary> /// <returns> /// File download acknowledgement request Uri /// </returns> public Uri GetAckUri() { var downloadSettings = _settings as DownloadJobSettings; var ackUri = new UriBuilder(GetAosRequestUri(UrlCombine.Combine(ConnectorApiActions.AckPath, downloadSettings.ActivityId.ToString()))).Uri; if (_settings.LogVerbose || Log.IsDebugEnabled) { Log.Debug($@"Job: {_settings.JobKey}. HttpClientHelper.GetAckUri is being called. Output: Generated Uri: {ackUri.AbsoluteUri}"); } return ackUri; } /// <summary> /// Gets data job status request URI /// </summary> /// <param name="jobId">The job identifier.</param> /// <returns> /// Data job status URI /// </returns> public Uri GetJobStatusUri(string jobId) { var processingJobSettings = _settings as ProcessingJobSettings; var jobStatusUri = new UriBuilder(GetAosRequestUri(UrlCombine.Combine(ConnectorApiActions.JobStatusPath, processingJobSettings.ActivityId.ToString()))) { Query = "jobId=" + jobId.Replace(@"""", "") }; if (_settings.LogVerbose || Log.IsDebugEnabled) { Log.Debug($@"Job: {_settings.JobKey}. HttpClientHelper.GetJobStatusUri is being called. Parameters: jobId: {jobId} Output: Generated uri: {jobStatusUri.Uri.AbsoluteUri} Generated query: {jobStatusUri.Query}"); } return jobStatusUri.Uri; } /// <summary> /// Gets temporary writable location /// </summary> /// <returns>temp writable cloud url</returns> public async Task<HttpResponseMessage> GetAzureWriteUrl() { var requestUri = GetAosRequestUri(_settings.GetAzureWriteUrlActionPath); string uniqueFileName = Guid.NewGuid().ToString(); var parameters = new { uniqueFileName }; string parametersJson = JsonConvert.SerializeObject(parameters, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto }); if (_settings.LogVerbose || Log.IsDebugEnabled) { Log.Debug($@"Job: {_settings.JobKey}. HttpClientHelper.GetAzureWriteUrl is being called. Uri: {requestUri} Parameters: uniqueFileName: {uniqueFileName}"); } var response = await PostStringRequestAsync(requestUri, parametersJson); if (!response.IsSuccessStatusCode) { Log.Error($@"Job: {_settings.JobKey}. HttpClientHelper.GetAzureWriteUrl request failed. Uri: {requestUri} Response status code: {response.StatusCode} Response reason: {response.ReasonPhrase} Response message: {response.Content}"); return null; } return response; } /// <summary> /// Checks execution status of a Job /// </summary> /// <param name="executionId">execution Id</param> /// <returns>Http response</returns> public async Task<HttpResponseMessage> GetExecutionSummaryStatus(string executionId) { var requestUri = GetAosRequestUri(_settings.GetExecutionSummaryStatusActionPath); var parameters = new { executionId }; string parametersJson = JsonConvert.SerializeObject(parameters, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto }); if (_settings.LogVerbose || Log.IsDebugEnabled) { Log.Debug($@"Job: {_settings.JobKey}. HttpClientHelper.GetExecutionSummaryStatus is being called. Uri: {requestUri} Parameters: executionId: {executionId}"); } var response = await PostStringRequestAsync(requestUri, parametersJson); if (!response.IsSuccessStatusCode) { Log.Error($@"Job: {_settings.JobKey}. HttpClientHelper.GetExecutionSummaryStatus request failed. Uri: {requestUri} Parameters: executionId: {executionId} Response status code: {response.StatusCode} Response reason: {response.ReasonPhrase} Response message: {response.Content}"); } return response; } /// <summary> /// Gets exported package Url location /// </summary> /// <param name="executionId">execution Id</param> /// <returns>Http response</returns> public async Task<HttpResponseMessage> GetExportedPackageUrl(string executionId) { var requestUri = GetAosRequestUri(_settings.GetExportedPackageUrlActionPath); var parameters = new { executionId }; string parametersJson = JsonConvert.SerializeObject(parameters, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto }); if (_settings.LogVerbose || Log.IsDebugEnabled) { Log.Debug($@"Job: {_settings.JobKey}. HttpClientHelper.GetExportedPackageUrl is being called. Uri: {requestUri} Parameters: executionId: {executionId}"); } var response = await PostStringRequestAsync(requestUri, parametersJson); if (!response.IsSuccessStatusCode) { Log.Error($@"Job: {_settings.JobKey}. HttpClientHelper.GetExportedPackageUrl request failed. Uri: {requestUri} Parameters: executionId: {executionId} Response status code: {response.StatusCode} Response reason: {response.ReasonPhrase} Response message: {response.Content}"); } return response; } /// <summary> /// Gets execution's summary page Url /// </summary> /// <param name="executionId">execution Id</param> /// <returns>Http response</returns> public async Task<HttpResponseMessage> GetExecutionSummaryPageUrl(string executionId) { var requestUri = GetAosRequestUri(_settings.GetExecutionSummaryPageUrlActionPath); var parameters = new { executionId }; string parametersJson = JsonConvert.SerializeObject(parameters, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto }); if (_settings.LogVerbose || Log.IsDebugEnabled) { Log.Debug($@"Job: {_settings.JobKey}. HttpClientHelper.GetExecutionSummaryPageUrl is being called. Uri: {requestUri} Parameters: executionId: {executionId}"); } var response = await PostStringRequestAsync(requestUri, parametersJson); if (!response.IsSuccessStatusCode) { Log.Error($@"Job: {_settings.JobKey}. HttpClientHelper.GetExecutionSummaryPageUrl request failed. Uri: {requestUri} Parameters: executionId: {executionId} Response status code: {response.StatusCode} Response reason: {response.ReasonPhrase} Response message: {response.Content}"); } return response; } /// <summary> /// Uploads package to a blob /// </summary> /// <param name="blobUrl">blob url</param> /// <param name="stream">bytes to write</param> /// <returns>HTTP response</returns> public async Task<HttpResponseMessage> UploadContentsToBlob(Uri blobUrl, Stream stream) { _httpClient.DefaultRequestHeaders.Clear(); _httpClient.DefaultRequestHeaders.Add("x-ms-date", DateTime.UtcNow.ToString("R", System.Globalization.CultureInfo.InvariantCulture)); _httpClient.DefaultRequestHeaders.Add("x-ms-blob-type", "BlockBlob"); _httpClient.DefaultRequestHeaders.Add("Overwrite", "T"); if (_settings.LogVerbose || Log.IsDebugEnabled) { Log.Debug($@"Job: {_settings.JobKey}. HttpClientHelper.UploadContentsToBlob is being called. Uri: {blobUrl.AbsoluteUri}"); } var response = await _httpClient.PutAsync(blobUrl.AbsoluteUri, new StreamContent(stream)); if (!response.IsSuccessStatusCode) { Log.Error($@"Job: {_settings.JobKey}. HttpClientHelper.UploadContentsToBlob request failed. Uri: {blobUrl.AbsoluteUri} Response status code: {response.StatusCode} Response reason: {response.ReasonPhrase} Response message: {response.Content}"); } return response; } /// <summary> /// Request to import package from specified location /// </summary> /// <param name="packageUrl">Location of uploaded package</param> /// <param name="definitionGroupId">Data project name</param> /// <param name="executionId">Execution Id</param> /// <param name="execute">Flag whether to execute import</param> /// <param name="overwrite">Flag whether to overwrite data project</param> /// <param name="legalEntityId">Target legal entity</param> /// <returns></returns> public async Task<HttpResponseMessage> ImportFromPackage(string packageUrl, string definitionGroupId, string executionId, bool execute, bool overwrite, string legalEntityId) { var requestUri = GetAosRequestUri(_settings.ImportFromPackageActionPath); var parameters = new { packageUrl, definitionGroupId, executionId, execute, overwrite, legalEntityId }; string parametersJson = JsonConvert.SerializeObject(parameters, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto }); if (_settings.LogVerbose || Log.IsDebugEnabled) { Log.Debug($@"Job: {_settings.JobKey}. HttpClientHelper.ImportFromPackage is being called. Uri: {requestUri} Parameters: packageUrl: {packageUrl} definitionGroupId: {definitionGroupId} executionId: {executionId} execute: {execute} overwrite: {overwrite} legalEntityId: {legalEntityId}"); } var response = await PostStringRequestAsync(requestUri, parametersJson); if (!response.IsSuccessStatusCode) { Log.Error($@"Job: {_settings.JobKey}. HttpClientHelper.ImportFromPackage request failed. Uri: {requestUri} Parameters: packageUrl: {packageUrl} definitionGroupId: {definitionGroupId} executionId: {executionId} execute: {execute} overwrite: {overwrite} legalEntityId: {legalEntityId} Response status code: {response.StatusCode} Response reason: {response.ReasonPhrase} Response message: {response.Content}"); } return response; } /// <summary> /// Delete Execution History /// </summary> /// <param name="executionId">execution Id</param> /// <returns></returns> public async Task<HttpResponseMessage> DeleteExecutionHistoryJob(string executionId) { var requestUri = GetAosRequestUri(_settings.DeleteExecutionHistoryJobActionPath); var parameters = new { executionId }; string parametersJson = JsonConvert.SerializeObject(parameters, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto }); if (_settings.LogVerbose || Log.IsDebugEnabled) { Log.Debug($@"Job: {_settings.JobKey}. HttpClientHelper.DeleteExecutionHistoryJob is being called. Uri: {requestUri} Parameters: executionId: {executionId}"); } var response = await PostStringRequestAsync(requestUri, parametersJson); if (!response.IsSuccessStatusCode) { Log.Error($@"Job: {_settings.JobKey}. HttpClientHelper.DeleteExecutionHistoryJob request failed. Uri: {requestUri} Parameters: executionId: {executionId} Response status code: {response.StatusCode} Response reason: {response.ReasonPhrase} Response message: {response.Content}"); } return response; } /// <summary> /// Export a package that has been already uploaded to server /// </summary> /// <param name="definitionGroupId">data project name</param> /// <param name="packageName">package name </param> /// <param name="executionId">execution id to use for results</param> /// <param name="legalEntityId">the company to pull</param> /// <param name="reExecute">reexecute flag</param> /// <returns>export package url</returns> public async Task<HttpResponseMessage> ExportToPackage(string definitionGroupId, string packageName, string executionId, string legalEntityId, bool reExecute = false) { var requestUri = GetAosRequestUri(_settings.ExportToPackageActionPath); var parameters = new { definitionGroupId, packageName, executionId, reExecute, legalEntityId }; string parametersJson = JsonConvert.SerializeObject(parameters, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto }); if (_settings.LogVerbose || Log.IsDebugEnabled) { Log.Debug($@"Job: {_settings.JobKey}. HttpClientHelper.ExportToPackage is being called. Uri: {requestUri} Parameters: definitionGroupId: {definitionGroupId} packageName: {packageName} executionId: {executionId} reExecute: {reExecute} legalEntityId: {legalEntityId}"); } var response = await PostStringRequestAsync(requestUri, parametersJson); if (!response.IsSuccessStatusCode) { Log.Error($@"Job: {_settings.JobKey}. HttpClientHelper.ExportToPackage request failed. Uri: {requestUri} Parameters: definitionGroupId: {definitionGroupId} packageName: {packageName} executionId: {executionId} reExecute: {reExecute} legalEntityId: {legalEntityId} Response status code: {response.StatusCode} Response reason: {response.ReasonPhrase} Response message: {response.Content}"); } return response; } /// <summary> /// Upload a package template and export data based on that template /// </summary> /// <param name="packageUrl">Location of uploaded package template</param> /// <param name="definitionGroupId">Data project name</param> /// <param name="executionId">Execution Id</param> /// <param name="execute">Flag whether to execute export</param> /// <param name="overwrite">Flag whether to overwrite data project</param> /// <param name="legalEntityId">Source legal entity</param> /// <returns>export package url</returns> public async Task<HttpResponseMessage> ExportFromPackage(string packageUrl, string definitionGroupId, string executionId, bool execute, bool overwrite, string legalEntityId) { var requestUri = GetAosRequestUri(_settings.ExportFromPackageActionPath); var parameters = new { packageUrl, definitionGroupId, executionId, execute, overwrite, legalEntityId }; string parametersJson = JsonConvert.SerializeObject(parameters, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto }); if (_settings.LogVerbose || Log.IsDebugEnabled) { Log.Debug($@"Job: {_settings.JobKey}. HttpClientHelper.ExportFromPackage is being called. Uri: {requestUri} Parameters: packageUrl: {packageUrl} definitionGroupId: {definitionGroupId} executionId: {executionId} execute: {execute} overwrite: {overwrite} legalEntityId: {legalEntityId}"); } var response = await PostStringRequestAsync(requestUri, parametersJson); if (!response.IsSuccessStatusCode) { Log.Error($@"Job: {_settings.JobKey}. HttpClientHelper.ExportFromPackage request failed. Uri: {requestUri} Parameters: packageUrl: {packageUrl} definitionGroupId: {definitionGroupId} executionId: {executionId} execute: {execute} overwrite: {overwrite} legalEntityId: {legalEntityId} Response status code: {response.StatusCode} Response reason: {response.ReasonPhrase} Response message: {response.Content}"); } return response; } /// <summary> /// Get message status /// </summary> /// <param name="messageId">Message Id</param> /// <returns></returns> public async Task<HttpResponseMessage> GetMessageStatus(string messageId) { var requestUri = GetAosRequestUri(_settings.GetMessageStatusActionPath); var parameters = new { messageId }; string parametersJson = JsonConvert.SerializeObject(parameters, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto }); if (_settings.LogVerbose || Log.IsDebugEnabled) { Log.Debug($@"Job: {_settings.JobKey}. HttpClientHelper.GetMessageStatus is being called. Uri: {requestUri} Parameters: messageId: {messageId}"); } var response = await PostStringRequestAsync(requestUri, parametersJson); if (!response.IsSuccessStatusCode) { Log.Error($@"Job: {_settings.JobKey}. HttpClientHelper.GetMessageStatus request failed. Uri: {requestUri} Parameters: messageId: {messageId} Response status code: {response.StatusCode} Response reason: {response.ReasonPhrase} Response message: {response.Content}"); } return response; } /// <summary> /// Generate error keys file for data entity import /// </summary> /// <param name="executionId">Execution Id</param> /// <param name="entityName">Entity name</param> /// <returns></returns> public async Task<HttpResponseMessage> GenerateImportTargetErrorKeysFile(string executionId, string entityName) { var requestUri = GetAosRequestUri(_settings.GenerateImportTargetErrorKeysFilePath); var parameters = new { executionId, entityName }; string parametersJson = JsonConvert.SerializeObject(parameters, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto }); if (_settings.LogVerbose || Log.IsDebugEnabled) { Log.Debug($@"Job: {_settings.JobKey}. HttpClientHelper.GenerateImportTargetErrorKeysFile is being called. Uri: {requestUri} Parameters: executionId: {executionId} entityName: {entityName}"); } var response = await PostStringRequestAsync(requestUri, parametersJson); if (!response.IsSuccessStatusCode) { Log.Error($@"Job: {_settings.JobKey}. HttpClientHelper.GenerateImportTargetErrorKeysFile request failed. Uri: {requestUri} Parameters: executionId: {executionId} entityName: {entityName} Response status code: {response.StatusCode} Response reason: {response.ReasonPhrase} Response message: {response.Content}"); } return response; } /// <summary> /// Get error keys file URL for data entity import /// </summary> /// <param name="executionId">Execution Id</param> /// <param name="entityName">Entity name</param> /// <returns></returns> public async Task<HttpResponseMessage> GetImportTargetErrorKeysFileUrl(string executionId, string entityName) { var requestUri = GetAosRequestUri(_settings.GetImportTargetErrorKeysFileUrlPath); var parameters = new { executionId, entityName }; string parametersJson = JsonConvert.SerializeObject(parameters, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto }); if (_settings.LogVerbose || Log.IsDebugEnabled) { Log.Debug($@"Job: {_settings.JobKey}. HttpClientHelper.GetImportTargetErrorKeysFileUrl is being called. Uri: {requestUri} Parameters: executionId: {executionId} entityName: {entityName}"); } var response = await PostStringRequestAsync(requestUri, parametersJson); if (!response.IsSuccessStatusCode) { Log.Error($@"Job: {_settings.JobKey}. HttpClientHelper.GetImportTargetErrorKeysFileUrl request failed. Uri: {requestUri} Parameters: executionId: {executionId} entityName: {entityName} Response status code: {response.StatusCode} Response reason: {response.ReasonPhrase} Response message: {response.Content}"); } return response; } /// <summary> /// Get execution errors /// </summary> /// <param name="executionId">Execution Id</param> /// <returns></returns> public async Task<HttpResponseMessage> GetExecutionErrors(string executionId) { var requestUri = GetAosRequestUri(_settings.GetExecutionErrorsPath); var parameters = new { executionId }; string parametersJson = JsonConvert.SerializeObject(parameters, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto }); if (_settings.LogVerbose || Log.IsDebugEnabled) { Log.Debug($@"Job: {_settings.JobKey}. HttpClientHelper.GetExecutionErrors is being called. Uri: {requestUri} Parameters: executionId: {executionId}"); } var response = await PostStringRequestAsync(requestUri, parametersJson); if (!response.IsSuccessStatusCode) { Log.Error($@"Job: {_settings.JobKey}. HttpClientHelper.GetExecutionErrors request failed. Uri: {requestUri} Parameters: executionId: {executionId} Response status code: {response.StatusCode} Response reason: {response.ReasonPhrase} Response message: {response.Content}"); } return response; } private Uri GetAosRequestUri(string requestRelativePath)         { var aosUrl = UrlCombine.Combine(_settings.AosUri, requestRelativePath); var aosUri = new Uri(aosUrl);             return aosUri;         } public static string ReadResponseString(HttpResponseMessage response) { string result = response.Content.ReadAsStringAsync().Result; JObject jsonResponse = (JObject)JsonConvert.DeserializeObject(result); return jsonResponse["value"].ToString(); } /// <summary> /// Dispose /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Dispose /// </summary> /// <param name="disposing">enable dispose</param> protected virtual void Dispose(bool disposing) { if (_disposed) return; _disposed = true; if (disposing) { _httpClient?.Dispose(); } } } }
37.083805
181
0.632494
[ "MIT" ]
Bhaskers-Blu-Org2/Recurring-Integrations-Scheduler
Common/Helpers/HttpClientHelper.cs
32,797
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="MaybeThrowsTests.cs" company="Daniel Franklin"> // Copyright © 2017 Daniel Franklin. // </copyright> // <license> // 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. // </license> // -------------------------------------------------------------------------------------------------------------------- // ReSharper disable InconsistentNaming namespace Franklin.Maybe { using System; using Xunit; public class MaybeThrowsTests { [Fact] public void None_is_type_of_MaybeThrows() { Assert.IsType<MaybeThrows<TestClass>>(MaybeThrows<TestClass>.None); } [Fact] public void None_HasValue_should_be_false() { MaybeThrows<TestClass> maybe = MaybeThrows<TestClass>.None; Assert.False(maybe.HasValue); } [Fact] public void Has_is_type_of_MaybeThrows() { Assert.IsType<MaybeThrows<TestClass>>(MaybeThrows<TestClass>.Has(new TestClass())); } [Fact] public void Has_HasValue_should_be_true() { MaybeThrows<TestClass> maybe = MaybeThrows<TestClass>.Has(new TestClass()); Assert.True(maybe.HasValue); } [Fact] public void Has_Value_should_equal_set_value() { TestClass testClass = new TestClass(); MaybeThrows<TestClass> maybe = MaybeThrows<TestClass>.Has(testClass); Assert.Equal(testClass, maybe.Value); } [Fact] public void Has_set_to_null_throws_NullReferenceException() { Assert.Throws<NullReferenceException>(() => MaybeThrows<TestClass>.Has(null)); } [Fact] public void When_MaybeThrows_used_incorrectly_HasValue_should_return_false() { MaybeThrows<TestClass> maybe = new MaybeThrows<TestClass>(); Assert.False(maybe.HasValue); } [Fact] public void Cast_to_MaybeThrows_T_should_return_HasValue_true() { TestClass testClass = new TestClass(); MaybeThrows<TestClass> maybe = (MaybeThrows<TestClass>)testClass; Assert.True(maybe.HasValue); } [Fact] public void Cast_to_MaybeThrows_T_should_return_set_value() { TestClass testClass = new TestClass(); MaybeThrows<TestClass> maybe = (MaybeThrows<TestClass>)testClass; Assert.Equal(testClass, maybe.Value); } [Fact] public void Cast_to_null_throws_NullReferenceException() { Assert.Throws<NullReferenceException>(() => (MaybeThrows<TestClass>)null); } [Fact] public void MaybeThrows_cast_to_T_should_return_value_of_T() { TestClass testClass = new TestClass(); MaybeThrows<TestClass> maybe = MaybeThrows<TestClass>.Has(testClass); TestClass returned = (TestClass)maybe; Assert.Equal(testClass, returned); } [Fact] public void Equals_should_compare_values() { string value1 = "1"; string value2 = "1"; string value3 = "2"; MaybeThrows<string> maybe1 = MaybeThrows<string>.Has(value1); MaybeThrows<string> maybe2 = MaybeThrows<string>.Has(value2); MaybeThrows<string> maybe3 = MaybeThrows<string>.Has(value3); bool result1 = maybe1.Equals(maybe2); bool result2 = maybe2.Equals(maybe3); Assert.True(result1); Assert.False(result2); } [Fact] public void Equals_should_return_false_if_HasValue_false_and_HasValue_true_even_if_values_are_equal() { MaybeThrows<int> maybe1 = MaybeThrows<int>.Has(0); MaybeThrows<int> maybe2 = MaybeThrows<int>.None; bool result = maybe1.Equals(maybe2); Assert.False(result); } [Fact] public void MaybeThrows_None_and_MaybeThrows_None_are_equal() { MaybeThrows<TestClass> maybe1 = MaybeThrows<TestClass>.None; MaybeThrows<TestClass> maybe2 = MaybeThrows<TestClass>.None; bool result = maybe1.Equals(maybe2); Assert.True(result); } [Fact] public void Do_not_throw_on_abuse_of_Equals() { MaybeThrows<TestClass> maybe1 = MaybeThrows<TestClass>.None; // ReSharper disable once SuspiciousTypeConversion.Global bool result = maybe1.Equals("Bad"); Assert.False(result); } [Fact] public void Equality_operator_should_compare_values() { string value1 = "1"; string value2 = "1"; string value3 = "2"; MaybeThrows<string> maybe1 = MaybeThrows<string>.Has(value1); MaybeThrows<string> maybe2 = MaybeThrows<string>.Has(value2); MaybeThrows<string> maybe3 = MaybeThrows<string>.Has(value3); bool results1 = maybe1 == maybe2; bool results2 = maybe2 == maybe3; Assert.True(results1); Assert.False(results2); } [Fact] public void Non_equality_operator_should_compare_values() { string value1 = "1"; string value2 = "2"; string value3 = "2"; MaybeThrows<string> maybe1 = MaybeThrows<string>.Has(value1); MaybeThrows<string> maybe2 = MaybeThrows<string>.Has(value2); MaybeThrows<string> maybe3 = MaybeThrows<string>.Has(value3); bool results1 = maybe1 != maybe2; bool results2 = maybe2 != maybe3; Assert.True(results1); Assert.False(results2); } [Fact] public void ToString_with_HasValue_false_returns_empty_string() { MaybeThrows<string> maybe2 = MaybeThrows<string>.None; Assert.Equal(string.Empty, maybe2.ToString()); } [Fact] public void ToString_with_HasValue_true_returns_value_as_string() { MaybeThrows<string> maybe = MaybeThrows<string>.Has("Hello"); Assert.Equal("Hello", maybe.ToString()); } [Fact] public void ToDebugString_returns_debug_string() { MaybeThrows<string> maybe2 = MaybeThrows<string>.None; MaybeThrows<string> maybe3 = MaybeThrows<string>.Has("test"); Assert.Equal("HasValue: False, Value: ", maybe2.ToDebugString()); Assert.Equal("HasValue: True, Value: test", maybe3.ToDebugString()); } private class TestClass { } } }
33.57265
153
0.598269
[ "MIT" ]
JTOne123/Franklin.Maybe
Franklin.Maybe.Tests/MaybeThrowsTests.cs
7,859
C#
//----------------------------------------------------------------------- // <copyright file="SQArray.cs" company="None"> // Copyright (c) IIHOSHI Yoshinori. // Licensed under the BSD-2-Clause license. See LICENSE.txt file in the project root for full license information. // </copyright> //----------------------------------------------------------------------- #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member namespace ReimuPlugins.Common.Squirrel { using System; using System.Collections.Generic; using System.IO; using System.Linq; using ReimuPlugins.Common.Properties; public sealed class SQArray : SQObject { public SQArray() : this(Array.Empty<SQObject>()) { } public SQArray(IEnumerable<SQObject> enumerable) : base(SQObjectType.Array) { this.Value = enumerable; } public new IEnumerable<SQObject> Value { get => base.Value as IEnumerable<SQObject>; private set => base.Value = value.ToArray(); } public static SQArray Create(BinaryReader reader, bool skipType = false) { if (reader is null) { throw new ArgumentNullException(nameof(reader)); } if (!skipType) { var type = reader.ReadInt32(); if (type != (int)SQObjectType.Array) { throw new InvalidDataException(Resources.InvalidDataExceptionWrongType); } } var num = reader.ReadInt32(); if (num < 0) { throw new InvalidDataException(Resources.InvalidDataExceptionNumElementsMustNotBeNegative); } var array = new SQArray(new SQObject[num]); for (var count = 0; count < num; count++) { var index = SQObject.Create(reader); var value = SQObject.Create(reader); if (index is not SQInteger i) { throw new InvalidDataException(Resources.InvalidDataExceptionIndexMustBeAnInteger); } if (i >= num) { throw new InvalidDataException(Resources.InvalidDataExceptionIndexIsOutOfRange); } ((array as SQObject).Value as SQObject[])[i] = value; } var sentinel = SQObject.Create(reader); return sentinel is SQNull ? array : throw new InvalidDataException(Resources.InvalidDataExceptionWrongSentinel); } } }
31.8
114
0.525712
[ "BSD-2-Clause" ]
y-iihoshi/REIMU_Plugins_V2
Common/Squirrel/SQArray.cs
2,705
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Security { /// <summary> /// IoT Security solution configuration and resource information. /// API Version: 2019-08-01. /// </summary> [AzureNativeResourceType("azure-native:security:IotSecuritySolution")] public partial class IotSecuritySolution : Pulumi.CustomResource { /// <summary> /// List of additional workspaces /// </summary> [Output("additionalWorkspaces")] public Output<ImmutableArray<Outputs.AdditionalWorkspacesPropertiesResponse>> AdditionalWorkspaces { get; private set; } = null!; /// <summary> /// List of resources that were automatically discovered as relevant to the security solution. /// </summary> [Output("autoDiscoveredResources")] public Output<ImmutableArray<string>> AutoDiscoveredResources { get; private set; } = null!; /// <summary> /// Disabled data sources. Disabling these data sources compromises the system. /// </summary> [Output("disabledDataSources")] public Output<ImmutableArray<string>> DisabledDataSources { get; private set; } = null!; /// <summary> /// Resource display name. /// </summary> [Output("displayName")] public Output<string> DisplayName { get; private set; } = null!; /// <summary> /// List of additional options for exporting to workspace data. /// </summary> [Output("export")] public Output<ImmutableArray<string>> Export { get; private set; } = null!; /// <summary> /// IoT Hub resource IDs /// </summary> [Output("iotHubs")] public Output<ImmutableArray<string>> IotHubs { get; private set; } = null!; /// <summary> /// The resource location. /// </summary> [Output("location")] public Output<string?> Location { get; private set; } = null!; /// <summary> /// Resource name /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// List of the configuration status for each recommendation type. /// </summary> [Output("recommendationsConfiguration")] public Output<ImmutableArray<Outputs.RecommendationConfigurationPropertiesResponse>> RecommendationsConfiguration { get; private set; } = null!; /// <summary> /// Status of the IoT Security solution. /// </summary> [Output("status")] public Output<string?> Status { get; private set; } = null!; /// <summary> /// Azure Resource Manager metadata containing createdBy and modifiedBy information. /// </summary> [Output("systemData")] public Output<Outputs.SystemDataResponse> SystemData { get; private set; } = null!; /// <summary> /// Resource tags /// </summary> [Output("tags")] public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!; /// <summary> /// Resource type /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Unmasked IP address logging status /// </summary> [Output("unmaskedIpLoggingStatus")] public Output<string?> UnmaskedIpLoggingStatus { get; private set; } = null!; /// <summary> /// Properties of the IoT Security solution's user defined resources. /// </summary> [Output("userDefinedResources")] public Output<Outputs.UserDefinedResourcesPropertiesResponse?> UserDefinedResources { get; private set; } = null!; /// <summary> /// Workspace resource ID /// </summary> [Output("workspace")] public Output<string?> Workspace { get; private set; } = null!; /// <summary> /// Create a IotSecuritySolution resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public IotSecuritySolution(string name, IotSecuritySolutionArgs args, CustomResourceOptions? options = null) : base("azure-native:security:IotSecuritySolution", name, args ?? new IotSecuritySolutionArgs(), MakeResourceOptions(options, "")) { } private IotSecuritySolution(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-native:security:IotSecuritySolution", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:security:IotSecuritySolution"}, new Pulumi.Alias { Type = "azure-native:security/v20170801preview:IotSecuritySolution"}, new Pulumi.Alias { Type = "azure-nextgen:security/v20170801preview:IotSecuritySolution"}, new Pulumi.Alias { Type = "azure-native:security/v20190801:IotSecuritySolution"}, new Pulumi.Alias { Type = "azure-nextgen:security/v20190801:IotSecuritySolution"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing IotSecuritySolution resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static IotSecuritySolution Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new IotSecuritySolution(name, id, options); } } public sealed class IotSecuritySolutionArgs : Pulumi.ResourceArgs { [Input("additionalWorkspaces")] private InputList<Inputs.AdditionalWorkspacesPropertiesArgs>? _additionalWorkspaces; /// <summary> /// List of additional workspaces /// </summary> public InputList<Inputs.AdditionalWorkspacesPropertiesArgs> AdditionalWorkspaces { get => _additionalWorkspaces ?? (_additionalWorkspaces = new InputList<Inputs.AdditionalWorkspacesPropertiesArgs>()); set => _additionalWorkspaces = value; } [Input("disabledDataSources")] private InputList<Union<string, Pulumi.AzureNative.Security.DataSource>>? _disabledDataSources; /// <summary> /// Disabled data sources. Disabling these data sources compromises the system. /// </summary> public InputList<Union<string, Pulumi.AzureNative.Security.DataSource>> DisabledDataSources { get => _disabledDataSources ?? (_disabledDataSources = new InputList<Union<string, Pulumi.AzureNative.Security.DataSource>>()); set => _disabledDataSources = value; } /// <summary> /// Resource display name. /// </summary> [Input("displayName", required: true)] public Input<string> DisplayName { get; set; } = null!; [Input("export")] private InputList<Union<string, Pulumi.AzureNative.Security.ExportData>>? _export; /// <summary> /// List of additional options for exporting to workspace data. /// </summary> public InputList<Union<string, Pulumi.AzureNative.Security.ExportData>> Export { get => _export ?? (_export = new InputList<Union<string, Pulumi.AzureNative.Security.ExportData>>()); set => _export = value; } [Input("iotHubs", required: true)] private InputList<string>? _iotHubs; /// <summary> /// IoT Hub resource IDs /// </summary> public InputList<string> IotHubs { get => _iotHubs ?? (_iotHubs = new InputList<string>()); set => _iotHubs = value; } /// <summary> /// The resource location. /// </summary> [Input("location")] public Input<string>? Location { get; set; } [Input("recommendationsConfiguration")] private InputList<Inputs.RecommendationConfigurationPropertiesArgs>? _recommendationsConfiguration; /// <summary> /// List of the configuration status for each recommendation type. /// </summary> public InputList<Inputs.RecommendationConfigurationPropertiesArgs> RecommendationsConfiguration { get => _recommendationsConfiguration ?? (_recommendationsConfiguration = new InputList<Inputs.RecommendationConfigurationPropertiesArgs>()); set => _recommendationsConfiguration = value; } /// <summary> /// The name of the resource group within the user's subscription. The name is case insensitive. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; /// <summary> /// The name of the IoT Security solution. /// </summary> [Input("solutionName")] public Input<string>? SolutionName { get; set; } /// <summary> /// Status of the IoT Security solution. /// </summary> [Input("status")] public InputUnion<string, Pulumi.AzureNative.Security.SecuritySolutionStatus>? Status { get; set; } [Input("tags")] private InputMap<string>? _tags; /// <summary> /// Resource tags /// </summary> public InputMap<string> Tags { get => _tags ?? (_tags = new InputMap<string>()); set => _tags = value; } /// <summary> /// Unmasked IP address logging status /// </summary> [Input("unmaskedIpLoggingStatus")] public InputUnion<string, Pulumi.AzureNative.Security.UnmaskedIpLoggingStatus>? UnmaskedIpLoggingStatus { get; set; } /// <summary> /// Properties of the IoT Security solution's user defined resources. /// </summary> [Input("userDefinedResources")] public Input<Inputs.UserDefinedResourcesPropertiesArgs>? UserDefinedResources { get; set; } /// <summary> /// Workspace resource ID /// </summary> [Input("workspace")] public Input<string>? Workspace { get; set; } public IotSecuritySolutionArgs() { Status = "Enabled"; UnmaskedIpLoggingStatus = "Disabled"; } } }
39.823729
152
0.609806
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Security/IotSecuritySolution.cs
11,748
C#
using EventBus.Messages.Common; using MassTransit; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.OpenApi.Models; using Ordering.API.EventBusConsumer; using Ordering.Application; using Ordering.Infrastructure; namespace Ordering.API { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddApplicationServices(); services.AddInfrastructureServices(Configuration); services.AddMassTransit(config => { config.AddConsumer<BasketCheckoutConsumer>(); config.UsingRabbitMq((ctx, cfg) => { cfg.Host(Configuration["EventBusSettings:HostAddress"]); cfg.ReceiveEndpoint(EventBusConstants.BasketCheckoutQueue, c => { c.ConfigureConsumer<BasketCheckoutConsumer>(ctx); }); }); }); services.AddMassTransitHostedService(); services.AddAutoMapper(typeof(Startup)); services.AddScoped<BasketCheckoutConsumer>(); services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Ordering.API", Version = "v1" }); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Ordering.API v1")); } app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
32.078947
106
0.59557
[ "MIT" ]
Ussef96/AspnetMicroservices
src/Services/Ordering/Ordering.API/Startup.cs
2,440
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace EzClean { public partial class EzClean : Form { // Constantes needed to move the window private const int WM_NCHITTEST = 0x84; private const int HT_CLIENT = 0x1; private const int HT_CAPTION = 0x2; // Drive letter const string DRIVERLETTER = "c:"; // import Shell32.dll [DllImport("Shell32.dll", CharSet = CharSet.Unicode)] static extern uint SHEmptyRecycleBin(IntPtr hwnd, string pszRootPath, RecycleFlags dwFlags); // user folder string userFolder = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile).ToString(); // Directories that can be cleared List<DirectoryInfo> totalDirectories = new List<DirectoryInfo>(); // Directories that will be cleared List<bool> directoriesToClear = new List<bool>(); // Constructor public EzClean() { InitializeComponent(); } enum RecycleFlags : uint { SHRB_NOCONFIRMATION = 0x00000001, // Don't ask confirmation SHRB_NOPROGRESSUI = 0x00000002, // Don't show any windows dialog SHRB_NOSOUND = 0x00000004 // Don't make sound } // Allows moving window protected override void WndProc(ref Message m) { base.WndProc(ref m); if (m.Msg == WM_NCHITTEST) m.Result = (IntPtr)(HT_CAPTION); } // Load private void EzClean_Load(object sender, EventArgs e) { // ProgressBar to 0 circularProgressBar.Value = 0; // Brings btnClean to front btnClean.BringToFront(); // Fills directories with paths fillDirectories(); // Fills the list with true values as many as existing paths bool clear = true; for (int i = 0; i < totalDirectories.Count() + 1; i++) { directoriesToClear.Add(clear); } } // Clean click private void btnClean_Click(object sender, EventArgs e) { // Brings progress bar to front circularProgressBar.BringToFront(); // Progress bar to 0 circularProgressBar.Value = 0; // Changes button image this.BackgroundImage = Properties.Resources.MainScreen; // Cleaning function clean(); // Cleaning finished progress.Text = "Finished"; // Sends progress bar to back circularProgressBar.SendToBack(); // Changes button image this.BackgroundImage = Properties.Resources.buttonUnpressed; } // Cleans directories private void clean() { try { if (directoriesToClear[10]) { // Cleans Recycle Bin uint IsSuccess = SHEmptyRecycleBin(IntPtr.Zero, null, RecycleFlags.SHRB_NOCONFIRMATION); } // For every dir in dirs list for (int i = 0; i < totalDirectories.Count(); i++) { // If the position is true (checkbox from settings = true) if (directoriesToClear[i]) { try { // Method cleanDir cleanDir(totalDirectories[i]); } catch (Exception) { } } // Progress bar advance and refresh circularProgressBar.PerformStep(); circularProgressBar.Refresh(); // Shows progress into the label progress.Text = i.ToString() + "0 %"; } } catch (Exception ex) { // Handle exceptions MessageBox.Show(ex.Message, "Error while cleaning", MessageBoxButtons.OK, MessageBoxIcon.Stop); } } // Deletes all folders and files inside a directory private void cleanDir(DirectoryInfo dir) { foreach (FileInfo file in dir.GetFiles()) { // Deletes file try{file.Delete();} catch (Exception){} } foreach (DirectoryInfo directory in dir.GetDirectories()) { // Delete directory try{directory.Delete(true);} catch (Exception){} } } // Close program private void pictureBoxClose_Click(object sender, EventArgs e) { // Close program this.Close(); } // Click in settings private void pictureBoxSettings_Click(object sender, EventArgs e) { // Opens settings Settings settings = new Settings(directoriesToClear); settings.ShowDialog(); } // Fills totalDirectories list with paths to be cleared private void fillDirectories() { // Directories to be cleared DirectoryInfo dir = new DirectoryInfo(userFolder + "\\temp"); DirectoryInfo dir2 = new DirectoryInfo(DRIVERLETTER + "\\temp"); DirectoryInfo dir3 = new DirectoryInfo(DRIVERLETTER + "\\Windows\\SoftwareDistribution"); DirectoryInfo dir4 = new DirectoryInfo(userFolder + "\\AppData\\Local\\Microsoft\\Windows\\Temporary Internet Files"); DirectoryInfo dir5 = new DirectoryInfo(userFolder + "\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Cache"); DirectoryInfo dir6 = new DirectoryInfo(DRIVERLETTER + "\\Windows.old"); DirectoryInfo dir7 = new DirectoryInfo(DRIVERLETTER + "\\Windows\\LiveKernelReports"); DirectoryInfo dir8 = new DirectoryInfo(DRIVERLETTER + "\\Windows\\Prefetch"); DirectoryInfo dir9 = new DirectoryInfo(DRIVERLETTER + "\\ProgramData\\Microsoft\\Windows\\WER"); DirectoryInfo dir10 = new DirectoryInfo(DRIVERLETTER + "\\Windows\\Minidump"); // Adding dirs to dirsToClear list totalDirectories.Add(dir); totalDirectories.Add(dir2); totalDirectories.Add(dir3); totalDirectories.Add(dir4); totalDirectories.Add(dir5); totalDirectories.Add(dir6); totalDirectories.Add(dir7); totalDirectories.Add(dir8); totalDirectories.Add(dir9); totalDirectories.Add(dir10); } } }
33.694836
133
0.538387
[ "MIT" ]
Marc-Ferrer-Castillo/EzClean
EzClean/EzClean.cs
7,179
C#
#pragma checksum "C:\Users\lord\source\repos\HostelOsis\HostelOsis\Views\Home\Index.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "02934233ff56c353e34e8a11f2ee62950b0cab0f" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Home_Index), @"mvc.1.0.view", @"/Views/Home/Index.cshtml")] [assembly:global::Microsoft.AspNetCore.Mvc.Razor.Compilation.RazorViewAttribute(@"/Views/Home/Index.cshtml", typeof(AspNetCore.Views_Home_Index))] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #line 1 "C:\Users\lord\source\repos\HostelOsis\HostelOsis\Views\_ViewImports.cshtml" using HostelOsis; #line default #line hidden #line 2 "C:\Users\lord\source\repos\HostelOsis\HostelOsis\Views\_ViewImports.cshtml" using HostelOsis.Models; #line default #line hidden [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"02934233ff56c353e34e8a11f2ee62950b0cab0f", @"/Views/Home/Index.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"38a62d4ac718b57047a8c31186d764b8729d2959", @"/Views/_ViewImports.cshtml")] public class Views_Home_Index : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<IEnumerable<HostelOsis.Models.ViewModel.OccupantViewModel>> { private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("href", new global::Microsoft.AspNetCore.Html.HtmlString("~/Hashboard/vendor/fontawesome-free/css/all.min.css"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("rel", new global::Microsoft.AspNetCore.Html.HtmlString("stylesheet"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("type", new global::Microsoft.AspNetCore.Html.HtmlString("text/css"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("href", new global::Microsoft.AspNetCore.Html.HtmlString("~/Hashboard/css/sb-admin-2.min.css"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", new global::Microsoft.AspNetCore.Html.HtmlString("~/Hashboard/vendor/jquery/jquery.min.js"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_5 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", new global::Microsoft.AspNetCore.Html.HtmlString("~/Hashboard/vendor/bootstrap/js/bootstrap.bundle.min.js"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_6 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", new global::Microsoft.AspNetCore.Html.HtmlString("~/Hashboard/vendor/jquery-easing/jquery.easing.min.js"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_7 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", new global::Microsoft.AspNetCore.Html.HtmlString("~/Hashboard/js/sb-admin-2.min.js"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_8 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", new global::Microsoft.AspNetCore.Html.HtmlString("~/Hashboard/vendor/chart.js/Chart.min.js"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_9 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", new global::Microsoft.AspNetCore.Html.HtmlString("~/Hashboard/js/demo/chart-area-demo.js"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_10 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", new global::Microsoft.AspNetCore.Html.HtmlString("~/Hashboard/js/demo/chart-pie-demo.js"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_11 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("id", new global::Microsoft.AspNetCore.Html.HtmlString("page-top"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); #line hidden #pragma warning disable 0169 private string __tagHelperStringValueBuffer; #pragma warning restore 0169 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner(); private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager { get { if (__backed__tagHelperScopeManager == null) { __backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); } return __backed__tagHelperScopeManager; } } private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.HeadTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_HeadTagHelper; private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper; private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.BodyTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_BodyTagHelper; #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { BeginContext(67, 2, true); WriteLiteral("\r\n"); EndContext(); #line 3 "C:\Users\lord\source\repos\HostelOsis\HostelOsis\Views\Home\Index.cshtml" ViewData["Title"] = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; #line default #line hidden BeginContext(157, 39, true); WriteLiteral("\r\n<!DOCTYPE html>\r\n<html lang=\"en\">\r\n\r\n"); EndContext(); BeginContext(196, 736, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("head", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "02934233ff56c353e34e8a11f2ee62950b0cab0f8324", async() => { BeginContext(202, 357, true); WriteLiteral(@" <meta charset=""utf-8""> <meta http-equiv=""X-UA-Compatible"" content=""IE=edge""> <meta name=""viewport"" content=""width=device-width, initial-scale=1, shrink-to-fit=no""> <meta name=""description"" content=""""> <meta name=""author"" content=""""> <title>SB Admin 2 - Dashboard</title> <!-- Custom fonts for this template--> "); EndContext(); BeginContext(559, 98, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("link", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagOnly, "02934233ff56c353e34e8a11f2ee62950b0cab0f9079", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(657, 199, true); WriteLiteral("\r\n <link href=\"https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i\" rel=\"stylesheet\">\r\n\r\n <!-- Custom styles for this template-->\r\n "); EndContext(); BeginContext(856, 65, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("link", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagOnly, "02934233ff56c353e34e8a11f2ee62950b0cab0f10704", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_3); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(921, 4, true); WriteLiteral("\r\n\r\n"); EndContext(); } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_HeadTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.HeadTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_HeadTagHelper); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(932, 2, true); WriteLiteral("\r\n"); EndContext(); BeginContext(934, 8889, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("body", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "02934233ff56c353e34e8a11f2ee62950b0cab0f12839", async() => { BeginContext(954, 8151, true); WriteLiteral(@" <div id=""wrapper""> <!-- Earnings (Monthly) Card Example --> <div class=""col-xl-3 col-md-6 mb-4""> <div class=""card border-left-primary shadow h-100 py-2""> <div class=""card-body""> <div class=""row no-gutters align-items-center""> <div class=""col mr-2""> <div class=""text-xs font-weight-bold text-primary text-uppercase mb-1"">Occupants</div> <div class=""h5 mb-0 font-weight-bold text-gray-800"">10</div> </div> <div class=""col-auto""> <i class=""fas fa-calendar fa-2x text-gray-300""></i> </div> </div> </div> </div> </div> <!-- Earnings (Monthly) Card Example --> <div class=""col-xl-3 col-md-6 mb-4""> <div class=""card border-left-success shadow h-100 py-2""> "); WriteLiteral(@" <div class=""card-body""> <div class=""row no-gutters align-items-center""> <div class=""col mr-2""> <div class=""text-xs font-weight-bold text-success text-uppercase mb-1"">Available Rooms</div> <div class=""h5 mb-0 font-weight-bold text-gray-800"">200</div> </div> <div class=""col-auto""> <i class=""fas fa-clipboard-list fa-2x text-gray-300""></i> </div> </div> </div> </div> </div> <!-- Earnings (Monthly) Card Example --> <div class=""col-xl-3 col-md-6 mb-4""> <div class=""card border-left-info shadow h-100 py-2""> <div class=""card-body""> <div class=""row no-gutters align-items-center""> <div class=""col mr-2""> <div class=""text-xs font-wei"); WriteLiteral(@"ght-bold text-info text-uppercase mb-1"">Amounts Earned</div> <div class=""row no-gutters align-items-center""> <div class=""col-auto""> <div class=""h5 mb-0 mr-3 font-weight-bold text-gray-800"">$5000</div> </div> <div class=""col""> <div class=""progress progress-sm mr-2""> <div class=""progress-bar bg-info"" role=""progressbar"" style=""width: 50%"" aria-valuenow=""50"" aria-valuemin=""0"" aria-valuemax=""100""></div> </div> </div> </div> </div> <div class=""col-auto""> <i class=""fas fa-dollar-sign fa-2x text-gray-300""></i> </div> </div> "); WriteLiteral(@" </div> </div> </div> <div class=""col-xl-3 col-md-6 mb-4""> <div class=""card border-left-warning shadow h-100 py-2""> <div class=""card-body""> <div class=""row no-gutters align-items-center""> <div class=""col mr-2""> <div class=""text-xs font-weight-bold text-warning text-uppercase mb-1"">Bookings Made</div> <div class=""h5 mb-0 font-weight-bold text-gray-800"">18</div> </div> <div class=""col-auto""> <i class=""fas fa-comments fa-2x text-gray-300""></i> </div> </div> </div> </div> </div> </div> <!-- Pending Requests Card Example --> <div class=""col-xl-3 col-md-6 mb-4""> </div> <!-- Content Row --> <div clas"); WriteLiteral(@"s=""row""> <!-- Area Chart --> <div class=""col-xl-8 col-lg-7""> <div class=""card shadow mb-4""> <!-- Card Header - Dropdown --> <div class=""card-header py-3 d-flex flex-row align-items-center justify-content-between""> <h6 class=""m-0 font-weight-bold text-primary"">Account Overview</h6> <div class=""dropdown no-arrow""> <a class=""dropdown-toggle"" href=""#"" role=""button"" id=""dropdownMenuLink"" data-toggle=""dropdown"" aria-haspopup=""true"" aria-expanded=""false""> <i class=""fas fa-ellipsis-v fa-sm fa-fw text-gray-400""></i> </a> <div class=""dropdown-menu dropdown-menu-right shadow animated--fade-in"" aria-labelledby=""dropdownMenuLink""> <div class=""dropdown-header"">Dropdown Header:</div> <a class=""dropdown-item"); WriteLiteral(@""" href=""#"">Action</a> <a class=""dropdown-item"" href=""#"">Another action</a> <div class=""dropdown-divider""></div> <a class=""dropdown-item"" href=""#"">Something else here</a> </div> </div> </div> <!-- Card Body --> <div class=""card-body""> <div class=""chart-area""> <canvas id=""myAreaChart""></canvas> </div> </div> </div> </div> <!-- Pie Chart --> <div class=""col-xl-4 col-lg-5""> <div class=""card shadow mb-4""> <!-- Card Header - Dropdown --> <div class=""card-header py-3 d-flex flex-row align-items-center justify-content-between""> <h6 class=""m-0 font-weight-bold text-pri"); WriteLiteral(@"mary"">Revenue Sources</h6> <div class=""dropdown no-arrow""> <a class=""dropdown-toggle"" href=""#"" role=""button"" id=""dropdownMenuLink"" data-toggle=""dropdown"" aria-haspopup=""true"" aria-expanded=""false""> <i class=""fas fa-ellipsis-v fa-sm fa-fw text-gray-400""></i> </a> <div class=""dropdown-menu dropdown-menu-right shadow animated--fade-in"" aria-labelledby=""dropdownMenuLink""> <div class=""dropdown-header"">Dropdown Header:</div> <a class=""dropdown-item"" href=""#"">Action</a> <a class=""dropdown-item"" href=""#"">Another action</a> <div class=""dropdown-divider""></div> <a class=""dropdown-item"" href=""#"">Something else here</a> </div> </div> </div> "); WriteLiteral(@" <!-- Card Body --> <div class=""card-body""> <div class=""chart-pie pt-4 pb-2""> <canvas id=""myPieChart""></canvas> </div> <div class=""mt-4 text-center small""> <span class=""mr-2""> <i class=""fas fa-circle text-primary""></i> Direct </span> <span class=""mr-2""> <i class=""fas fa-circle text-success""></i> Social </span> <span class=""mr-2""> <i class=""fas fa-circle text-info""></i> Referral </span> </div> </div> </div> </div> </div> <!-- Bootstrap core JavaScript--> "); EndContext(); BeginContext(9105, 63, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "02934233ff56c353e34e8a11f2ee62950b0cab0f21841", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_4); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(9168, 10, true); WriteLiteral("\r\n "); EndContext(); BeginContext(9178, 79, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "02934233ff56c353e34e8a11f2ee62950b0cab0f23102", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_5); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(9257, 52, true); WriteLiteral("\r\n\r\n <!-- Core plugin JavaScript-->\r\n "); EndContext(); BeginContext(9309, 77, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "02934233ff56c353e34e8a11f2ee62950b0cab0f24409", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_6); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(9386, 58, true); WriteLiteral("\r\n\r\n <!-- Custom scripts for all pages-->\r\n "); EndContext(); BeginContext(9444, 56, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "02934233ff56c353e34e8a11f2ee62950b0cab0f25722", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_7); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(9500, 49, true); WriteLiteral("\r\n\r\n <!-- Page level plugins -->\r\n "); EndContext(); BeginContext(9549, 64, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "02934233ff56c353e34e8a11f2ee62950b0cab0f27026", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_8); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(9613, 56, true); WriteLiteral("\r\n\r\n <!-- Page level custom scripts -->\r\n "); EndContext(); BeginContext(9669, 62, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "02934233ff56c353e34e8a11f2ee62950b0cab0f28337", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_9); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(9731, 10, true); WriteLiteral("\r\n "); EndContext(); BeginContext(9741, 61, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "02934233ff56c353e34e8a11f2ee62950b0cab0f29598", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_10); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(9802, 14, true); WriteLiteral("\r\n </div>\r\n"); EndContext(); } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_BodyTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.BodyTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_BodyTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_11); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(9823, 9, true); WriteLiteral("\r\n</html>"); EndContext(); } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<IEnumerable<HostelOsis.Models.ViewModel.OccupantViewModel>> Html { get; private set; } } } #pragma warning restore 1591
66.858921
391
0.62493
[ "MIT" ]
koninlord/HostelOsis
HostelOsis/obj/Debug/netcoreapp2.2/Razor/Views/Home/Index.cshtml.g.cs
32,226
C#
namespace RazzleServer.Common.Constants { public enum WorldName : byte { Tespia } }
13.125
40
0.619048
[ "MIT" ]
Bia10/RazzleServer
RazzleServer.Common/Constants/WorldName.cs
107
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Runtime.InteropServices; using size_t = System.UInt64; using curl_socket_t = System.Int32; using curl_off_t = System.Int64; internal static partial class Interop { internal static partial class libcurl { // Class for constants defined for the enum CURLoption in curl.h internal static partial class CURLoption { // Curl options are of the format <type base> + <n> private const int CurlOptionLongBase = 0; private const int CurlOptionObjectPointBase = 10000; private const int CurlOptionFunctionPointBase = 20000; internal const int CURLOPT_VERBOSE = CurlOptionLongBase + 41; internal const int CURLOPT_NOBODY = CurlOptionLongBase + 44; internal const int CURLOPT_UPLOAD = CurlOptionLongBase + 46; internal const int CURLOPT_POST = CurlOptionLongBase + 47; internal const int CURLOPT_FOLLOWLOCATION = CurlOptionLongBase + 52; internal const int CURLOPT_PROXYPORT = CurlOptionLongBase + 59; internal const int CURLOPT_POSTFIELDSIZE = CurlOptionLongBase + 60; internal const int CURLOPT_MAXREDIRS = CurlOptionLongBase + 68; internal const int CURLOPT_NOSIGNAL = CurlOptionLongBase + 99; internal const int CURLOPT_PROXYTYPE = CurlOptionLongBase + 101; internal const int CURLOPT_HTTPAUTH = CurlOptionLongBase + 107; internal const int CURLOPT_WRITEDATA = CurlOptionObjectPointBase + 1; internal const int CURLOPT_URL = CurlOptionObjectPointBase + 2; internal const int CURLOPT_PROXY = CurlOptionObjectPointBase + 4; internal const int CURLOPT_PROXYUSERPWD = CurlOptionObjectPointBase + 6; internal const int CURLOPT_READDATA = CurlOptionObjectPointBase + 9; internal const int CURLOPT_COOKIE = CurlOptionObjectPointBase + 22; internal const int CURLOPT_HTTPHEADER = CurlOptionObjectPointBase + 23; internal const int CURLOPT_HEADERDATA = CurlOptionObjectPointBase + 29; internal const int CURLOPT_ACCEPTENCODING = CurlOptionObjectPointBase + 102; internal const int CURLOPT_PRIVATE = CurlOptionObjectPointBase + 103; internal const int CURLOPT_COPYPOSTFIELDS = CurlOptionObjectPointBase + 165; internal const int CURLOPT_SEEKDATA = CurlOptionObjectPointBase + 168; internal const int CURLOPT_USERNAME = CurlOptionObjectPointBase + 173; internal const int CURLOPT_PASSWORD = CurlOptionObjectPointBase + 174; internal const int CURLOPT_WRITEFUNCTION = CurlOptionFunctionPointBase + 11; internal const int CURLOPT_READFUNCTION = CurlOptionFunctionPointBase + 12; internal const int CURLOPT_HEADERFUNCTION = CurlOptionFunctionPointBase + 79; internal const int CURLOPT_SEEKFUNCTION = CurlOptionFunctionPointBase + 167; } // Class for constants defined for the enum CURLINFO in curl.h internal static partial class CURLINFO { // Curl info are of the format <type base> + <n> private const int CurlInfoStringBase = 0x100000; private const int CurlInfoLongBase = 0x200000; internal const int CURLINFO_PRIVATE = CurlInfoStringBase + 21; internal const int CURLINFO_HTTPAUTH_AVAIL = CurlInfoLongBase + 23; } // Class for constants defined for the enum curl_proxytype in curl.h internal static partial class curl_proxytype { internal const int CURLPROXY_HTTP = 0; } // Class for constants defined for the enum CURLMcode in multi.h internal static partial class CURLMcode { internal const int CURLM_OK = 0; internal const int CURLM_BAD_HANDLE = 1; internal const int CURLM_BAD_EASY_HANDLE = 2; internal const int CURLM_OUT_OF_MEMORY = 3; internal const int CURLM_INTERNAL_ERROR = 4; internal const int CURLM_BAD_SOCKET = 5; internal const int CURLM_UNKNOWN_OPTION = 6; internal const int CURLM_ADDED_ALREADY = 7; } // Class for constants defined for the results of CURL_SEEKFUNCTION internal static partial class CURL_SEEKFUNC { internal const int CURL_SEEKFUNC_OK = 0; internal const int CURL_SEEKFUNC_FAIL = 1; internal const int CURL_SEEKFUNC_CANTSEEK = 2; } // Class for constants defined for the enum CURLMSG in multi.h internal static partial class CURLMSG { internal const int CURLMSG_DONE = 1; } // AUTH related constants internal static partial class CURLAUTH { internal const ulong None = 0; internal const ulong Basic = 1 << 0; internal const ulong Digest = 1 << 1; internal const ulong Negotiate = 1 << 2; internal const ulong DigestIE = 1 << 4; internal const ulong AuthAny = ~DigestIE; } internal static partial class CURL_VERSION_Features { internal const int CURL_VERSION_IPV6 = (1<<0); internal const int CURL_VERSION_KERBEROS4 = (1<<1); internal const int CURL_VERSION_SSL = (1<<2); internal const int CURL_VERSION_LIBZ = (1<<3); internal const int CURL_VERSION_NTLM = (1<<4); internal const int CURL_VERSION_GSSNEGOTIATE = (1<<5); internal const int CURL_VERSION_DEBUG = (1<<6); internal const int CURL_VERSION_ASYNCHDNS = (1<<7); internal const int CURL_VERSION_SPNEGO = (1<<8); internal const int CURL_VERSION_LARGEFILE = (1<<9); internal const int CURL_VERSION_IDN = (1<<10); internal const int CURL_VERSION_SSPI = (1<<11); internal const int CURL_VERSION_CONV = (1<<12); internal const int CURL_VERSION_CURLDEBUG = (1<<13); internal const int CURL_VERSION_TLSAUTH_SRP = (1<<14); internal const int CURL_VERSION_NTLM_WB = (1<<15); internal const int CURL_VERSION_HTTP2 = (1<<16); internal const int CURL_VERSION_GSSAPI = (1<<17); internal const int CURL_VERSION_KERBEROS5 = (1<<18); internal const int CURL_VERSION_UNIX_SOCKETS = (1<<19); } // Type definition of CURLMsg from multi.h [StructLayout(LayoutKind.Explicit)] internal struct CURLMsg { [FieldOffset(0)] internal int msg; [FieldOffset(8)] internal IntPtr easy_handle; [FieldOffset(16)] internal IntPtr data; [FieldOffset(16)] internal int result; } // NOTE: The definition of this structure in Curl/curl.h is larger than // than what is defined below. This definition is only valid for use with // Marshal.PtrToStructure and not for general use in P/Invoke signatures. [StructLayout(LayoutKind.Sequential)] internal struct curl_version_info_data { internal int age; private unsafe char *version; private int versionNum; private unsafe char *host; internal int features; } // Poll values used with curl_multi_wait and curl_waitfd.events/revents internal const int CURL_WAIT_POLLIN = 0x0001; internal const int CURL_WAIT_POLLPRI = 0x0002; internal const int CURL_WAIT_POLLOUT = 0x0004; #pragma warning disable 0649 // until this file is split up, this produces a warning in the X509 project due to being unused internal struct curl_waitfd { internal int fd; internal short events; internal short revents; }; #pragma warning restore 0649 public delegate size_t curl_readwrite_callback( IntPtr buffer, size_t size, size_t nitems, IntPtr context); public delegate int seek_callback( IntPtr userp, curl_off_t offset, int origin); } }
45.37766
124
0.637792
[ "MIT" ]
shana/corefx
src/Common/src/Interop/Unix/libcurl/Interop.libcurl_types.cs
8,531
C#
using System; using System.Collections.Generic; using System.Data; using System.Text; using DayPilot.Web.Ui; using DayPilot.Web.Ui.Data; using DayPilot.Web.Ui.Events; using DayPilot.Web.Ui.Events.Scheduler; using Util.Task; using Util.Ui; public partial class Project_Default : ProjectPage { private Plan _plan = null; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { DayPilotScheduler1.StartDate = Plan.VeryStart ?? DateTime.Today; DayPilotScheduler1.Days = Plan.Days ?? 1; UpdateZoomLevel(); LoadEvents(); } string cols = new DataManager().GetUserConfig(User.Identity.Name, "project.cols"); if (cols != null) { DayPilotScheduler1.RowHeaderColumnWidths = cols; } } private void UpdateZoomLevel() { string level = RadioButtonListZoom.SelectedValue; switch (level) { case "Hours": DayPilotScheduler1.CellDuration = 60; break; case "Days": DayPilotScheduler1.CellDuration = 1440; break; } } private string TaskLink(string name, int id, string status) { if (status == String.Empty) { status = null; } StringBuilder sb = new StringBuilder(); sb.Append("<div class='task_status "); sb.Append(status ?? "planned"); sb.Append("' data-taskid='" + id + "'></div>"); sb.Append("<a title='"); sb.Append(name); sb.Append("' "); sb.Append("href='javascript:edit(\""); sb.Append(id); sb.Append("\")'>"); sb.Append(name); sb.Append("</a>"); return sb.ToString(); } private Plan Plan { get { if (_plan == null) { DataTable table = new DataManager().GetAssignmentsPlanned(ProjectId); _plan = new Plan(); _plan.LoadTasks(table.Rows, "AssignmentId", "AssignmentDuration", "ResourceId"); _plan.Process(); } return _plan; } } private List<Task> Data { get { List<Task> all = new List<Task>(); if (!CheckBoxHideFinished.Checked) { all.AddRange(Finished); } all.AddRange(Started); all.AddRange(Plan.Processed); return all; } } private List<Task> Finished { get { List<Task> tasks = new List<Task>(); DataTable table = new DataManager().GetAssignmentsFinished(ProjectId); foreach (var row in table.Rows) { var task = new Task() { Start = (DateTime)Binder.Get(row, "AssignmentStart").DateTime, End = (DateTime)Binder.Get(row, "AssignmentEnd").DateTime, Id = Binder.Get(row, "AssignmentId").String, Source = row }; tasks.Add(task); } return tasks; } } private List<Task> Started { get { List<Task> tasks = new List<Task>(); DataTable table = new DataManager().GetAssignmentsStarted(ProjectId); foreach (DataRow row in table.Rows) { var task = new Task() { Start = (DateTime)Binder.Get(row, "AssignmentStart").DateTime, End = DateTime.Now, Id = Binder.Get(row, "AssignmentId").String, Source = row }; tasks.Add(task); } return tasks; } } protected void UpdatePanelScheduler_Load(object sender, EventArgs e) { } protected void DayPilotScheduler1_BeforeEventRender(object sender, BeforeEventRenderEventArgs e) { Task t = (Task)e.DataItem.Source; e.DurationBarColor = Helper.StatusToColor(t["AssignmentStatus"]); } protected void DayPilotScheduler1_HeaderColumnWidthChanged(object sender, HeaderColumnWidthChangedEventArgs e) { new DataManager().SetUserConfig(User.Identity.Name, "project.cols", DayPilotScheduler1.RowHeaderColumnWidths); LoadEvents(); } protected void RadioButtonListZoom_SelectedIndexChanged(object sender, EventArgs e) { UpdateZoomLevel(); LoadEvents(); } protected void ButtonReorder_Click(object sender, EventArgs e) { string order = HiddenOrder.Value; new DataManager().UpdateOrder(ProjectId, order); LoadEvents(); } private void LoadEvents() { DayPilotScheduler1.DataSource = Data; LabelSummary.Text = String.Format("Estimated finish time: {0}", Plan.VeryEnd); DataBind(); } protected void ButtonRefresh_Click(object sender, EventArgs e) { LoadEvents(); } protected void CheckBoxHideFinished_CheckedChanged(object sender, EventArgs e) { LoadEvents(); } protected void DayPilotScheduler1_BeforeResHeaderRender(object sender, BeforeHeaderRenderEventArgs e) { DataItemWrapper task = e.DataItem; string name = (string)task["AssignmentNote"]; int id = Convert.ToInt32(task["AssignmentId"]); string resource = Convert.ToString(task["ResourceName"]); string status = Convert.ToString(task["AssignmentStatus"]); TimeSpan duration = TimeSpan.FromMinutes(Convert.ToInt32(task["AssignmentDuration"])); string durationString = duration.ToHourMinuteString(); string spentString = Binder.Get(task, "AssignmentDurationReal").IsNotNull ? Binder.Get(task, "AssignmentDurationReal").TimeSpanFromMinutes.ToHourMinuteString() : String.Empty; e.InnerHTML = TaskLink(name, id, status); e.Columns[0].InnerHTML = "<div style='text-align:right'>" + durationString + "</div>"; e.Columns[1].InnerHTML = "<div style='text-align:right'>" + spentString + "</div>"; e.Columns[2].InnerHTML = resource; } }
29.954545
135
0.537785
[ "Apache-2.0" ]
atlasoutdoor/project-management
TutorialCS/Project/Default.aspx.cs
6,590
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; namespace MixedRealityExtension.Messaging.Commands { internal interface ICommandManager { void ExecuteCommandPayload(ICommandHandlerContext handlerContext, ICommandPayload commandPayload, Action onCompleteCallback); } }
28
127
0.824405
[ "MIT" ]
Djmondoent/mixed-reality-extension-unity
MREUnityRuntimeLib/Messaging/Commands/ICommandManager.cs
336
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using Azure.Core; using Azure.Messaging.EventHubs.Core; namespace Azure.Messaging.EventHubs { /// <summary> /// The set of options that can be specified to influence how /// retry attempts are made, and a failure is eligible to be retried. /// </summary> /// public class EventHubsRetryOptions { /// <summary>The maximum number of retry attempts before considering the associated operation to have failed.</summary> private int _maximumRetries = 3; /// <summary>The delay or back-off factor to apply between retry attempts.</summary> private TimeSpan _delay = TimeSpan.FromSeconds(0.8); /// <summary>The maximum delay to allow between retry attempts.</summary> private TimeSpan _maximumDelay = TimeSpan.FromMinutes(1); /// <summary>The maximum duration to wait for an operation, per attempt.</summary> private TimeSpan _tryTimeOut = TimeSpan.FromMinutes(1); /// <summary> /// The approach to use for calculating retry delays. /// </summary> /// public EventHubsRetryMode Mode { get; set; } = EventHubsRetryMode.Exponential; /// <summary> /// The maximum number of retry attempts before considering the associated operation /// to have failed. /// </summary> /// public int MaximumRetries { get => _maximumRetries; set { Argument.AssertInRange(value, 0, 100, nameof(MaximumRetries)); _maximumRetries = value; } } /// <summary> /// The delay between retry attempts for a fixed approach or the delay /// on which to base calculations for a backoff-based approach. /// </summary> /// public TimeSpan Delay { get => _delay; set { Argument.AssertInRange(value, TimeSpan.FromMilliseconds(1), TimeSpan.FromMinutes(5), nameof(Delay)); _delay = value; } } /// <summary> /// The maximum permissible delay between retry attempts. /// </summary> /// public TimeSpan MaximumDelay { get => _maximumDelay; set { Argument.AssertNotNegative(value, nameof(MaximumDelay)); _maximumDelay = value; } } /// <summary> /// The maximum duration to wait for completion of a single attempt, whether the initial /// attempt or a retry. /// </summary> /// public TimeSpan TryTimeout { get => _tryTimeOut; set { if (value < TimeSpan.Zero) { throw new ArgumentException(Resources.TimeoutMustBePositive, nameof(TryTimeout)); } Argument.AssertInRange(value, TimeSpan.Zero, TimeSpan.FromHours(1), nameof(TryTimeout)); _tryTimeOut = value; } } /// <summary> /// A custom retry policy to be used in place of the individual option values. /// </summary> /// /// <remarks> /// When populated, this custom policy will take precedence over the individual retry /// options provided. /// </remarks> /// public EventHubsRetryPolicy CustomRetryPolicy { get; set; } /// <summary> /// Creates a new copy of the current <see cref="EventHubsRetryOptions" />, cloning its attributes into a new instance. /// </summary> /// /// <returns>A new copy of <see cref="EventHubsRetryOptions" />.</returns> /// internal EventHubsRetryOptions Clone() => new EventHubsRetryOptions { Mode = Mode, CustomRetryPolicy = CustomRetryPolicy, _maximumRetries = _maximumRetries, _delay = _delay, _maximumDelay = _maximumDelay, _tryTimeOut = _tryTimeOut }; /// <summary> /// Converts the options into a retry policy for use. /// </summary> /// /// <returns>The <see cref="EventHubsRetryPolicy" /> represented by the options.</returns> internal EventHubsRetryPolicy ToRetryPolicy() => CustomRetryPolicy ?? new BasicRetryPolicy(this); } }
33.057143
129
0.556612
[ "MIT" ]
Azkel/azure-sdk-for-net
sdk/eventhub/Azure.Messaging.EventHubs/src/EventHubsRetryOptions.cs
4,630
C#
// ---------------------------------------------------------------------------- // <copyright file="LoadBalancingPeer.cs" company="Exit Games GmbH"> // Loadbalancing Framework for Photon - Copyright (C) 2018 Exit Games GmbH // </copyright> // <summary> // Provides operations to use the LoadBalancing and Cloud photon servers. // No logic is implemented here. // </summary> // <author>developer@photonengine.com</author> // ---------------------------------------------------------------------------- #if UNITY_4_7 || UNITY_5 || UNITY_5_3_OR_NEWER #define SUPPORTED_UNITY #endif namespace Photon.Realtime { using System; using System.Collections; using System.Collections.Generic; using ExitGames.Client.Photon; #if SUPPORTED_UNITY using UnityEngine; using Debug = UnityEngine.Debug; #endif #if SUPPORTED_UNITY || NETFX_CORE using Hashtable = ExitGames.Client.Photon.Hashtable; using SupportClass = ExitGames.Client.Photon.SupportClass; #endif /// <summary> /// A LoadBalancingPeer provides the operations and enum definitions needed to use the LoadBalancing server application which is also used in Photon Cloud. /// </summary> /// <remarks> /// This class is internally used. /// The LoadBalancingPeer does not keep a state, instead this is done by a LoadBalancingClient. /// </remarks> public class LoadBalancingPeer : PhotonPeer { /// <summary>Obsolete accessor to the RegionHandler.PingImplementation.</summary> [Obsolete("Use RegionHandler.PingImplementation directly.")] protected internal static Type PingImplementation { get { return RegionHandler.PingImplementation; } set { RegionHandler.PingImplementation = value; } } private readonly Pool<ParameterDictionary> paramDictionaryPool = new Pool<ParameterDictionary>( () => new ParameterDictionary(), x => x.Clear(), 1); // used in OpRaiseEvent() (avoids lots of new Dictionary() calls) /// <summary> /// Creates a Peer with specified connection protocol. You need to set the Listener before using the peer. /// </summary> /// <remarks>Each connection protocol has it's own default networking ports for Photon.</remarks> /// <param name="protocolType">The preferred option is UDP.</param> public LoadBalancingPeer(ConnectionProtocol protocolType) : base(protocolType) { // this does not require a Listener, so: // make sure to set this.Listener before using a peer! this.ConfigUnitySockets(); } /// <summary> /// Creates a Peer with specified connection protocol and a Listener for callbacks. /// </summary> public LoadBalancingPeer(IPhotonPeerListener listener, ConnectionProtocol protocolType) : this(protocolType) { this.Listener = listener; } // Sets up the socket implementations to use, depending on platform [System.Diagnostics.Conditional("SUPPORTED_UNITY")] private void ConfigUnitySockets() { Type websocketType = null; #if (UNITY_XBOXONE || UNITY_GAMECORE) && !UNITY_EDITOR websocketType = Type.GetType("ExitGames.Client.Photon.SocketNativeSource, PhotonRealtime", false); if (websocketType == null) { websocketType = Type.GetType("ExitGames.Client.Photon.SocketNativeSource, Assembly-CSharp-firstpass", false); } if (websocketType == null) { websocketType = Type.GetType("ExitGames.Client.Photon.SocketNativeSource, Assembly-CSharp", false); } if (websocketType == null) { Debug.LogError("UNITY_XBOXONE is defined but peer could not find SocketNativeSource. Check your project files to make sure the native WSS implementation is available. Won't connect."); } #else // to support WebGL export in Unity, we find and assign the SocketWebTcp class (if it's in the project). // alternatively class SocketWebTcp might be in the Photon3Unity3D.dll websocketType = Type.GetType("ExitGames.Client.Photon.SocketWebTcp, PhotonWebSocket", false); if (websocketType == null) { websocketType = Type.GetType("ExitGames.Client.Photon.SocketWebTcp, Assembly-CSharp-firstpass", false); } if (websocketType == null) { websocketType = Type.GetType("ExitGames.Client.Photon.SocketWebTcp, Assembly-CSharp", false); } #endif if (websocketType != null) { this.SocketImplementationConfig[ConnectionProtocol.WebSocket] = websocketType; this.SocketImplementationConfig[ConnectionProtocol.WebSocketSecure] = websocketType; } #if NET_4_6 && (UNITY_EDITOR || !ENABLE_IL2CPP) && !NETFX_CORE this.SocketImplementationConfig[ConnectionProtocol.Udp] = typeof(SocketUdpAsync); this.SocketImplementationConfig[ConnectionProtocol.Tcp] = typeof(SocketTcpAsync); #endif } public virtual bool OpGetRegions(string appId) { Dictionary<byte, object> parameters = new Dictionary<byte, object>(1); parameters[(byte)ParameterCode.ApplicationId] = appId; return this.SendOperation(OperationCode.GetRegions, parameters, new SendOptions() { Reliability = true, Encrypt = true }); } /// <summary> /// Joins the lobby on the Master Server, where you get a list of RoomInfos of currently open rooms. /// This is an async request which triggers a OnOperationResponse() call. /// </summary> /// <param name="lobby">The lobby join to.</param> /// <returns>If the operation could be sent (has to be connected).</returns> public virtual bool OpJoinLobby(TypedLobby lobby = null) { if (this.DebugOut >= DebugLevel.INFO) { this.Listener.DebugReturn(DebugLevel.INFO, "OpJoinLobby()"); } Dictionary<byte, object> parameters = null; if (lobby != null && !lobby.IsDefault) { parameters = new Dictionary<byte, object>(); parameters[(byte)ParameterCode.LobbyName] = lobby.Name; parameters[(byte)ParameterCode.LobbyType] = (byte)lobby.Type; } return this.SendOperation(OperationCode.JoinLobby, parameters, SendOptions.SendReliable); } /// <summary> /// Leaves the lobby on the Master Server. /// This is an async request which triggers a OnOperationResponse() call. /// </summary> /// <returns>If the operation could be sent (requires connection).</returns> public virtual bool OpLeaveLobby() { if (this.DebugOut >= DebugLevel.INFO) { this.Listener.DebugReturn(DebugLevel.INFO, "OpLeaveLobby()"); } return this.SendOperation(OperationCode.LeaveLobby, (Dictionary<byte, object>)null, SendOptions.SendReliable); } /// <summary>Used by OpJoinRoom and by OpCreateRoom alike.</summary> private void RoomOptionsToOpParameters(Dictionary<byte, object> op, RoomOptions roomOptions, bool usePropertiesKey = false) { if (roomOptions == null) { roomOptions = new RoomOptions(); } Hashtable gameProperties = new Hashtable(); gameProperties[GamePropertyKey.IsOpen] = roomOptions.IsOpen; gameProperties[GamePropertyKey.IsVisible] = roomOptions.IsVisible; gameProperties[GamePropertyKey.PropsListedInLobby] = (roomOptions.CustomRoomPropertiesForLobby == null) ? new string[0] : roomOptions.CustomRoomPropertiesForLobby; gameProperties.MergeStringKeys(roomOptions.CustomRoomProperties); if (roomOptions.MaxPlayers > 0) { gameProperties[GamePropertyKey.MaxPlayers] = roomOptions.MaxPlayers; } if (!usePropertiesKey) { op[ParameterCode.GameProperties] = gameProperties; // typically, the key for game props is 248 } else { op[ParameterCode.Properties] = gameProperties; // when an op uses 248 as filter, the "create room" props can be set as 251 } int flags = 0; // a new way to send the room options as bitwise-flags if (roomOptions.CleanupCacheOnLeave) { op[ParameterCode.CleanupCacheOnLeave] = true; // this defines the server's room settings and logic flags = flags | (int)RoomOptionBit.DeleteCacheOnLeave; // this defines the server's room settings and logic (for servers that support flags) } else { op[ParameterCode.CleanupCacheOnLeave] = false; // this defines the server's room settings and logic gameProperties[GamePropertyKey.CleanupCacheOnLeave] = false; // this is only informational for the clients which join } #if SERVERSDK op[ParameterCode.CheckUserOnJoin] = roomOptions.CheckUserOnJoin; if (roomOptions.CheckUserOnJoin) { flags = flags | (int) RoomOptionBit.CheckUserOnJoin; } #else // in PUN v1.88 and PUN 2, CheckUserOnJoin is set by default: flags = flags | (int) RoomOptionBit.CheckUserOnJoin; op[ParameterCode.CheckUserOnJoin] = true; #endif if (roomOptions.PlayerTtl > 0 || roomOptions.PlayerTtl == -1) { op[ParameterCode.PlayerTTL] = roomOptions.PlayerTtl; // TURNBASED } if (roomOptions.EmptyRoomTtl > 0) { op[ParameterCode.EmptyRoomTTL] = roomOptions.EmptyRoomTtl; //TURNBASED } if (roomOptions.SuppressRoomEvents) { flags = flags | (int)RoomOptionBit.SuppressRoomEvents; op[ParameterCode.SuppressRoomEvents] = true; } if (roomOptions.SuppressPlayerInfo) { flags = flags | (int)RoomOptionBit.SuppressPlayerInfo; } if (roomOptions.Plugins != null) { op[ParameterCode.Plugins] = roomOptions.Plugins; } if (roomOptions.PublishUserId) { flags = flags | (int)RoomOptionBit.PublishUserId; op[ParameterCode.PublishUserId] = true; } if (roomOptions.DeleteNullProperties) { flags = flags | (int)RoomOptionBit.DeleteNullProps; // this is only settable as flag } if (roomOptions.BroadcastPropsChangeToAll) { flags = flags | (int)RoomOptionBit.BroadcastPropsChangeToAll; // this is only settable as flag } op[ParameterCode.RoomOptionFlags] = flags; } /// <summary> /// Creates a room (on either Master or Game Server). /// The OperationResponse depends on the server the peer is connected to: /// Master will return a Game Server to connect to. /// Game Server will return the joined Room's data. /// This is an async request which triggers a OnOperationResponse() call. /// </summary> /// <remarks> /// If the room is already existing, the OperationResponse will have a returnCode of ErrorCode.GameAlreadyExists. /// </remarks> public virtual bool OpCreateRoom(EnterRoomParams opParams) { if (this.DebugOut >= DebugLevel.INFO) { this.Listener.DebugReturn(DebugLevel.INFO, "OpCreateRoom()"); } Dictionary<byte, object> op = new Dictionary<byte, object>(); if (!string.IsNullOrEmpty(opParams.RoomName)) { op[ParameterCode.RoomName] = opParams.RoomName; } if (opParams.Lobby != null && !opParams.Lobby.IsDefault) { op[ParameterCode.LobbyName] = opParams.Lobby.Name; op[ParameterCode.LobbyType] = (byte)opParams.Lobby.Type; } if (opParams.ExpectedUsers != null && opParams.ExpectedUsers.Length > 0) { op[ParameterCode.Add] = opParams.ExpectedUsers; } if (opParams.OnGameServer) { if (opParams.PlayerProperties != null && opParams.PlayerProperties.Count > 0) { op[ParameterCode.PlayerProperties] = opParams.PlayerProperties; } op[ParameterCode.Broadcast] = true; // broadcast actor properties this.RoomOptionsToOpParameters(op, opParams.RoomOptions); } //this.Listener.DebugReturn(DebugLevel.INFO, "OpCreateRoom: " + SupportClass.DictionaryToString(op)); return this.SendOperation(OperationCode.CreateGame, op, SendOptions.SendReliable); } /// <summary> /// Joins a room by name or creates new room if room with given name not exists. /// The OperationResponse depends on the server the peer is connected to: /// Master will return a Game Server to connect to. /// Game Server will return the joined Room's data. /// This is an async request which triggers a OnOperationResponse() call. /// </summary> /// <remarks> /// If the room is not existing (anymore), the OperationResponse will have a returnCode of ErrorCode.GameDoesNotExist. /// Other possible ErrorCodes are: GameClosed, GameFull. /// </remarks> /// <returns>If the operation could be sent (requires connection).</returns> public virtual bool OpJoinRoom(EnterRoomParams opParams) { if (this.DebugOut >= DebugLevel.INFO) { this.Listener.DebugReturn(DebugLevel.INFO, "OpJoinRoom()"); } Dictionary<byte, object> op = new Dictionary<byte, object>(); if (!string.IsNullOrEmpty(opParams.RoomName)) { op[ParameterCode.RoomName] = opParams.RoomName; } if (opParams.JoinMode == JoinMode.CreateIfNotExists) { op[ParameterCode.JoinMode] = (byte)JoinMode.CreateIfNotExists; if (opParams.Lobby != null && !opParams.Lobby.IsDefault) { op[ParameterCode.LobbyName] = opParams.Lobby.Name; op[ParameterCode.LobbyType] = (byte)opParams.Lobby.Type; } } else if (opParams.JoinMode == JoinMode.RejoinOnly) { op[ParameterCode.JoinMode] = (byte)JoinMode.RejoinOnly; // changed from JoinMode.JoinOrRejoin } if (opParams.ExpectedUsers != null && opParams.ExpectedUsers.Length > 0) { op[ParameterCode.Add] = opParams.ExpectedUsers; } if (opParams.OnGameServer) { if (opParams.PlayerProperties != null && opParams.PlayerProperties.Count > 0) { op[ParameterCode.PlayerProperties] = opParams.PlayerProperties; } op[ParameterCode.Broadcast] = true; // broadcast actor properties if (opParams.JoinMode == JoinMode.CreateIfNotExists) { this.RoomOptionsToOpParameters(op, opParams.RoomOptions); } } //this.Listener.DebugReturn(DebugLevel.INFO, "OpJoinRoom: " + SupportClass.DictionaryToString(op)); return this.SendOperation(OperationCode.JoinGame, op, SendOptions.SendReliable); } /// <summary> /// Operation to join a random, available room. Overloads take additional player properties. /// This is an async request which triggers a OnOperationResponse() call. /// If all rooms are closed or full, the OperationResponse will have a returnCode of ErrorCode.NoRandomMatchFound. /// If successful, the OperationResponse contains a gameserver address and the name of some room. /// </summary> /// <returns>If the operation could be sent currently (requires connection).</returns> public virtual bool OpJoinRandomRoom(OpJoinRandomRoomParams opJoinRandomRoomParams) { if (this.DebugOut >= DebugLevel.INFO) { this.Listener.DebugReturn(DebugLevel.INFO, "OpJoinRandomRoom()"); } Hashtable expectedRoomProperties = new Hashtable(); expectedRoomProperties.MergeStringKeys(opJoinRandomRoomParams.ExpectedCustomRoomProperties); if (opJoinRandomRoomParams.ExpectedMaxPlayers > 0) { expectedRoomProperties[GamePropertyKey.MaxPlayers] = opJoinRandomRoomParams.ExpectedMaxPlayers; } Dictionary<byte, object> opParameters = new Dictionary<byte, object>(); if (expectedRoomProperties.Count > 0) { opParameters[ParameterCode.GameProperties] = expectedRoomProperties; } if (opJoinRandomRoomParams.MatchingType != MatchmakingMode.FillRoom) { opParameters[ParameterCode.MatchMakingType] = (byte)opJoinRandomRoomParams.MatchingType; } if (opJoinRandomRoomParams.TypedLobby != null && !opJoinRandomRoomParams.TypedLobby.IsDefault) { opParameters[ParameterCode.LobbyName] = opJoinRandomRoomParams.TypedLobby.Name; opParameters[ParameterCode.LobbyType] = (byte)opJoinRandomRoomParams.TypedLobby.Type; } if (!string.IsNullOrEmpty(opJoinRandomRoomParams.SqlLobbyFilter)) { opParameters[ParameterCode.Data] = opJoinRandomRoomParams.SqlLobbyFilter; } if (opJoinRandomRoomParams.ExpectedUsers != null && opJoinRandomRoomParams.ExpectedUsers.Length > 0) { opParameters[ParameterCode.Add] = opJoinRandomRoomParams.ExpectedUsers; } //this.Listener.DebugReturn(DebugLevel.INFO, "OpJoinRandomRoom: " + SupportClass.DictionaryToString(opParameters)); return this.SendOperation(OperationCode.JoinRandomGame, opParameters, SendOptions.SendReliable); } /// <summary> /// Only used on the Master Server. It will assign a game server and room to join-or-create. /// On the Game Server, the OpJoin is used with option "create if not exists". /// </summary> public virtual bool OpJoinRandomOrCreateRoom(OpJoinRandomRoomParams opJoinRandomRoomParams, EnterRoomParams createRoomParams) { if (this.DebugOut >= DebugLevel.INFO) { this.Listener.DebugReturn(DebugLevel.INFO, "OpJoinRandomOrCreateRoom()"); } // join random room parameters: Hashtable expectedRoomProperties = new Hashtable(); expectedRoomProperties.MergeStringKeys(opJoinRandomRoomParams.ExpectedCustomRoomProperties); if (opJoinRandomRoomParams.ExpectedMaxPlayers > 0) { expectedRoomProperties[GamePropertyKey.MaxPlayers] = opJoinRandomRoomParams.ExpectedMaxPlayers; } Dictionary<byte, object> opParameters = new Dictionary<byte, object>(); if (expectedRoomProperties.Count > 0) { opParameters[ParameterCode.GameProperties] = expectedRoomProperties; // used as filter. below, RoomOptionsToOpParameters has usePropertiesKey = true } if (opJoinRandomRoomParams.MatchingType != MatchmakingMode.FillRoom) { opParameters[ParameterCode.MatchMakingType] = (byte)opJoinRandomRoomParams.MatchingType; } if (opJoinRandomRoomParams.TypedLobby != null && !opJoinRandomRoomParams.TypedLobby.IsDefault) { opParameters[ParameterCode.LobbyName] = opJoinRandomRoomParams.TypedLobby.Name; opParameters[ParameterCode.LobbyType] = (byte)opJoinRandomRoomParams.TypedLobby.Type; } if (!string.IsNullOrEmpty(opJoinRandomRoomParams.SqlLobbyFilter)) { opParameters[ParameterCode.Data] = opJoinRandomRoomParams.SqlLobbyFilter; } if (opJoinRandomRoomParams.ExpectedUsers != null && opJoinRandomRoomParams.ExpectedUsers.Length > 0) { opParameters[ParameterCode.Add] = opJoinRandomRoomParams.ExpectedUsers; } // parameters for creating a room if needed ("or create" part of the operation) // partial copy of OpCreateRoom opParameters[ParameterCode.JoinMode] = (byte)JoinMode.CreateIfNotExists; if (createRoomParams != null) { if (!string.IsNullOrEmpty(createRoomParams.RoomName)) { opParameters[ParameterCode.RoomName] = createRoomParams.RoomName; } this.RoomOptionsToOpParameters(opParameters, createRoomParams.RoomOptions, true); } //this.Listener.DebugReturn(DebugLevel.INFO, "OpJoinRandomOrCreateRoom: " + SupportClass.DictionaryToString(opParameters, false)); return this.SendOperation(OperationCode.JoinRandomGame, opParameters, SendOptions.SendReliable); } /// <summary> /// Leaves a room with option to come back later or "for good". /// </summary> /// <param name="becomeInactive">Async games can be re-joined (loaded) later on. Set to false, if you want to abandon a game entirely.</param> /// <param name="sendAuthCookie">WebFlag: Securely transmit the encrypted object AuthCookie to the web service in PathLeave webhook when available</param> /// <returns>If the opteration can be send currently.</returns> public virtual bool OpLeaveRoom(bool becomeInactive, bool sendAuthCookie = false) { Dictionary<byte, object> opParameters = new Dictionary<byte, object>(); if (becomeInactive) { opParameters[ParameterCode.IsInactive] = true; } if (sendAuthCookie) { opParameters[ParameterCode.EventForward] = WebFlags.SendAuthCookieConst; } return this.SendOperation(OperationCode.Leave, opParameters, SendOptions.SendReliable); } /// <summary>Gets a list of games matching a SQL-like where clause.</summary> /// <remarks> /// Operation is only available in lobbies of type SqlLobby. /// This is an async request which triggers a OnOperationResponse() call. /// Returned game list is stored in RoomInfoList. /// </remarks> /// <see cref="https://doc.photonengine.com/en-us/realtime/current/reference/matchmaking-and-lobby#sql_lobby_type"/> /// <param name="lobby">The lobby to query. Has to be of type SqlLobby.</param> /// <param name="queryData">The sql query statement.</param> /// <returns>If the operation could be sent (has to be connected).</returns> public virtual bool OpGetGameList(TypedLobby lobby, string queryData) { if (this.DebugOut >= DebugLevel.INFO) { this.Listener.DebugReturn(DebugLevel.INFO, "OpGetGameList()"); } if (lobby == null) { if (this.DebugOut >= DebugLevel.INFO) { this.Listener.DebugReturn(DebugLevel.INFO, "OpGetGameList not sent. Lobby cannot be null."); } return false; } if (lobby.Type != LobbyType.SqlLobby) { if (this.DebugOut >= DebugLevel.INFO) { this.Listener.DebugReturn(DebugLevel.INFO, "OpGetGameList not sent. LobbyType must be SqlLobby."); } return false; } if (lobby.IsDefault) { if (this.DebugOut >= DebugLevel.INFO) { this.Listener.DebugReturn(DebugLevel.INFO, "OpGetGameList not sent. LobbyName must be not null and not empty."); } return false; } if (string.IsNullOrEmpty(queryData)) { if (this.DebugOut >= DebugLevel.INFO) { this.Listener.DebugReturn(DebugLevel.INFO, "OpGetGameList not sent. queryData must be not null and not empty."); } return false; } Dictionary<byte, object> opParameters = new Dictionary<byte, object>(); opParameters[(byte)ParameterCode.LobbyName] = lobby.Name; opParameters[(byte)ParameterCode.LobbyType] = (byte)lobby.Type; opParameters[(byte)ParameterCode.Data] = queryData; return this.SendOperation(OperationCode.GetGameList, opParameters, SendOptions.SendReliable); } /// <summary> /// Request the rooms and online status for a list of friends (each client must set a unique username via OpAuthenticate). /// </summary> /// <remarks> /// Used on Master Server to find the rooms played by a selected list of users. /// Users identify themselves by using OpAuthenticate with a unique user ID. /// The list of user IDs must be fetched from some other source (not provided by Photon). /// /// The server response includes 2 arrays of info (each index matching a friend from the request):<br/> /// ParameterCode.FindFriendsResponseOnlineList = bool[] of online states<br/> /// ParameterCode.FindFriendsResponseRoomIdList = string[] of room names (empty string if not in a room)<br/> /// <br/> /// The options may be used to define which state a room must match to be returned. /// </remarks> /// <param name="friendsToFind">Array of friend's names (make sure they are unique).</param> /// <param name="options">Options that affect the result of the FindFriends operation.</param> /// <returns>If the operation could be sent (requires connection).</returns> public virtual bool OpFindFriends(string[] friendsToFind, FindFriendsOptions options = null) { Dictionary<byte, object> opParameters = new Dictionary<byte, object>(); if (friendsToFind != null && friendsToFind.Length > 0) { opParameters[ParameterCode.FindFriendsRequestList] = friendsToFind; } if (options != null) { opParameters[ParameterCode.FindFriendsOptions] = options.ToIntFlags(); } return this.SendOperation(OperationCode.FindFriends, opParameters, SendOptions.SendReliable); } public bool OpSetCustomPropertiesOfActor(int actorNr, Hashtable actorProperties) { return this.OpSetPropertiesOfActor(actorNr, actorProperties.StripToStringKeys(), null); } /// <summary> /// Sets properties of a player / actor. /// Internally this uses OpSetProperties, which can be used to either set room or player properties. /// </summary> /// <param name="actorNr">The payer ID (a.k.a. actorNumber) of the player to attach these properties to.</param> /// <param name="actorProperties">The properties to add or update.</param> /// <param name="expectedProperties">If set, these must be in the current properties-set (on the server) to set actorProperties: CAS.</param> /// <param name="webflags">Set these to forward the properties to a WebHook as defined for this app (in Dashboard).</param> /// <returns>If the operation could be sent (requires connection).</returns> protected internal bool OpSetPropertiesOfActor(int actorNr, Hashtable actorProperties, Hashtable expectedProperties = null, WebFlags webflags = null) { if (this.DebugOut >= DebugLevel.INFO) { this.Listener.DebugReturn(DebugLevel.INFO, "OpSetPropertiesOfActor()"); } if (actorNr <= 0 || actorProperties == null || actorProperties.Count == 0) { if (this.DebugOut >= DebugLevel.INFO) { this.Listener.DebugReturn(DebugLevel.INFO, "OpSetPropertiesOfActor not sent. ActorNr must be > 0 and actorProperties must be not null nor empty."); } return false; } Dictionary<byte, object> opParameters = new Dictionary<byte, object>(); opParameters.Add(ParameterCode.Properties, actorProperties); opParameters.Add(ParameterCode.ActorNr, actorNr); opParameters.Add(ParameterCode.Broadcast, true); if (expectedProperties != null && expectedProperties.Count != 0) { opParameters.Add(ParameterCode.ExpectedValues, expectedProperties); } if (webflags != null && webflags.HttpForward) { opParameters[ParameterCode.EventForward] = webflags.WebhookFlags; } return this.SendOperation(OperationCode.SetProperties, opParameters, SendOptions.SendReliable); } protected bool OpSetPropertyOfRoom(byte propCode, object value) { Hashtable properties = new Hashtable(); properties[propCode] = value; return this.OpSetPropertiesOfRoom(properties); } public bool OpSetCustomPropertiesOfRoom(Hashtable gameProperties) { return this.OpSetPropertiesOfRoom(gameProperties.StripToStringKeys()); } /// <summary> /// Sets properties of a room. /// Internally this uses OpSetProperties, which can be used to either set room or player properties. /// </summary> /// <param name="gameProperties">The properties to add or update.</param> /// <param name="expectedProperties">The properties expected when update occurs. (CAS : "Check And Swap")</param> /// <param name="webflags">WebFlag to indicate if request should be forwarded as "PathProperties" webhook or not.</param> /// <returns>If the operation could be sent (has to be connected).</returns> protected internal bool OpSetPropertiesOfRoom(Hashtable gameProperties, Hashtable expectedProperties = null, WebFlags webflags = null) { if (this.DebugOut >= DebugLevel.INFO) { this.Listener.DebugReturn(DebugLevel.INFO, "OpSetPropertiesOfRoom()"); } if (gameProperties == null || gameProperties.Count == 0) { if (this.DebugOut >= DebugLevel.INFO) { this.Listener.DebugReturn(DebugLevel.INFO, "OpSetPropertiesOfRoom not sent. gameProperties must be not null nor empty."); } return false; } Dictionary<byte, object> opParameters = new Dictionary<byte, object>(); opParameters.Add(ParameterCode.Properties, gameProperties); opParameters.Add(ParameterCode.Broadcast, true); if (expectedProperties != null && expectedProperties.Count != 0) { opParameters.Add(ParameterCode.ExpectedValues, expectedProperties); } if (webflags!=null && webflags.HttpForward) { opParameters[ParameterCode.EventForward] = webflags.WebhookFlags; } return this.SendOperation(OperationCode.SetProperties, opParameters, SendOptions.SendReliable); } /// <summary> /// Sends this app's appId and appVersion to identify this application server side. /// This is an async request which triggers a OnOperationResponse() call. /// </summary> /// <remarks> /// This operation makes use of encryption, if that is established before. /// See: EstablishEncryption(). Check encryption with IsEncryptionAvailable. /// This operation is allowed only once per connection (multiple calls will have ErrorCode != Ok). /// </remarks> /// <param name="appId">Your application's name or ID to authenticate. This is assigned by Photon Cloud (webpage).</param> /// <param name="appVersion">The client's version (clients with differing client appVersions are separated and players don't meet).</param> /// <param name="authValues">Contains all values relevant for authentication. Even without account system (external Custom Auth), the clients are allowed to identify themselves.</param> /// <param name="regionCode">Optional region code, if the client should connect to a specific Photon Cloud Region.</param> /// <param name="getLobbyStatistics">Set to true on Master Server to receive "Lobby Statistics" events.</param> /// <returns>If the operation could be sent (has to be connected).</returns> public virtual bool OpAuthenticate(string appId, string appVersion, AuthenticationValues authValues, string regionCode, bool getLobbyStatistics) { if (this.DebugOut >= DebugLevel.INFO) { this.Listener.DebugReturn(DebugLevel.INFO, "OpAuthenticate()"); } Dictionary<byte, object> opParameters = new Dictionary<byte, object>(); if (getLobbyStatistics) { // must be sent in operation, even if a Token is available opParameters[ParameterCode.LobbyStats] = true; } // shortcut, if we have a Token if (authValues != null && authValues.Token != null) { opParameters[ParameterCode.Token] = authValues.Token; return this.SendOperation(OperationCode.Authenticate, opParameters, SendOptions.SendReliable); // we don't have to encrypt, when we have a token (which is encrypted) } // without a token, we send a complete op auth opParameters[ParameterCode.AppVersion] = appVersion; opParameters[ParameterCode.ApplicationId] = appId; if (!string.IsNullOrEmpty(regionCode)) { opParameters[ParameterCode.Region] = regionCode; } if (authValues != null) { if (!string.IsNullOrEmpty(authValues.UserId)) { opParameters[ParameterCode.UserId] = authValues.UserId; } if (authValues.AuthType != CustomAuthenticationType.None) { opParameters[ParameterCode.ClientAuthenticationType] = (byte)authValues.AuthType; // if we had a token, the code above would use it. here, we send parameters: if (!string.IsNullOrEmpty(authValues.AuthGetParameters)) { opParameters[ParameterCode.ClientAuthenticationParams] = authValues.AuthGetParameters; } if (authValues.AuthPostData != null) { opParameters[ParameterCode.ClientAuthenticationData] = authValues.AuthPostData; } } } return this.SendOperation(OperationCode.Authenticate, opParameters, new SendOptions() { Reliability = true, Encrypt = true }); } /// <summary> /// Sends this app's appId and appVersion to identify this application server side. /// This is an async request which triggers a OnOperationResponse() call. /// </summary> /// <remarks> /// This operation makes use of encryption, if that is established before. /// See: EstablishEncryption(). Check encryption with IsEncryptionAvailable. /// This operation is allowed only once per connection (multiple calls will have ErrorCode != Ok). /// </remarks> /// <param name="appId">Your application's name or ID to authenticate. This is assigned by Photon Cloud (webpage).</param> /// <param name="appVersion">The client's version (clients with differing client appVersions are separated and players don't meet).</param> /// <param name="authValues">Optional authentication values. The client can set no values or a UserId or some parameters for Custom Authentication by a server.</param> /// <param name="regionCode">Optional region code, if the client should connect to a specific Photon Cloud Region.</param> /// <param name="encryptionMode"></param> /// <param name="expectedProtocol"></param> /// <returns>If the operation could be sent (has to be connected).</returns> public virtual bool OpAuthenticateOnce(string appId, string appVersion, AuthenticationValues authValues, string regionCode, EncryptionMode encryptionMode, ConnectionProtocol expectedProtocol) { if (this.DebugOut >= DebugLevel.INFO) { this.Listener.DebugReturn(DebugLevel.INFO, "OpAuthenticateOnce(): authValues = " + authValues + ", region = " + regionCode + ", encryption = " + encryptionMode); } var opParameters = new Dictionary<byte, object>(); // shortcut, if we have a Token if (authValues != null && authValues.Token != null) { opParameters[ParameterCode.Token] = authValues.Token; return this.SendOperation(OperationCode.AuthenticateOnce, opParameters, SendOptions.SendReliable); // we don't have to encrypt, when we have a token (which is encrypted) } if (encryptionMode == EncryptionMode.DatagramEncryption && expectedProtocol != ConnectionProtocol.Udp) { // TODO disconnect?! throw new NotSupportedException("Expected protocol set to UDP, due to encryption mode DatagramEncryption."); // TODO use some other form of callback?! } opParameters[ParameterCode.ExpectedProtocol] = (byte)expectedProtocol; opParameters[ParameterCode.EncryptionMode] = (byte)encryptionMode; opParameters[ParameterCode.AppVersion] = appVersion; opParameters[ParameterCode.ApplicationId] = appId; if (!string.IsNullOrEmpty(regionCode)) { opParameters[ParameterCode.Region] = regionCode; } if (authValues != null) { if (!string.IsNullOrEmpty(authValues.UserId)) { opParameters[ParameterCode.UserId] = authValues.UserId; } if (authValues.AuthType != CustomAuthenticationType.None) { opParameters[ParameterCode.ClientAuthenticationType] = (byte)authValues.AuthType; if (authValues.Token != null) { opParameters[ParameterCode.Token] = authValues.Token; } else { if (!string.IsNullOrEmpty(authValues.AuthGetParameters)) { opParameters[ParameterCode.ClientAuthenticationParams] = authValues.AuthGetParameters; } if (authValues.AuthPostData != null) { opParameters[ParameterCode.ClientAuthenticationData] = authValues.AuthPostData; } } } } return this.SendOperation(OperationCode.AuthenticateOnce, opParameters, new SendOptions() { Reliability = true, Encrypt = true }); } /// <summary> /// Operation to handle this client's interest groups (for events in room). /// </summary> /// <remarks> /// Note the difference between passing null and byte[0]: /// null won't add/remove any groups. /// byte[0] will add/remove all (existing) groups. /// First, removing groups is executed. This way, you could leave all groups and join only the ones provided. /// /// Changes become active not immediately but when the server executes this operation (approximately RTT/2). /// </remarks> /// <param name="groupsToRemove">Groups to remove from interest. Null will not remove any. A byte[0] will remove all.</param> /// <param name="groupsToAdd">Groups to add to interest. Null will not add any. A byte[0] will add all current.</param> /// <returns>If operation could be enqueued for sending. Sent when calling: Service or SendOutgoingCommands.</returns> public virtual bool OpChangeGroups(byte[] groupsToRemove, byte[] groupsToAdd) { if (this.DebugOut >= DebugLevel.ALL) { this.Listener.DebugReturn(DebugLevel.ALL, "OpChangeGroups()"); } Dictionary<byte, object> opParameters = new Dictionary<byte, object>(); if (groupsToRemove != null) { opParameters[(byte)ParameterCode.Remove] = groupsToRemove; } if (groupsToAdd != null) { opParameters[(byte)ParameterCode.Add] = groupsToAdd; } return this.SendOperation(OperationCode.ChangeGroups, opParameters, SendOptions.SendReliable); } /// <summary> /// Send an event with custom code/type and any content to the other players in the same room. /// </summary> /// <remarks>This override explicitly uses another parameter order to not mix it up with the implementation for Hashtable only.</remarks> /// <param name="eventCode">Identifies this type of event (and the content). Your game's event codes can start with 0.</param> /// <param name="customEventContent">Any serializable datatype (including Hashtable like the other OpRaiseEvent overloads).</param> /// <param name="raiseEventOptions">Contains (slightly) less often used options. If you pass null, the default options will be used.</param> /// <param name="sendOptions">Send options for reliable, encryption etc</param> /// <returns>If operation could be enqueued for sending. Sent when calling: Service or SendOutgoingCommands.</returns> public virtual bool OpRaiseEvent(byte eventCode, object customEventContent, RaiseEventOptions raiseEventOptions, SendOptions sendOptions) { var paramDict = this.paramDictionaryPool.Acquire(); try { if (raiseEventOptions != null) { if (raiseEventOptions.CachingOption != EventCaching.DoNotCache) { paramDict.Add(ParameterCode.Cache, (byte)raiseEventOptions.CachingOption); } switch (raiseEventOptions.CachingOption) { case EventCaching.SliceSetIndex: case EventCaching.SlicePurgeIndex: case EventCaching.SlicePurgeUpToIndex: //this.opParameters[(byte) ParameterCode.CacheSliceIndex] = // (byte) raiseEventOptions.CacheSliceIndex; return this.SendOperation(OperationCode.RaiseEvent, paramDict, sendOptions); case EventCaching.SliceIncreaseIndex: case EventCaching.RemoveFromRoomCacheForActorsLeft: return this.SendOperation(OperationCode.RaiseEvent, paramDict, sendOptions); case EventCaching.RemoveFromRoomCache: if (raiseEventOptions.TargetActors != null) { paramDict.Add(ParameterCode.ActorList, raiseEventOptions.TargetActors); } break; default: if (raiseEventOptions.TargetActors != null) { paramDict.Add(ParameterCode.ActorList, raiseEventOptions.TargetActors); } else if (raiseEventOptions.InterestGroup != 0) { paramDict.Add(ParameterCode.Group, (byte)raiseEventOptions.InterestGroup); } else if (raiseEventOptions.Receivers != ReceiverGroup.Others) { paramDict.Add(ParameterCode.ReceiverGroup, (byte)raiseEventOptions.Receivers); } if (raiseEventOptions.Flags.HttpForward) { paramDict.Add(ParameterCode.EventForward, (byte)raiseEventOptions.Flags.WebhookFlags); } break; } } paramDict.Add(ParameterCode.Code, (byte)eventCode); if (customEventContent != null) { paramDict.Add(ParameterCode.Data, (object)customEventContent); } return this.SendOperation(OperationCode.RaiseEvent, paramDict, sendOptions); } finally { this.paramDictionaryPool.Release(paramDict); } } /// <summary> /// Internally used operation to set some "per server" settings. This is for the Master Server. /// </summary> /// <param name="receiveLobbyStats">Set to true, to get Lobby Statistics (lists of existing lobbies).</param> /// <returns>False if the operation could not be sent.</returns> public virtual bool OpSettings(bool receiveLobbyStats) { if (this.DebugOut >= DebugLevel.ALL) { this.Listener.DebugReturn(DebugLevel.ALL, "OpSettings()"); } Dictionary<byte, object> opParameters = new Dictionary<byte, object>(); // implementation for Master Server: if (receiveLobbyStats) { opParameters[(byte)0] = receiveLobbyStats; } if (opParameters.Count == 0) { // no need to send op in case we set the default values return true; } return this.SendOperation(OperationCode.ServerSettings, opParameters, SendOptions.SendReliable); } } /// <summary>Used in the RoomOptionFlags parameter, this bitmask toggles options in the room.</summary> internal enum RoomOptionBit : int { CheckUserOnJoin = 0x01, // toggles a check of the UserId when joining (enabling returning to a game) DeleteCacheOnLeave = 0x02, // deletes cache on leave SuppressRoomEvents = 0x04, // suppresses all room events PublishUserId = 0x08, // signals that we should publish userId DeleteNullProps = 0x10, // signals that we should remove property if its value was set to null. see RoomOption to Delete Null Properties BroadcastPropsChangeToAll = 0x20, // signals that we should send PropertyChanged event to all room players including initiator SuppressPlayerInfo = 0x40, // disables events join and leave from the server as well as property broadcasts in a room (to minimize traffic) } /// <summary> /// Options for OpFindFriends can be combined to filter which rooms of friends are returned. /// </summary> public class FindFriendsOptions { /// <summary>Include a friend's room only if it is created and confirmed by the game server.</summary> public bool CreatedOnGs = false; //flag: 0x01 /// <summary>Include a friend's room only if it is visible (using Room.IsVisible).</summary> public bool Visible = false; //flag: 0x02 /// <summary>Include a friend's room only if it is open (using Room.IsOpen).</summary> public bool Open = false; //flag: 0x04 /// <summary>Turns the bool options into an integer, which is sent as option flags for Op FindFriends.</summary> /// <returns>The options applied to bits of an integer.</returns> internal int ToIntFlags() { int optionFlags = 0; if (this.CreatedOnGs) { optionFlags = optionFlags | 0x1; } if (this.Visible) { optionFlags = optionFlags | 0x2; } if (this.Open) { optionFlags = optionFlags | 0x4; } return optionFlags; } } /// <summary> /// Parameters for the matchmaking of JoinRandomRoom and JoinRandomOrCreateRoom. /// </summary> /// <remarks> /// More about matchmaking: <see cref="https://doc.photonengine.com/en-us/pun/current/manuals-and-demos/matchmaking-and-lobby"/>. /// </remarks> public class OpJoinRandomRoomParams { /// <summary>The custom room properties a room must have to fit. All key-values must be present to match. In SQL Lobby, use SqlLobbyFilter instead.</summary> public Hashtable ExpectedCustomRoomProperties; /// <summary>Filters by the MaxPlayers value of rooms.</summary> public byte ExpectedMaxPlayers; /// <summary>The MatchmakingMode affects how rooms get filled. By default, the server fills rooms.</summary> public MatchmakingMode MatchingType; /// <summary>The lobby in which to match. The type affects how filters are applied.</summary> public TypedLobby TypedLobby; /// <summary>SQL query to filter room matches. For default-typed lobbies, use ExpectedCustomRoomProperties instead.</summary> public string SqlLobbyFilter; /// <summary>The expected users list blocks player slots for your friends or team mates to join the room, too.</summary> /// <remarks>See: https://doc.photonengine.com/en-us/pun/v2/lobby-and-matchmaking/matchmaking-and-lobby#matchmaking_slot_reservation </remarks> public string[] ExpectedUsers; } /// <summary>Parameters for creating rooms.</summary> public class EnterRoomParams { /// <summary>The name of the room to create. If null, the server generates a unique name. If not null, it must be unique and new or will cause an error.</summary> public string RoomName; /// <summary>The RoomOptions define the optional behaviour of rooms.</summary> public RoomOptions RoomOptions; /// <summary>A lobby to attach the new room to. If set, this overrides a joined lobby (if any).</summary> public TypedLobby Lobby; /// <summary>The custom player properties that describe this client / user. Keys must be strings.</summary> public Hashtable PlayerProperties; /// <summary>Internally used value to skip some values when the operation is sent to the Master Server.</summary> protected internal bool OnGameServer = true; // defaults to true! better send more parameter than too few (GS needs all) /// <summary>Internally used value to check which join mode we should call.</summary> protected internal JoinMode JoinMode; /// <summary>A list of users who are expected to join the room along with this client. Reserves slots for rooms with MaxPlayers value.</summary> public string[] ExpectedUsers; } /// <summary> /// ErrorCode defines the default codes associated with Photon client/server communication. /// </summary> public class ErrorCode { /// <summary>(0) is always "OK", anything else an error or specific situation.</summary> public const int Ok = 0; // server - Photon low(er) level: <= 0 /// <summary> /// (-3) Operation can't be executed yet (e.g. OpJoin can't be called before being authenticated, RaiseEvent cant be used before getting into a room). /// </summary> /// <remarks> /// Before you call any operations on the Cloud servers, the automated client workflow must complete its authorization. /// Wait until State is: JoinedLobby or ConnectedToMasterServer /// </remarks> public const int OperationNotAllowedInCurrentState = -3; /// <summary>(-2) The operation you called is not implemented on the server (application) you connect to. Make sure you run the fitting applications.</summary> [Obsolete("Use InvalidOperation.")] public const int InvalidOperationCode = -2; /// <summary>(-2) The operation you called could not be executed on the server.</summary> /// <remarks> /// Make sure you are connected to the server you expect. /// /// This code is used in several cases: /// The arguments/parameters of the operation might be out of range, missing entirely or conflicting. /// The operation you called is not implemented on the server (application). Server-side plugins affect the available operations. /// </remarks> public const int InvalidOperation = -2; /// <summary>(-1) Something went wrong in the server. Try to reproduce and contact Exit Games.</summary> public const int InternalServerError = -1; // server - client: 0x7FFF and down // logic-level error codes start with short.max /// <summary>(32767) Authentication failed. Possible cause: AppId is unknown to Photon (in cloud service).</summary> public const int InvalidAuthentication = 0x7FFF; /// <summary>(32766) GameId (name) already in use (can't create another). Change name.</summary> public const int GameIdAlreadyExists = 0x7FFF - 1; /// <summary>(32765) Game is full. This rarely happens when some player joined the room before your join completed.</summary> public const int GameFull = 0x7FFF - 2; /// <summary>(32764) Game is closed and can't be joined. Join another game.</summary> public const int GameClosed = 0x7FFF - 3; [Obsolete("No longer used, cause random matchmaking is no longer a process.")] public const int AlreadyMatched = 0x7FFF - 4; /// <summary>(32762) All servers are busy. This is a temporary issue and the game logic should try again after a brief wait time.</summary> /// <remarks> /// This error may happen for all operations that create rooms. The operation response will contain this error code. /// /// This error is very unlikely to happen as we monitor load on all servers and add them on demand. /// However, it's good to be prepared for a shortage of machines or surge in CCUs. /// </remarks> public const int ServerFull = 0x7FFF - 5; /// <summary>(32761) Not in use currently.</summary> public const int UserBlocked = 0x7FFF - 6; /// <summary>(32760) Random matchmaking only succeeds if a room exists thats neither closed nor full. Repeat in a few seconds or create a new room.</summary> public const int NoRandomMatchFound = 0x7FFF - 7; /// <summary>(32758) Join can fail if the room (name) is not existing (anymore). This can happen when players leave while you join.</summary> public const int GameDoesNotExist = 0x7FFF - 9; /// <summary>(32757) Authorization on the Photon Cloud failed becaus the concurrent users (CCU) limit of the app's subscription is reached.</summary> /// <remarks> /// Unless you have a plan with "CCU Burst", clients might fail the authentication step during connect. /// Affected client are unable to call operations. Please note that players who end a game and return /// to the master server will disconnect and re-connect, which means that they just played and are rejected /// in the next minute / re-connect. /// This is a temporary measure. Once the CCU is below the limit, players will be able to connect an play again. /// /// OpAuthorize is part of connection workflow but only on the Photon Cloud, this error can happen. /// Self-hosted Photon servers with a CCU limited license won't let a client connect at all. /// </remarks> public const int MaxCcuReached = 0x7FFF - 10; /// <summary>(32756) Authorization on the Photon Cloud failed because the app's subscription does not allow to use a particular region's server.</summary> /// <remarks> /// Some subscription plans for the Photon Cloud are region-bound. Servers of other regions can't be used then. /// Check your master server address and compare it with your Photon Cloud Dashboard's info. /// https://dashboard.photonengine.com /// /// OpAuthorize is part of connection workflow but only on the Photon Cloud, this error can happen. /// Self-hosted Photon servers with a CCU limited license won't let a client connect at all. /// </remarks> public const int InvalidRegion = 0x7FFF - 11; /// <summary> /// (32755) Custom Authentication of the user failed due to setup reasons (see Cloud Dashboard) or the provided user data (like username or token). Check error message for details. /// </summary> public const int CustomAuthenticationFailed = 0x7FFF - 12; /// <summary>(32753) The Authentication ticket expired. Usually, this is refreshed behind the scenes. Connect (and authorize) again.</summary> public const int AuthenticationTicketExpired = 0x7FF1; /// <summary> /// (32752) A server-side plugin (or webhook) failed to execute and reported an error. Check the OperationResponse.DebugMessage. /// </summary> public const int PluginReportedError = 0x7FFF - 15; /// <summary> /// (32751) CreateGame/JoinGame/Join operation fails if expected plugin does not correspond to loaded one. /// </summary> public const int PluginMismatch = 0x7FFF - 16; /// <summary> /// (32750) for join requests. Indicates the current peer already called join and is joined to the room. /// </summary> public const int JoinFailedPeerAlreadyJoined = 32750; // 0x7FFF - 17, /// <summary> /// (32749) for join requests. Indicates the list of InactiveActors already contains an actor with the requested ActorNr or UserId. /// </summary> public const int JoinFailedFoundInactiveJoiner = 32749; // 0x7FFF - 18, /// <summary> /// (32748) for join requests. Indicates the list of Actors (active and inactive) did not contain an actor with the requested ActorNr or UserId. /// </summary> public const int JoinFailedWithRejoinerNotFound = 32748; // 0x7FFF - 19, /// <summary> /// (32747) for join requests. Note: for future use - Indicates the requested UserId was found in the ExcludedList. /// </summary> public const int JoinFailedFoundExcludedUserId = 32747; // 0x7FFF - 20, /// <summary> /// (32746) for join requests. Indicates the list of ActiveActors already contains an actor with the requested ActorNr or UserId. /// </summary> public const int JoinFailedFoundActiveJoiner = 32746; // 0x7FFF - 21, /// <summary> /// (32745) for SetProerties and Raisevent (if flag HttpForward is true) requests. Indicates the maximum allowd http requests per minute was reached. /// </summary> public const int HttpLimitReached = 32745; // 0x7FFF - 22, /// <summary> /// (32744) for WebRpc requests. Indicates the the call to the external service failed. /// </summary> public const int ExternalHttpCallFailed = 32744; // 0x7FFF - 23, /// <summary> /// (32743) for operations with defined limits (as in calls per second, content count or size). /// </summary> public const int OperationLimitReached = 32743; // 0x7FFF - 24, /// <summary> /// (32742) Server error during matchmaking with slot reservation. E.g. the reserved slots can not exceed MaxPlayers. /// </summary> public const int SlotError = 32742; // 0x7FFF - 25, /// <summary> /// (32741) Server will react with this error if invalid encryption parameters provided by token /// </summary> public const int InvalidEncryptionParameters = 32741; // 0x7FFF - 24, } /// <summary> /// Class for constants. These (byte) values define "well known" properties for an Actor / Player. /// </summary> /// <remarks> /// These constants are used internally. /// "Custom properties" have to use a string-type as key. They can be assigned at will. /// </remarks> public class ActorProperties { /// <summary>(255) Name of a player/actor.</summary> public const byte PlayerName = 255; // was: 1 /// <summary>(254) Tells you if the player is currently in this game (getting events live).</summary> /// <remarks>A server-set value for async games, where players can leave the game and return later.</remarks> public const byte IsInactive = 254; /// <summary>(253) UserId of the player. Sent when room gets created with RoomOptions.PublishUserId = true.</summary> public const byte UserId = 253; } /// <summary> /// Class for constants. These (byte) values are for "well known" room/game properties used in Photon LoadBalancing. /// </summary> /// <remarks> /// These constants are used internally. /// "Custom properties" have to use a string-type as key. They can be assigned at will. /// </remarks> public class GamePropertyKey { /// <summary>(255) Max number of players that "fit" into this room. 0 is for "unlimited".</summary> public const byte MaxPlayers = 255; /// <summary>(254) Makes this room listed or not in the lobby on master.</summary> public const byte IsVisible = 254; /// <summary>(253) Allows more players to join a room (or not).</summary> public const byte IsOpen = 253; /// <summary>(252) Current count of players in the room. Used only in the lobby on master.</summary> public const byte PlayerCount = 252; /// <summary>(251) True if the room is to be removed from room listing (used in update to room list in lobby on master)</summary> public const byte Removed = 251; /// <summary>(250) A list of the room properties to pass to the RoomInfo list in a lobby. This is used in CreateRoom, which defines this list once per room.</summary> public const byte PropsListedInLobby = 250; /// <summary>(249) Equivalent of Operation Join parameter CleanupCacheOnLeave.</summary> public const byte CleanupCacheOnLeave = 249; /// <summary>(248) Code for MasterClientId, which is synced by server. When sent as op-parameter this is (byte)203. As room property this is (byte)248.</summary> /// <remarks>Tightly related to ParameterCode.MasterClientId.</remarks> public const byte MasterClientId = (byte)248; /// <summary>(247) Code for ExpectedUsers in a room. Matchmaking keeps a slot open for the players with these userIDs.</summary> public const byte ExpectedUsers = (byte)247; /// <summary>(246) Player Time To Live. How long any player can be inactive (due to disconnect or leave) before the user gets removed from the playerlist (freeing a slot).</summary> public const byte PlayerTtl = (byte)246; /// <summary>(245) Room Time To Live. How long a room stays available (and in server-memory), after the last player becomes inactive. After this time, the room gets persisted or destroyed.</summary> public const byte EmptyRoomTtl = (byte)245; } /// <summary> /// Class for constants. These values are for events defined by Photon LoadBalancing. /// </summary> /// <remarks>They start at 255 and go DOWN. Your own in-game events can start at 0. These constants are used internally.</remarks> public class EventCode { /// <summary>(230) Initial list of RoomInfos (in lobby on Master)</summary> public const byte GameList = 230; /// <summary>(229) Update of RoomInfos to be merged into "initial" list (in lobby on Master)</summary> public const byte GameListUpdate = 229; /// <summary>(228) Currently not used. State of queueing in case of server-full</summary> public const byte QueueState = 228; /// <summary>(227) Currently not used. Event for matchmaking</summary> public const byte Match = 227; /// <summary>(226) Event with stats about this application (players, rooms, etc)</summary> public const byte AppStats = 226; /// <summary>(224) This event provides a list of lobbies with their player and game counts.</summary> public const byte LobbyStats = 224; /// <summary>(210) Internally used in case of hosting by Azure</summary> [Obsolete("TCP routing was removed after becoming obsolete.")] public const byte AzureNodeInfo = 210; /// <summary>(255) Event Join: someone joined the game. The new actorNumber is provided as well as the properties of that actor (if set in OpJoin).</summary> public const byte Join = (byte)255; /// <summary>(254) Event Leave: The player who left the game can be identified by the actorNumber.</summary> public const byte Leave = (byte)254; /// <summary>(253) When you call OpSetProperties with the broadcast option "on", this event is fired. It contains the properties being set.</summary> public const byte PropertiesChanged = (byte)253; /// <summary>(253) When you call OpSetProperties with the broadcast option "on", this event is fired. It contains the properties being set.</summary> [Obsolete("Use PropertiesChanged now.")] public const byte SetProperties = (byte)253; /// (252) When player left game unexpected and the room has a playerTtl != 0, this event is fired to let everyone know about the timeout. /// Obsolete. Replaced by Leave. public const byte Disconnect = LiteEventCode.Disconnect; /// <summary>(251) Sent by Photon Cloud when a plugin-call or webhook-call failed or events cache limit exceeded. Usually, the execution on the server continues, despite the issue. Contains: ParameterCode.Info.</summary> /// <seealso cref="https://doc.photonengine.com/en-us/realtime/current/reference/webhooks#options"/> public const byte ErrorInfo = 251; /// <summary>(250) Sent by Photon whent he event cache slice was changed. Done by OpRaiseEvent.</summary> public const byte CacheSliceChanged = 250; /// <summary>(223) Sent by Photon to update a token before it times out.</summary> public const byte AuthEvent = 223; } /// <summary>Class for constants. Codes for parameters of Operations and Events.</summary> /// <remarks>These constants are used internally.</remarks> public class ParameterCode { /// <summary>(237) A bool parameter for creating games. If set to true, no room events are sent to the clients on join and leave. Default: false (and not sent).</summary> public const byte SuppressRoomEvents = 237; /// <summary>(236) Time To Live (TTL) for a room when the last player leaves. Keeps room in memory for case a player re-joins soon. In milliseconds.</summary> public const byte EmptyRoomTTL = 236; /// <summary>(235) Time To Live (TTL) for an 'actor' in a room. If a client disconnects, this actor is inactive first and removed after this timeout. In milliseconds.</summary> public const byte PlayerTTL = 235; /// <summary>(234) Optional parameter of OpRaiseEvent and OpSetCustomProperties to forward the event/operation to a web-service.</summary> public const byte EventForward = 234; /// <summary>(233) Optional parameter of OpLeave in async games. If false, the player does abandons the game (forever). By default players become inactive and can re-join.</summary> [Obsolete("Use: IsInactive")] public const byte IsComingBack = (byte)233; /// <summary>(233) Used in EvLeave to describe if a user is inactive (and might come back) or not. In rooms with PlayerTTL, becoming inactive is the default case.</summary> public const byte IsInactive = (byte)233; /// <summary>(232) Used when creating rooms to define if any userid can join the room only once.</summary> public const byte CheckUserOnJoin = (byte)232; /// <summary>(231) Code for "Check And Swap" (CAS) when changing properties.</summary> public const byte ExpectedValues = (byte)231; /// <summary>(230) Address of a (game) server to use.</summary> public const byte Address = 230; /// <summary>(229) Count of players in this application in a rooms (used in stats event)</summary> public const byte PeerCount = 229; /// <summary>(228) Count of games in this application (used in stats event)</summary> public const byte GameCount = 228; /// <summary>(227) Count of players on the master server (in this app, looking for rooms)</summary> public const byte MasterPeerCount = 227; /// <summary>(225) User's ID</summary> public const byte UserId = 225; /// <summary>(224) Your application's ID: a name on your own Photon or a GUID on the Photon Cloud</summary> public const byte ApplicationId = 224; /// <summary>(223) Not used currently (as "Position"). If you get queued before connect, this is your position</summary> public const byte Position = 223; /// <summary>(223) Modifies the matchmaking algorithm used for OpJoinRandom. Allowed parameter values are defined in enum MatchmakingMode.</summary> public const byte MatchMakingType = 223; /// <summary>(222) List of RoomInfos about open / listed rooms</summary> public const byte GameList = 222; /// <summary>(221) Internally used to establish encryption</summary> public const byte Token = 221; /// <summary>(220) Version of your application</summary> public const byte AppVersion = 220; /// <summary>(210) Internally used in case of hosting by Azure</summary> [Obsolete("TCP routing was removed after becoming obsolete.")] public const byte AzureNodeInfo = 210; // only used within events, so use: EventCode.AzureNodeInfo /// <summary>(209) Internally used in case of hosting by Azure</summary> [Obsolete("TCP routing was removed after becoming obsolete.")] public const byte AzureLocalNodeId = 209; /// <summary>(208) Internally used in case of hosting by Azure</summary> [Obsolete("TCP routing was removed after becoming obsolete.")] public const byte AzureMasterNodeId = 208; /// <summary>(255) Code for the gameId/roomName (a unique name per room). Used in OpJoin and similar.</summary> public const byte RoomName = (byte)255; /// <summary>(250) Code for broadcast parameter of OpSetProperties method.</summary> public const byte Broadcast = (byte)250; /// <summary>(252) Code for list of players in a room.</summary> public const byte ActorList = (byte)252; /// <summary>(254) Code of the Actor of an operation. Used for property get and set.</summary> public const byte ActorNr = (byte)254; /// <summary>(249) Code for property set (Hashtable).</summary> public const byte PlayerProperties = (byte)249; /// <summary>(245) Code of data/custom content of an event. Used in OpRaiseEvent.</summary> public const byte CustomEventContent = (byte)245; /// <summary>(245) Code of data of an event. Used in OpRaiseEvent.</summary> public const byte Data = (byte)245; /// <summary>(244) Code used when sending some code-related parameter, like OpRaiseEvent's event-code.</summary> /// <remarks>This is not the same as the Operation's code, which is no longer sent as part of the parameter Dictionary in Photon 3.</remarks> public const byte Code = (byte)244; /// <summary>(248) Code for property set (Hashtable).</summary> public const byte GameProperties = (byte)248; /// <summary> /// (251) Code for property-set (Hashtable). This key is used when sending only one set of properties. /// If either ActorProperties or GameProperties are used (or both), check those keys. /// </summary> public const byte Properties = (byte)251; /// <summary>(253) Code of the target Actor of an operation. Used for property set. Is 0 for game</summary> public const byte TargetActorNr = (byte)253; /// <summary>(246) Code to select the receivers of events (used in Lite, Operation RaiseEvent).</summary> public const byte ReceiverGroup = (byte)246; /// <summary>(247) Code for caching events while raising them.</summary> public const byte Cache = (byte)247; /// <summary>(241) Bool parameter of CreateGame Operation. If true, server cleans up roomcache of leaving players (their cached events get removed).</summary> public const byte CleanupCacheOnLeave = (byte)241; /// <summary>(240) Code for "group" operation-parameter (as used in Op RaiseEvent).</summary> public const byte Group = 240; /// <summary>(239) The "Remove" operation-parameter can be used to remove something from a list. E.g. remove groups from player's interest groups.</summary> public const byte Remove = 239; /// <summary>(239) Used in Op Join to define if UserIds of the players are broadcast in the room. Useful for FindFriends and reserving slots for expected users.</summary> public const byte PublishUserId = 239; /// <summary>(238) The "Add" operation-parameter can be used to add something to some list or set. E.g. add groups to player's interest groups.</summary> public const byte Add = 238; /// <summary>(218) Content for EventCode.ErrorInfo and internal debug operations.</summary> public const byte Info = 218; /// <summary>(217) This key's (byte) value defines the target custom authentication type/service the client connects with. Used in OpAuthenticate</summary> public const byte ClientAuthenticationType = 217; /// <summary>(216) This key's (string) value provides parameters sent to the custom authentication type/service the client connects with. Used in OpAuthenticate</summary> public const byte ClientAuthenticationParams = 216; /// <summary>(215) Makes the server create a room if it doesn't exist. OpJoin uses this to always enter a room, unless it exists and is full/closed.</summary> // public const byte CreateIfNotExists = 215; /// <summary>(215) The JoinMode enum defines which variant of joining a room will be executed: Join only if available, create if not exists or re-join.</summary> /// <remarks>Replaces CreateIfNotExists which was only a bool-value.</remarks> public const byte JoinMode = 215; /// <summary>(214) This key's (string or byte[]) value provides parameters sent to the custom authentication service setup in Photon Dashboard. Used in OpAuthenticate</summary> public const byte ClientAuthenticationData = 214; /// <summary>(203) Code for MasterClientId, which is synced by server. When sent as op-parameter this is code 203.</summary> /// <remarks>Tightly related to GamePropertyKey.MasterClientId.</remarks> public const byte MasterClientId = (byte)203; /// <summary>(1) Used in Op FindFriends request. Value must be string[] of friends to look up.</summary> public const byte FindFriendsRequestList = (byte)1; /// <summary>(2) Used in Op FindFriends request. An integer containing option-flags to filter the results.</summary> public const byte FindFriendsOptions = (byte)2; /// <summary>(1) Used in Op FindFriends response. Contains bool[] list of online states (false if not online).</summary> public const byte FindFriendsResponseOnlineList = (byte)1; /// <summary>(2) Used in Op FindFriends response. Contains string[] of room names ("" where not known or no room joined).</summary> public const byte FindFriendsResponseRoomIdList = (byte)2; /// <summary>(213) Used in matchmaking-related methods and when creating a room to name a lobby (to join or to attach a room to).</summary> public const byte LobbyName = (byte)213; /// <summary>(212) Used in matchmaking-related methods and when creating a room to define the type of a lobby. Combined with the lobby name this identifies the lobby.</summary> public const byte LobbyType = (byte)212; /// <summary>(211) This (optional) parameter can be sent in Op Authenticate to turn on Lobby Stats (info about lobby names and their user- and game-counts).</summary> public const byte LobbyStats = (byte)211; /// <summary>(210) Used for region values in OpAuth and OpGetRegions.</summary> public const byte Region = (byte)210; /// <summary>(209) Path of the WebRPC that got called. Also known as "WebRpc Name". Type: string.</summary> public const byte UriPath = 209; /// <summary>(208) Parameters for a WebRPC as: Dictionary&lt;string, object&gt;. This will get serialized to JSon.</summary> public const byte WebRpcParameters = 208; /// <summary>(207) ReturnCode for the WebRPC, as sent by the web service (not by Photon, which uses ErrorCode). Type: byte.</summary> public const byte WebRpcReturnCode = 207; /// <summary>(206) Message returned by WebRPC server. Analog to Photon's debug message. Type: string.</summary> public const byte WebRpcReturnMessage = 206; /// <summary>(205) Used to define a "slice" for cached events. Slices can easily be removed from cache. Type: int.</summary> public const byte CacheSliceIndex = 205; /// <summary>(204) Informs the server of the expected plugin setup.</summary> /// <remarks> /// The operation will fail in case of a plugin mismatch returning error code PluginMismatch 32751(0x7FFF - 16). /// Setting string[]{} means the client expects no plugin to be setup. /// Note: for backwards compatibility null omits any check. /// </remarks> public const byte Plugins = 204; /// <summary>(202) Used by the server in Operation Responses, when it sends the nickname of the client (the user's nickname).</summary> public const byte NickName = 202; /// <summary>(201) Informs user about name of plugin load to game</summary> public const byte PluginName = 201; /// <summary>(200) Informs user about version of plugin load to game</summary> public const byte PluginVersion = 200; /// <summary>(196) Cluster info provided in OpAuthenticate/OpAuthenticateOnce responses.</summary> public const byte Cluster = 196; /// <summary>(195) Protocol which will be used by client to connect master/game servers. Used for nameserver.</summary> public const byte ExpectedProtocol = 195; /// <summary>(194) Set of custom parameters which are sent in auth request.</summary> public const byte CustomInitData = 194; /// <summary>(193) How are we going to encrypt data.</summary> public const byte EncryptionMode = 193; /// <summary>(192) Parameter of Authentication, which contains encryption keys (depends on AuthMode and EncryptionMode).</summary> public const byte EncryptionData = 192; /// <summary>(191) An int parameter summarizing several boolean room-options with bit-flags.</summary> public const byte RoomOptionFlags = 191; } /// <summary> /// Class for constants. Contains operation codes. /// </summary> /// <remarks>These constants are used internally.</remarks> public class OperationCode { [Obsolete("Exchanging encrpytion keys is done internally in the lib now. Don't expect this operation-result.")] public const byte ExchangeKeysForEncryption = 250; /// <summary>(255) Code for OpJoin, to get into a room.</summary> [Obsolete] public const byte Join = 255; /// <summary>(231) Authenticates this peer and connects to a virtual application</summary> public const byte AuthenticateOnce = 231; /// <summary>(230) Authenticates this peer and connects to a virtual application</summary> public const byte Authenticate = 230; /// <summary>(229) Joins lobby (on master)</summary> public const byte JoinLobby = 229; /// <summary>(228) Leaves lobby (on master)</summary> public const byte LeaveLobby = 228; /// <summary>(227) Creates a game (or fails if name exists)</summary> public const byte CreateGame = 227; /// <summary>(226) Join game (by name)</summary> public const byte JoinGame = 226; /// <summary>(225) Joins random game (on master)</summary> public const byte JoinRandomGame = 225; // public const byte CancelJoinRandom = 224; // obsolete, cause JoinRandom no longer is a "process". now provides result immediately /// <summary>(254) Code for OpLeave, to get out of a room.</summary> public const byte Leave = (byte)254; /// <summary>(253) Raise event (in a room, for other actors/players)</summary> public const byte RaiseEvent = (byte)253; /// <summary>(252) Set Properties (of room or actor/player)</summary> public const byte SetProperties = (byte)252; /// <summary>(251) Get Properties</summary> public const byte GetProperties = (byte)251; /// <summary>(248) Operation code to change interest groups in Rooms (Lite application and extending ones).</summary> public const byte ChangeGroups = (byte)248; /// <summary>(222) Request the rooms and online status for a list of friends (by name, which should be unique).</summary> public const byte FindFriends = 222; /// <summary>(221) Request statistics about a specific list of lobbies (their user and game count).</summary> public const byte GetLobbyStats = 221; /// <summary>(220) Get list of regional servers from a NameServer.</summary> public const byte GetRegions = 220; /// <summary>(219) WebRpc Operation.</summary> public const byte WebRpc = 219; /// <summary>(218) Operation to set some server settings. Used with different parameters on various servers.</summary> public const byte ServerSettings = 218; /// <summary>(217) Get the game list matching a supplied sql filter (SqlListLobby only) </summary> public const byte GetGameList = 217; } /// <summary>Defines possible values for OpJoinRoom and OpJoinOrCreate. It tells the server if the room can be only be joined normally, created implicitly or found on a web-service for Turnbased games.</summary> /// <remarks>These values are not directly used by a game but implicitly set.</remarks> public enum JoinMode : byte { /// <summary>Regular join. The room must exist.</summary> Default = 0, /// <summary>Join or create the room if it's not existing. Used for OpJoinOrCreate for example.</summary> CreateIfNotExists = 1, /// <summary>The room might be out of memory and should be loaded (if possible) from a Turnbased web-service.</summary> JoinOrRejoin = 2, /// <summary>Only re-join will be allowed. If the user is not yet in the room, this will fail.</summary> RejoinOnly = 3, } /// <summary> /// Options for matchmaking rules for OpJoinRandom. /// </summary> public enum MatchmakingMode : byte { /// <summary>Fills up rooms (oldest first) to get players together as fast as possible. Default.</summary> /// <remarks>Makes most sense with MaxPlayers > 0 and games that can only start with more players.</remarks> FillRoom = 0, /// <summary>Distributes players across available rooms sequentially but takes filter into account. Without filter, rooms get players evenly distributed.</summary> SerialMatching = 1, /// <summary>Joins a (fully) random room. Expected properties must match but aside from this, any available room might be selected.</summary> RandomMatching = 2 } /// <summary> /// Lite - OpRaiseEvent lets you chose which actors in the room should receive events. /// By default, events are sent to "Others" but you can overrule this. /// </summary> public enum ReceiverGroup : byte { /// <summary>Default value (not sent). Anyone else gets my event.</summary> Others = 0, /// <summary>Everyone in the current room (including this peer) will get this event.</summary> All = 1, /// <summary>The server sends this event only to the actor with the lowest actorNumber.</summary> /// <remarks>The "master client" does not have special rights but is the one who is in this room the longest time.</remarks> MasterClient = 2, } /// <summary> /// Lite - OpRaiseEvent allows you to cache events and automatically send them to joining players in a room. /// Events are cached per event code and player: Event 100 (example!) can be stored once per player. /// Cached events can be modified, replaced and removed. /// </summary> /// <remarks> /// Caching works only combination with ReceiverGroup options Others and All. /// </remarks> public enum EventCaching : byte { /// <summary>Default value (not sent).</summary> DoNotCache = 0, /// <summary>Will merge this event's keys with those already cached.</summary> [Obsolete] MergeCache = 1, /// <summary>Replaces the event cache for this eventCode with this event's content.</summary> [Obsolete] ReplaceCache = 2, /// <summary>Removes this event (by eventCode) from the cache.</summary> [Obsolete] RemoveCache = 3, /// <summary>Adds an event to the room's cache</summary> AddToRoomCache = 4, /// <summary>Adds this event to the cache for actor 0 (becoming a "globally owned" event in the cache).</summary> AddToRoomCacheGlobal = 5, /// <summary>Remove fitting event from the room's cache.</summary> RemoveFromRoomCache = 6, /// <summary>Removes events of players who already left the room (cleaning up).</summary> RemoveFromRoomCacheForActorsLeft = 7, /// <summary>Increase the index of the sliced cache.</summary> SliceIncreaseIndex = 10, /// <summary>Set the index of the sliced cache. You must set RaiseEventOptions.CacheSliceIndex for this.</summary> SliceSetIndex = 11, /// <summary>Purge cache slice with index. Exactly one slice is removed from cache. You must set RaiseEventOptions.CacheSliceIndex for this.</summary> SlicePurgeIndex = 12, /// <summary>Purge cache slices with specified index and anything lower than that. You must set RaiseEventOptions.CacheSliceIndex for this.</summary> SlicePurgeUpToIndex = 13, } /// <summary> /// Flags for "types of properties", being used as filter in OpGetProperties. /// </summary> [Flags] public enum PropertyTypeFlag : byte { /// <summary>(0x00) Flag type for no property type.</summary> None = 0x00, /// <summary>(0x01) Flag type for game-attached properties.</summary> Game = 0x01, /// <summary>(0x02) Flag type for actor related propeties.</summary> Actor = 0x02, /// <summary>(0x01) Flag type for game AND actor properties. Equal to 'Game'</summary> GameAndActor = Game | Actor } /// <summary>Wraps up common room properties needed when you create rooms. Read the individual entries for more details.</summary> /// <remarks>This directly maps to the fields in the Room class.</remarks> public class RoomOptions { /// <summary>Defines if this room is listed in the lobby. If not, it also is not joined randomly.</summary> /// <remarks> /// A room that is not visible will be excluded from the room lists that are sent to the clients in lobbies. /// An invisible room can be joined by name but is excluded from random matchmaking. /// /// Use this to "hide" a room and simulate "private rooms". Players can exchange a roomname and create it /// invisble to avoid anyone else joining it. /// </remarks> public bool IsVisible { get { return this.isVisible; } set { this.isVisible = value; } } private bool isVisible = true; /// <summary>Defines if this room can be joined at all.</summary> /// <remarks> /// If a room is closed, no player can join this. As example this makes sense when 3 of 4 possible players /// start their gameplay early and don't want anyone to join during the game. /// The room can still be listed in the lobby (set isVisible to control lobby-visibility). /// </remarks> public bool IsOpen { get { return this.isOpen; } set { this.isOpen = value; } } private bool isOpen = true; /// <summary>Max number of players that can be in the room at any time. 0 means "no limit".</summary> public byte MaxPlayers; /// <summary>Time To Live (TTL) for an 'actor' in a room. If a client disconnects, this actor is inactive first and removed after this timeout. In milliseconds.</summary> public int PlayerTtl; /// <summary>Time To Live (TTL) for a room when the last player leaves. Keeps room in memory for case a player re-joins soon. In milliseconds.</summary> public int EmptyRoomTtl; /// <summary>Removes a user's events and properties from the room when a user leaves.</summary> /// <remarks> /// This makes sense when in rooms where players can't place items in the room and just vanish entirely. /// When you disable this, the event history can become too long to load if the room stays in use indefinitely. /// Default: true. Cleans up the cache and props of leaving users. /// </remarks> public bool CleanupCacheOnLeave { get { return this.cleanupCacheOnLeave; } set { this.cleanupCacheOnLeave = value; } } private bool cleanupCacheOnLeave = true; /// <summary>The room's custom properties to set. Use string keys!</summary> /// <remarks> /// Custom room properties are any key-values you need to define the game's setup. /// The shorter your keys are, the better. /// Example: Map, Mode (could be "m" when used with "Map"), TileSet (could be "t"). /// </remarks> public Hashtable CustomRoomProperties; /// <summary>Defines the custom room properties that get listed in the lobby.</summary> /// <remarks> /// Name the custom room properties that should be available to clients that are in a lobby. /// Use with care. Unless a custom property is essential for matchmaking or user info, it should /// not be sent to the lobby, which causes traffic and delays for clients in the lobby. /// /// Default: No custom properties are sent to the lobby. /// </remarks> public string[] CustomRoomPropertiesForLobby = new string[0]; /// <summary>Informs the server of the expected plugin setup.</summary> /// <remarks> /// The operation will fail in case of a plugin missmatch returning error code PluginMismatch 32757(0x7FFF - 10). /// Setting string[]{} means the client expects no plugin to be setup. /// Note: for backwards compatibility null omits any check. /// </remarks> public string[] Plugins; /// <summary> /// Tells the server to skip room events for joining and leaving players. /// </summary> /// <remarks> /// Using this makes the client unaware of the other players in a room. /// That can save some traffic if you have some server logic that updates players /// but it can also limit the client's usability. /// </remarks> public bool SuppressRoomEvents { get; set; } /// <summary>Disables events join and leave from the server as well as property broadcasts in a room (to minimize traffic)</summary> public bool SuppressPlayerInfo { get; set; } /// <summary> /// Defines if the UserIds of players get "published" in the room. Useful for FindFriends, if players want to play another game together. /// </summary> /// <remarks> /// When you set this to true, Photon will publish the UserIds of the players in that room. /// In that case, you can use PhotonPlayer.userId, to access any player's userID. /// This is useful for FindFriends and to set "expected users" to reserve slots in a room. /// </remarks> public bool PublishUserId { get; set; } /// <summary>Optionally, properties get deleted, when null gets assigned as value. Defaults to off / false.</summary> /// <remarks> /// When Op SetProperties is setting a key's value to null, the server and clients should remove the key/value from the Custom Properties. /// By default, the server keeps the keys (and null values) and sends them to joining players. /// /// Important: Only when SetProperties does a "broadcast", the change (key, value = null) is sent to clients to update accordingly. /// This applies to Custom Properties for rooms and actors/players. /// </remarks> public bool DeleteNullProperties { get; set; } /// <summary>By default, property changes are sent back to the client that's setting them to avoid de-sync when properties are set concurrently.</summary> /// <remarks> /// This option is enables by default to fix this scenario: /// /// 1) On server, room property ABC is set to value FOO, which triggers notifications to all the clients telling them that the property changed. /// 2) While that notification is in flight, a client sets the ABC property to value BAR. /// 3) Client receives notification from the server and changes it�s local copy of ABC to FOO. /// 4) Server receives the set operation and changes the official value of ABC to BAR, but never notifies the client that sent the set operation that the value is now BAR. /// /// Without this option, the client that set the value to BAR never hears from the server that the official copy has been updated to BAR, and thus gets stuck with a value of FOO. /// </remarks> public bool BroadcastPropsChangeToAll { get { return this.broadcastPropsChangeToAll; } set { this.broadcastPropsChangeToAll = value; } } private bool broadcastPropsChangeToAll = true; #if SERVERSDK public bool CheckUserOnJoin { get; set; } #endif } /// <summary>Aggregates several less-often used options for operation RaiseEvent. See field descriptions for usage details.</summary> public class RaiseEventOptions { /// <summary>Default options: CachingOption: DoNotCache, InterestGroup: 0, targetActors: null, receivers: Others, sequenceChannel: 0.</summary> public readonly static RaiseEventOptions Default = new RaiseEventOptions(); /// <summary>Defines if the server should simply send the event, put it in the cache or remove events that are like this one.</summary> /// <remarks> /// When using option: SliceSetIndex, SlicePurgeIndex or SlicePurgeUpToIndex, set a CacheSliceIndex. All other options except SequenceChannel get ignored. /// </remarks> public EventCaching CachingOption; /// <summary>The number of the Interest Group to send this to. 0 goes to all users but to get 1 and up, clients must subscribe to the group first.</summary> public byte InterestGroup; /// <summary>A list of Player.ActorNumbers to send this event to. You can implement events that just go to specific users this way.</summary> public int[] TargetActors; /// <summary>Sends the event to All, MasterClient or Others (default). Be careful with MasterClient, as the client might disconnect before it got the event and it gets lost.</summary> public ReceiverGroup Receivers; /// <summary>Events are ordered per "channel". If you have events that are independent of others, they can go into another sequence or channel.</summary> [Obsolete("Not used where SendOptions are a parameter too. Use SendOptions.Channel instead.")] public byte SequenceChannel; /// <summary> Optional flags to be used in Photon client SDKs with Op RaiseEvent and Op SetProperties.</summary> /// <remarks>Introduced mainly for webhooks 1.2 to control behavior of forwarded HTTP requests.</remarks> public WebFlags Flags = WebFlags.Default; ///// <summary>Used along with CachingOption SliceSetIndex, SlicePurgeIndex or SlicePurgeUpToIndex if you want to set or purge a specific cache-slice.</summary> //public int CacheSliceIndex; } /// <summary>Types of lobbies define their behaviour and capabilities. Check each value for details.</summary> /// <remarks>Values of this enum must be matched by the server.</remarks> public enum LobbyType :byte { /// <summary>Standard type and behaviour: While joined to this lobby clients get room-lists and JoinRandomRoom can use a simple filter to match properties (perfectly).</summary> Default = 0, /// <summary>This lobby type lists rooms like Default but JoinRandom has a parameter for SQL-like "where" clauses for filtering. This allows bigger, less, or and and combinations.</summary> SqlLobby = 2, /// <summary>This lobby does not send lists of games. It is only used for OpJoinRandomRoom. It keeps rooms available for a while when there are only inactive users left.</summary> AsyncRandomLobby = 3 } /// <summary>Refers to a specific lobby on the server.</summary> /// <remarks> /// Name and Type combined are the unique identifier for a lobby.<br/> /// The server will create lobbies "on demand", so no registration or setup is required.<br/> /// An empty or null Name always points to the "default lobby" as special case. /// </remarks> public class TypedLobby { /// <summary> /// Name of the lobby. Default: null, pointing to the "default lobby". /// </summary> /// <remarks> /// If Name is null or empty, a TypedLobby will point to the "default lobby". This ignores the Type value and always acts as <see cref="LobbyType.Default"/>. /// </remarks> public string Name; /// <summary> /// Type (and behaviour) of the lobby. /// </summary> /// <remarks> /// An empty or null Name always points to the "default lobby" as special case. /// </remarks> public LobbyType Type; /// <summary> /// A reference to the default lobby which is the unique lobby that uses null as name and is of type <see cref="LobbyType.Default"/>. /// </summary> /// <remarks> /// There is only a single lobby with an empty name on the server. It is always of type <see cref="LobbyType.Default"/>.<br/> /// On the other hand, this is a shortcut and reusable reference to the default lobby.<br/> /// Do not change Name or Type.<br/> /// </remarks> public static readonly TypedLobby Default = new TypedLobby(); /// <summary> /// Returns whether or not this instance points to the "default lobby" (<see cref="TypedLobby.Default"/>). /// </summary> /// <remarks> /// This comes up to checking if the Name is null or empty. /// <see cref="LobbyType.Default"/> is not the same thing as the "default lobby" (<see cref="TypedLobby.Default"/>). /// </remarks> public bool IsDefault { get { return string.IsNullOrEmpty(this.Name); } } /// <summary> /// Creates a TypedLobby instance. Unless Name is changed, this points to the "default lobby" (<see cref="TypedLobby.Default"/>). /// </summary> internal TypedLobby() { } /// <summary> /// Sets Name and Type of the new instance. Make sure name is not empty or null, as that always points to the "default lobby" (<see cref="TypedLobby.Default"/>). /// </summary> /// <param name="name">Some string to identify a lobby.</param> /// <param name="type">The type of a lobby defines it's capabilities and behaviour.</param> public TypedLobby(string name, LobbyType type) { this.Name = name; this.Type = type; } public override string ToString() { return string.Format("lobby '{0}'[{1}]", this.Name, this.Type); } } /// <summary> /// Info for a lobby on the server. Used when <see cref="LoadBalancingClient.EnableLobbyStatistics"/> is true. /// </summary> public class TypedLobbyInfo : TypedLobby { /// <summary>Count of players that currently joined this lobby.</summary> public int PlayerCount; /// <summary>Count of rooms currently associated with this lobby.</summary> public int RoomCount; public override string ToString() { return string.Format("TypedLobbyInfo '{0}'[{1}] rooms: {2} players: {3}", this.Name, this.Type, this.RoomCount, this.PlayerCount); } } /// <summary> /// Options for authentication modes. From "classic" auth on each server to AuthOnce (on NameServer). /// </summary> public enum AuthModeOption { Auth, AuthOnce, AuthOnceWss } /// <summary> /// Options for optional "Custom Authentication" services used with Photon. Used by OpAuthenticate after connecting to Photon. /// </summary> public enum CustomAuthenticationType : byte { /// <summary>Use a custom authentification service. Currently the only implemented option.</summary> Custom = 0, /// <summary>Authenticates users by their Steam Account. Set auth values accordingly!</summary> Steam = 1, /// <summary>Authenticates users by their Facebook Account. Set auth values accordingly!</summary> Facebook = 2, /// <summary>Authenticates users by their Oculus Account and token.</summary> Oculus = 3, /// <summary>Authenticates users by their PSN Account and token.</summary> PlayStation = 4, /// <summary>Authenticates users by their Xbox Account and XSTS token.</summary> Xbox = 5, /// <summary>Authenticates users by their HTC Viveport Account and user token. Set AuthGetParameters to "userToken=[userToken]"</summary> Viveport = 10, /// <summary>Authenticates users by their NSA ID.</summary> NintendoSwitch = 11, /// <summary>Disables custom authentification. Same as not providing any AuthenticationValues for connect (more precisely for: OpAuthenticate).</summary> None = byte.MaxValue } /// <summary> /// Container for user authentication in Photon. Set AuthValues before you connect - all else is handled. /// </summary> /// <remarks> /// On Photon, user authentication is optional but can be useful in many cases. /// If you want to FindFriends, a unique ID per user is very practical. /// /// There are basically three options for user authentication: None at all, the client sets some UserId /// or you can use some account web-service to authenticate a user (and set the UserId server-side). /// /// Custom Authentication lets you verify end-users by some kind of login or token. It sends those /// values to Photon which will verify them before granting access or disconnecting the client. /// /// The AuthValues are sent in OpAuthenticate when you connect, so they must be set before you connect. /// If the AuthValues.UserId is null or empty when it's sent to the server, then the Photon Server assigns a UserId! /// /// The Photon Cloud Dashboard will let you enable this feature and set important server values for it. /// https://dashboard.photonengine.com /// </remarks> public class AuthenticationValues { /// <summary>See AuthType.</summary> private CustomAuthenticationType authType = CustomAuthenticationType.None; /// <summary>The type of authentication provider that should be used. Defaults to None (no auth whatsoever).</summary> /// <remarks>Several auth providers are available and CustomAuthenticationType.Custom can be used if you build your own service.</remarks> public CustomAuthenticationType AuthType { get { return authType; } set { authType = value; } } /// <summary>This string must contain any (http get) parameters expected by the used authentication service. By default, username and token.</summary> /// <remarks> /// Maps to operation parameter 216. /// Standard http get parameters are used here and passed on to the service that's defined in the server (Photon Cloud Dashboard). /// </remarks> public string AuthGetParameters { get; set; } /// <summary>Data to be passed-on to the auth service via POST. Default: null (not sent). Either string or byte[] (see setters).</summary> /// <remarks>Maps to operation parameter 214.</remarks> public object AuthPostData { get; private set; } /// <summary>Internal <b>Photon token</b>. After initial authentication, Photon provides a token for this client, subsequently used as (cached) validation.</summary> /// <remarks>Any token for custom authentication should be set via SetAuthPostData or AddAuthParameter.</remarks> public object Token { get; protected internal set; } /// <summary>The UserId should be a unique identifier per user. This is for finding friends, etc..</summary> /// <remarks>See remarks of AuthValues for info about how this is set and used.</remarks> public string UserId { get; set; } /// <summary>Creates empty auth values without any info.</summary> public AuthenticationValues() { } /// <summary>Creates minimal info about the user. If this is authenticated or not, depends on the set AuthType.</summary> /// <param name="userId">Some UserId to set in Photon.</param> public AuthenticationValues(string userId) { this.UserId = userId; } /// <summary>Sets the data to be passed-on to the auth service via POST.</summary> /// <remarks>AuthPostData is just one value. Each SetAuthPostData replaces any previous value. It can be either a string, a byte[] or a dictionary.</remarks> /// <param name="stringData">String data to be used in the body of the POST request. Null or empty string will set AuthPostData to null.</param> public virtual void SetAuthPostData(string stringData) { this.AuthPostData = (string.IsNullOrEmpty(stringData)) ? null : stringData; } /// <summary>Sets the data to be passed-on to the auth service via POST.</summary> /// <remarks>AuthPostData is just one value. Each SetAuthPostData replaces any previous value. It can be either a string, a byte[] or a dictionary.</remarks> /// <param name="byteData">Binary token / auth-data to pass on.</param> public virtual void SetAuthPostData(byte[] byteData) { this.AuthPostData = byteData; } /// <summary>Sets data to be passed-on to the auth service as Json (Content-Type: "application/json") via Post.</summary> /// <remarks>AuthPostData is just one value. Each SetAuthPostData replaces any previous value. It can be either a string, a byte[] or a dictionary.</remarks> /// <param name="dictData">A authentication-data dictionary will be converted to Json and passed to the Auth webservice via HTTP Post.</param> public virtual void SetAuthPostData(Dictionary<string, object> dictData) { this.AuthPostData = dictData; } /// <summary>Adds a key-value pair to the get-parameters used for Custom Auth (AuthGetParameters).</summary> /// <remarks>This method does uri-encoding for you.</remarks> /// <param name="key">Key for the value to set.</param> /// <param name="value">Some value relevant for Custom Authentication.</param> public virtual void AddAuthParameter(string key, string value) { string ampersand = string.IsNullOrEmpty(this.AuthGetParameters) ? "" : "&"; this.AuthGetParameters = string.Format("{0}{1}{2}={3}", this.AuthGetParameters, ampersand, System.Uri.EscapeDataString(key), System.Uri.EscapeDataString(value)); } /// <summary> /// Transform this object into string. /// </summary> /// <returns>String info about this object's values.</returns> public override string ToString() { return string.Format("AuthenticationValues = AuthType: {0} UserId: {1}{2}{3}{4}", this.AuthType, this.UserId, string.IsNullOrEmpty(this.AuthGetParameters) ? " GetParameters: yes" : "", this.AuthPostData == null ? "" : " PostData: yes", this.Token == null ? "" : " Token: yes"); } /// <summary> /// Make a copy of the current object. /// </summary> /// <param name="copy">The object to be copied into.</param> /// <returns>The copied object.</returns> public AuthenticationValues CopyTo(AuthenticationValues copy) { copy.AuthType = this.AuthType; copy.AuthGetParameters = this.AuthGetParameters; copy.AuthPostData = this.AuthPostData; copy.UserId = this.UserId; return copy; } } }
51.557104
229
0.622162
[ "MIT" ]
MohammedGh92/Photon2SampleProject
Assets/Photon/PhotonRealtime/Code/LoadbalancingPeer.cs
114,665
C#
// HtmlAgilityPack V1.0 - Simon Mourier <simon underscore mourier at hotmail dot com> using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Xml; namespace HtmlAgilityPack { /// <summary> /// Represents a complete HTML document. /// </summary> public partial class HtmlDocument { #region Fields /// <summary> /// Defines the max level we would go deep into the html document /// </summary> private static int _maxDepthLevel = int.MaxValue; private int _c; private Crc32 _crc32; private HtmlAttribute _currentattribute; private HtmlNode _currentnode; private Encoding _declaredencoding; private HtmlNode _documentnode; private bool _fullcomment; private int _index; internal Dictionary<string, HtmlNode> Lastnodes = new Dictionary<string, HtmlNode>(); private HtmlNode _lastparentnode; private int _line; private int _lineposition, _maxlineposition; internal Dictionary<string, HtmlNode> Nodesid; private ParseState _oldstate; private bool _onlyDetectEncoding; internal Dictionary<int, HtmlNode> Openednodes; private List<HtmlParseError> _parseerrors = new List<HtmlParseError>(); private string _remainder; private int _remainderOffset; private ParseState _state; private Encoding _streamencoding; internal string Text; // public props /// <summary> /// Adds Debugging attributes to node. Default is false. /// </summary> public bool OptionAddDebuggingAttributes; /// <summary> /// Defines if closing for non closed nodes must be done at the end or directly in the document. /// Setting this to true can actually change how browsers render the page. Default is false. /// </summary> public bool OptionAutoCloseOnEnd; // close errors at the end /// <summary> /// Defines if non closed nodes will be checked at the end of parsing. Default is true. /// </summary> public bool OptionCheckSyntax = true; /// <summary> /// Defines if a checksum must be computed for the document while parsing. Default is false. /// </summary> public bool OptionComputeChecksum; /// <summary> /// Defines the default stream encoding to use. Default is System.Text.Encoding.Default. /// </summary> public Encoding OptionDefaultStreamEncoding; /// <summary> /// Defines if source text must be extracted while parsing errors. /// If the document has a lot of errors, or cascading errors, parsing performance can be dramatically affected if set to true. /// Default is false. /// </summary> public bool OptionExtractErrorSourceText; // turning this on can dramatically slow performance if a lot of errors are detected /// <summary> /// Defines the maximum length of source text or parse errors. Default is 100. /// </summary> public int OptionExtractErrorSourceTextMaxLength = 100; /// <summary> /// Defines if LI, TR, TH, TD tags must be partially fixed when nesting errors are detected. Default is false. /// </summary> public bool OptionFixNestedTags; // fix li, tr, th, td tags /// <summary> /// Defines if output must conform to XML, instead of HTML. /// </summary> public bool OptionOutputAsXml; /// <summary> /// Defines if attribute value output must be optimized (not bound with double quotes if it is possible). Default is false. /// </summary> public bool OptionOutputOptimizeAttributeValues; /// <summary> /// Defines if name must be output with it's original case. Useful for asp.net tags and attributes /// </summary> public bool OptionOutputOriginalCase; /// <summary> /// Defines if name must be output in uppercase. Default is false. /// </summary> public bool OptionOutputUpperCase; /// <summary> /// Defines if declared encoding must be read from the document. /// Declared encoding is determined using the meta http-equiv="content-type" content="text/html;charset=XXXXX" html node. /// Default is true. /// </summary> public bool OptionReadEncoding = true; /// <summary> /// Defines the name of a node that will throw the StopperNodeException when found as an end node. Default is null. /// </summary> public string OptionStopperNodeName; /// <summary> /// Defines if the 'id' attribute must be specifically used. Default is true. /// </summary> public bool OptionUseIdAttribute = true; /// <summary> /// Defines if empty nodes must be written as closed during output. Default is false. /// </summary> public bool OptionWriteEmptyNodes; #endregion #region Static Members internal static readonly string HtmlExceptionRefNotChild = "Reference node must be a child of this node"; internal static readonly string HtmlExceptionUseIdAttributeFalse = "You need to set UseIdAttribute property to true to enable this feature"; #endregion #region Constructors /// <summary> /// Creates an instance of an HTML document. /// </summary> public HtmlDocument() { _documentnode = CreateNode(HtmlNodeType.Document, 0); #if NETSTANDARD1_3 || NETSTANDARD1_5 OptionDefaultStreamEncoding =Encoding.UTF8; #else OptionDefaultStreamEncoding = Encoding.Default; #endif } #endregion #region Properties /// <summary> /// Defines the max level we would go deep into the html document. If this depth level is exceeded, and exception is /// thrown. /// </summary> public static int MaxDepthLevel { get { return _maxDepthLevel; } set { _maxDepthLevel = value; } } /// <summary> /// Gets the document CRC32 checksum if OptionComputeChecksum was set to true before parsing, 0 otherwise. /// </summary> public int CheckSum { get { return _crc32 == null ? 0 : (int)_crc32.CheckSum; } } /// <summary> /// Gets the document's declared encoding. /// Declared encoding is determined using the meta http-equiv="content-type" content="text/html;charset=XXXXX" html node. /// </summary> public Encoding DeclaredEncoding { get { return _declaredencoding; } } /// <summary> /// Gets the root node of the document. /// </summary> public HtmlNode DocumentNode { get { return _documentnode; } } /// <summary> /// Gets the document's output encoding. /// </summary> public Encoding Encoding { get { return GetOutEncoding(); } } /// <summary> /// Gets a list of parse errors found in the document. /// </summary> public IEnumerable<HtmlParseError> ParseErrors { get { return _parseerrors; } } /// <summary> /// Gets the remaining text. /// Will always be null if OptionStopperNodeName is null. /// </summary> public string Remainder { get { return _remainder; } } /// <summary> /// Gets the offset of Remainder in the original Html text. /// If OptionStopperNodeName is null, this will return the length of the original Html text. /// </summary> public int RemainderOffset { get { return _remainderOffset; } } /// <summary> /// Gets the document's stream encoding. /// </summary> public Encoding StreamEncoding { get { return _streamencoding; } } #endregion #region Public Methods /// <summary> /// Gets a valid XML name. /// </summary> /// <param name="name">Any text.</param> /// <returns>A string that is a valid XML name.</returns> public static string GetXmlName(string name) { string xmlname = string.Empty; bool nameisok = true; for (int i = 0; i < name.Length; i++) { // names are lcase // note: we are very limited here, too much? if (((name[i] >= 'a') && (name[i] <= 'z')) || ((name[i] >= '0') && (name[i] <= '9')) || // (name[i]==':') || (name[i]=='_') || (name[i]=='-') || (name[i]=='.')) // these are bads in fact (name[i] == '_') || (name[i] == '-') || (name[i] == '.')) { xmlname += name[i]; } else { nameisok = false; byte[] bytes = Encoding.UTF8.GetBytes(new char[] { name[i] }); for (int j = 0; j < bytes.Length; j++) { xmlname += bytes[j].ToString("x2"); } xmlname += "_"; } } if (nameisok) { return xmlname; } return "_" + xmlname; } /// <summary> /// Applies HTML encoding to a specified string. /// </summary> /// <param name="html">The input string to encode. May not be null.</param> /// <returns>The encoded string.</returns> public static string HtmlEncode(string html) { if (html == null) { throw new ArgumentNullException("html"); } // replace & by &amp; but only once! Regex rx = new Regex("&(?!(amp;)|(lt;)|(gt;)|(quot;))", RegexOptions.IgnoreCase); return rx.Replace(html, "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("\"", "&quot;"); } /// <summary> /// Determines if the specified character is considered as a whitespace character. /// </summary> /// <param name="c">The character to check.</param> /// <returns>true if if the specified character is considered as a whitespace character.</returns> public static bool IsWhiteSpace(int c) { if ((c == 10) || (c == 13) || (c == 32) || (c == 9)) { return true; } return false; } /// <summary> /// Creates an HTML attribute with the specified name. /// </summary> /// <param name="name">The name of the attribute. May not be null.</param> /// <returns>The new HTML attribute.</returns> public HtmlAttribute CreateAttribute(string name) { if (name == null) throw new ArgumentNullException("name"); HtmlAttribute att = CreateAttribute(); att.Name = name; return att; } /// <summary> /// Creates an HTML attribute with the specified name. /// </summary> /// <param name="name">The name of the attribute. May not be null.</param> /// <param name="value">The value of the attribute.</param> /// <returns>The new HTML attribute.</returns> public HtmlAttribute CreateAttribute(string name, string value) { if (name == null) { throw new ArgumentNullException("name"); } HtmlAttribute att = CreateAttribute(name); att.Value = value; return att; } /// <summary> /// Creates an HTML comment node. /// </summary> /// <returns>The new HTML comment node.</returns> public HtmlCommentNode CreateComment() { return (HtmlCommentNode)CreateNode(HtmlNodeType.Comment); } /// <summary> /// Creates an HTML comment node with the specified comment text. /// </summary> /// <param name="comment">The comment text. May not be null.</param> /// <returns>The new HTML comment node.</returns> public HtmlCommentNode CreateComment(string comment) { if (comment == null) { throw new ArgumentNullException("comment"); } HtmlCommentNode c = CreateComment(); c.Comment = comment; return c; } /// <summary> /// Creates an HTML element node with the specified name. /// </summary> /// <param name="name">The qualified name of the element. May not be null.</param> /// <returns>The new HTML node.</returns> public HtmlNode CreateElement(string name) { if (name == null) { throw new ArgumentNullException("name"); } HtmlNode node = CreateNode(HtmlNodeType.Element); node.Name = name; return node; } /// <summary> /// Creates an HTML text node. /// </summary> /// <returns>The new HTML text node.</returns> public HtmlTextNode CreateTextNode() { return (HtmlTextNode)CreateNode(HtmlNodeType.Text); } /// <summary> /// Creates an HTML text node with the specified text. /// </summary> /// <param name="text">The text of the node. May not be null.</param> /// <returns>The new HTML text node.</returns> public HtmlTextNode CreateTextNode(string text) { if (text == null) { throw new ArgumentNullException("text"); } HtmlTextNode t = CreateTextNode(); t.Text = text; return t; } /// <summary> /// Detects the encoding of an HTML stream. /// </summary> /// <param name="stream">The input stream. May not be null.</param> /// <returns>The detected encoding.</returns> public Encoding DetectEncoding(Stream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } return DetectEncoding(new StreamReader(stream)); } /// <summary> /// Detects the encoding of an HTML text provided on a TextReader. /// </summary> /// <param name="reader">The TextReader used to feed the HTML. May not be null.</param> /// <returns>The detected encoding.</returns> public Encoding DetectEncoding(TextReader reader) { if (reader == null) { throw new ArgumentNullException("reader"); } _onlyDetectEncoding = true; if (OptionCheckSyntax) { Openednodes = new Dictionary<int, HtmlNode>(); } else { Openednodes = null; } if (OptionUseIdAttribute) { Nodesid = new Dictionary<string, HtmlNode>(); } else { Nodesid = null; } StreamReader sr = reader as StreamReader; if (sr != null) { _streamencoding = sr.CurrentEncoding; } else { _streamencoding = null; } _declaredencoding = null; Text = reader.ReadToEnd(); _documentnode = CreateNode(HtmlNodeType.Document, 0); // this is almost a hack, but it allows us not to muck with the original parsing code try { Parse(); } catch (EncodingFoundException ex) { return ex.Encoding; } return null; } /// <summary> /// Detects the encoding of an HTML text. /// </summary> /// <param name="html">The input html text. May not be null.</param> /// <returns>The detected encoding.</returns> public Encoding DetectEncodingHtml(string html) { if (html == null) { throw new ArgumentNullException("html"); } using(StringReader sr = new StringReader(html)) { Encoding encoding = DetectEncoding(sr); return encoding; } } /// <summary> /// Gets the HTML node with the specified 'id' attribute value. /// </summary> /// <param name="id">The attribute id to match. May not be null.</param> /// <returns>The HTML node with the matching id or null if not found.</returns> public HtmlNode GetElementbyId(string id) { if (id == null) { throw new ArgumentNullException("id"); } if (Nodesid == null) { throw new Exception(HtmlExceptionUseIdAttributeFalse); } return Nodesid.ContainsKey(id.ToLower()) ? Nodesid[id.ToLower()] : null; } /// <summary> /// Loads an HTML document from a stream. /// </summary> /// <param name="stream">The input stream.</param> public void Load(Stream stream) { Load(new StreamReader(stream, OptionDefaultStreamEncoding)); } /// <summary> /// Loads an HTML document from a stream. /// </summary> /// <param name="stream">The input stream.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the stream.</param> public void Load(Stream stream, bool detectEncodingFromByteOrderMarks) { Load(new StreamReader(stream, detectEncodingFromByteOrderMarks)); } /// <summary> /// Loads an HTML document from a stream. /// </summary> /// <param name="stream">The input stream.</param> /// <param name="encoding">The character encoding to use.</param> public void Load(Stream stream, Encoding encoding) { Load(new StreamReader(stream, encoding)); } /// <summary> /// Loads an HTML document from a stream. /// </summary> /// <param name="stream">The input stream.</param> /// <param name="encoding">The character encoding to use.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the stream.</param> public void Load(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks) { Load(new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks)); } /// <summary> /// Loads an HTML document from a stream. /// </summary> /// <param name="stream">The input stream.</param> /// <param name="encoding">The character encoding to use.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the stream.</param> /// <param name="buffersize">The minimum buffer size.</param> public void Load(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int buffersize) { Load(new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks, buffersize)); } /// <summary> /// Loads the HTML document from the specified TextReader. /// </summary> /// <param name="reader">The TextReader used to feed the HTML data into the document. May not be null.</param> public void Load(TextReader reader) { // all Load methods pass down to this one if (reader == null) throw new ArgumentNullException("reader"); _onlyDetectEncoding = false; if (OptionCheckSyntax) Openednodes = new Dictionary<int, HtmlNode>(); else Openednodes = null; if (OptionUseIdAttribute) { Nodesid = new Dictionary<string, HtmlNode>(); } else { Nodesid = null; } StreamReader sr = reader as StreamReader; if (sr != null) { try { // trigger bom read if needed sr.Peek(); } // ReSharper disable EmptyGeneralCatchClause catch (Exception) // ReSharper restore EmptyGeneralCatchClause { // void on purpose } _streamencoding = sr.CurrentEncoding; } else { _streamencoding = null; } _declaredencoding = null; Text = reader.ReadToEnd(); _documentnode = CreateNode(HtmlNodeType.Document, 0); Parse(); if (!OptionCheckSyntax || Openednodes == null) return; foreach (HtmlNode node in Openednodes.Values) { if (!node._starttag) // already reported { continue; } string html; if (OptionExtractErrorSourceText) { html = node.OuterHtml; if (html.Length > OptionExtractErrorSourceTextMaxLength) { html = html.Substring(0, OptionExtractErrorSourceTextMaxLength); } } else { html = string.Empty; } AddError( HtmlParseErrorCode.TagNotClosed, node._line, node._lineposition, node._streamposition, html, "End tag </" + node.Name + "> was not found"); } // we don't need this anymore Openednodes.Clear(); } /// <summary> /// Loads the HTML document from the specified string. /// </summary> /// <param name="html">String containing the HTML document to load. May not be null.</param> public void LoadHtml(string html) { if (html == null) { throw new ArgumentNullException("html"); } using (StringReader sr = new StringReader(html)) { Load(sr); } } /// <summary> /// Saves the HTML document to the specified stream. /// </summary> /// <param name="outStream">The stream to which you want to save.</param> public void Save(Stream outStream) { StreamWriter sw = new StreamWriter(outStream, GetOutEncoding()); Save(sw); } /// <summary> /// Saves the HTML document to the specified stream. /// </summary> /// <param name="outStream">The stream to which you want to save. May not be null.</param> /// <param name="encoding">The character encoding to use. May not be null.</param> public void Save(Stream outStream, Encoding encoding) { if (outStream == null) { throw new ArgumentNullException("outStream"); } if (encoding == null) { throw new ArgumentNullException("encoding"); } StreamWriter sw = new StreamWriter(outStream, encoding); Save(sw); } /// <summary> /// Saves the HTML document to the specified StreamWriter. /// </summary> /// <param name="writer">The StreamWriter to which you want to save.</param> public void Save(StreamWriter writer) { Save((TextWriter)writer); } /// <summary> /// Saves the HTML document to the specified TextWriter. /// </summary> /// <param name="writer">The TextWriter to which you want to save. May not be null.</param> public void Save(TextWriter writer) { if (writer == null) { throw new ArgumentNullException("writer"); } DocumentNode.WriteTo(writer); writer.Flush(); } /// <summary> /// Saves the HTML document to the specified XmlWriter. /// </summary> /// <param name="writer">The XmlWriter to which you want to save.</param> public void Save(XmlWriter writer) { DocumentNode.WriteTo(writer); writer.Flush(); } #endregion #region Internal Methods internal HtmlAttribute CreateAttribute() { return new HtmlAttribute(this); } internal HtmlNode CreateNode(HtmlNodeType type) { return CreateNode(type, -1); } internal HtmlNode CreateNode(HtmlNodeType type, int index) { switch (type) { case HtmlNodeType.Comment: return new HtmlCommentNode(this, index); case HtmlNodeType.Text: return new HtmlTextNode(this, index); default: return new HtmlNode(type, this, index); } } internal Encoding GetOutEncoding() { // when unspecified, use the stream encoding first return _declaredencoding ?? (_streamencoding ?? OptionDefaultStreamEncoding); } internal HtmlNode GetXmlDeclaration() { if (!_documentnode.HasChildNodes) return null; foreach (HtmlNode node in _documentnode._childnodes) if (node.Name == "?xml") // it's ok, names are case sensitive return node; return null; } internal void SetIdForNode(HtmlNode node, string id) { if (!OptionUseIdAttribute) return; if ((Nodesid == null) || (id == null)) return; if (node == null) Nodesid.Remove(id.ToLower()); else Nodesid[id.ToLower()] = node; } internal void UpdateLastParentNode() { do { if (_lastparentnode.Closed) _lastparentnode = _lastparentnode.ParentNode; } while ((_lastparentnode != null) && (_lastparentnode.Closed)); if (_lastparentnode == null) _lastparentnode = _documentnode; } #endregion #region Private Methods private void AddError(HtmlParseErrorCode code, int line, int linePosition, int streamPosition, string sourceText, string reason) { HtmlParseError err = new HtmlParseError(code, line, linePosition, streamPosition, sourceText, reason); _parseerrors.Add(err); return; } private void CloseCurrentNode() { if (_currentnode.Closed) // text or document are by def closed return; bool error = false; HtmlNode prev = Utilities.GetDictionaryValueOrNull(Lastnodes, _currentnode.Name); // find last node of this kind if (prev == null) { if (HtmlNode.IsClosedElement(_currentnode.Name)) { // </br> will be seen as <br> _currentnode.CloseNode(_currentnode); // add to parent node if (_lastparentnode != null) { HtmlNode foundNode = null; Stack<HtmlNode> futureChild = new Stack<HtmlNode>(); for (HtmlNode node = _lastparentnode.LastChild; node != null; node = node.PreviousSibling) { if ((node.Name == _currentnode.Name) && (!node.HasChildNodes)) { foundNode = node; break; } futureChild.Push(node); } if (foundNode != null) { while (futureChild.Count != 0) { HtmlNode node = futureChild.Pop(); _lastparentnode.RemoveChild(node); foundNode.AppendChild(node); } } else { _lastparentnode.AppendChild(_currentnode); } } } else { // node has no parent // node is not a closed node if (HtmlNode.CanOverlapElement(_currentnode.Name)) { // this is a hack: add it as a text node HtmlNode closenode = CreateNode(HtmlNodeType.Text, _currentnode._outerstartindex); closenode._outerlength = _currentnode._outerlength; ((HtmlTextNode)closenode).Text = ((HtmlTextNode)closenode).Text.ToLower(); if (_lastparentnode != null) { _lastparentnode.AppendChild(closenode); } } else { if (HtmlNode.IsEmptyElement(_currentnode.Name)) { AddError( HtmlParseErrorCode.EndTagNotRequired, _currentnode._line, _currentnode._lineposition, _currentnode._streamposition, _currentnode.OuterHtml, "End tag </" + _currentnode.Name + "> is not required"); } else { // node cannot overlap, node is not empty AddError( HtmlParseErrorCode.TagNotOpened, _currentnode._line, _currentnode._lineposition, _currentnode._streamposition, _currentnode.OuterHtml, "Start tag <" + _currentnode.Name + "> was not found"); error = true; } } } } else { if (OptionFixNestedTags) { if (FindResetterNodes(prev, GetResetters(_currentnode.Name))) { AddError( HtmlParseErrorCode.EndTagInvalidHere, _currentnode._line, _currentnode._lineposition, _currentnode._streamposition, _currentnode.OuterHtml, "End tag </" + _currentnode.Name + "> invalid here"); error = true; } } if (!error) { Lastnodes[_currentnode.Name] = prev._prevwithsamename; prev.CloseNode(_currentnode); } } // we close this node, get grandparent if (!error) { if ((_lastparentnode != null) && ((!HtmlNode.IsClosedElement(_currentnode.Name)) || (_currentnode._starttag))) { UpdateLastParentNode(); } } } private string CurrentNodeName() { return Text.Substring(_currentnode._namestartindex, _currentnode._namelength); } private void DecrementPosition() { _index--; if (_lineposition == 1) { _lineposition = _maxlineposition; _line--; } else { _lineposition--; } } private HtmlNode FindResetterNode(HtmlNode node, string name) { HtmlNode resetter = Utilities.GetDictionaryValueOrNull(Lastnodes, name); if (resetter == null) return null; if (resetter.Closed) return null; if (resetter._streamposition < node._streamposition) { return null; } return resetter; } private bool FindResetterNodes(HtmlNode node, string[] names) { if (names == null) return false; for (int i = 0; i < names.Length; i++) { if (FindResetterNode(node, names[i]) != null) return true; } return false; } private void FixNestedTag(string name, string[] resetters) { if (resetters == null) return; HtmlNode prev = Utilities.GetDictionaryValueOrNull(Lastnodes, _currentnode.Name); // if we find a previous unclosed same name node, without a resetter node between, we must close it if (prev == null || (Lastnodes[name].Closed)) return; // try to find a resetter node, if found, we do nothing if (FindResetterNodes(prev, resetters)) { return; } // ok we need to close the prev now // create a fake closer node HtmlNode close = new HtmlNode(prev.NodeType, this, -1); close._endnode = close; prev.CloseNode(close); } private void FixNestedTags() { // we are only interested by start tags, not closing tags if (!_currentnode._starttag) return; string name = CurrentNodeName(); FixNestedTag(name, GetResetters(name)); } private string[] GetResetters(string name) { switch (name) { case "li": return new string[] { "ul" }; case "tr": return new string[] { "table" }; case "th": case "td": return new string[] { "tr", "table" }; default: return null; } } private void IncrementPosition() { if (_crc32 != null) { // REVIEW: should we add some checksum code in DecrementPosition too? _crc32.AddToCRC32(_c); } _index++; _maxlineposition = _lineposition; if (_c == 10) { _lineposition = 1; _line++; } else { _lineposition++; } } private bool NewCheck() { if (_c != '<') { return false; } if (_index < Text.Length) { if (Text[_index] == '%') { switch (_state) { case ParseState.AttributeAfterEquals: PushAttributeValueStart(_index - 1); break; case ParseState.BetweenAttributes: PushAttributeNameStart(_index - 1); break; case ParseState.WhichTag: PushNodeNameStart(true, _index - 1); _state = ParseState.Tag; break; } _oldstate = _state; _state = ParseState.ServerSideCode; return true; } } if (!PushNodeEnd(_index - 1, true)) { // stop parsing _index = Text.Length; return true; } _state = ParseState.WhichTag; if ((_index - 1) <= (Text.Length - 2)) { if (Text[_index] == '!') { PushNodeStart(HtmlNodeType.Comment, _index - 1); PushNodeNameStart(true, _index); PushNodeNameEnd(_index + 1); _state = ParseState.Comment; if (_index < (Text.Length - 2)) { if ((Text[_index + 1] == '-') && (Text[_index + 2] == '-')) { _fullcomment = true; } else { _fullcomment = false; } } return true; } } PushNodeStart(HtmlNodeType.Element, _index - 1); return true; } private void Parse() { int lastquote = 0; if (OptionComputeChecksum) { _crc32 = new Crc32(); } Lastnodes = new Dictionary<string, HtmlNode>(); _c = 0; _fullcomment = false; _parseerrors = new List<HtmlParseError>(); _line = 1; _lineposition = 1; _maxlineposition = 1; _state = ParseState.Text; _oldstate = _state; _documentnode._innerlength = Text.Length; _documentnode._outerlength = Text.Length; _remainderOffset = Text.Length; _lastparentnode = _documentnode; _currentnode = CreateNode(HtmlNodeType.Text, 0); _currentattribute = null; _index = 0; PushNodeStart(HtmlNodeType.Text, 0); while (_index < Text.Length) { _c = Text[_index]; IncrementPosition(); switch (_state) { case ParseState.Text: if (NewCheck()) continue; break; case ParseState.WhichTag: if (NewCheck()) continue; if (_c == '/') { PushNodeNameStart(false, _index); } else { PushNodeNameStart(true, _index - 1); DecrementPosition(); } _state = ParseState.Tag; break; case ParseState.Tag: if (NewCheck()) continue; if (IsWhiteSpace(_c)) { PushNodeNameEnd(_index - 1); if (_state != ParseState.Tag) continue; _state = ParseState.BetweenAttributes; continue; } if (_c == '/') { PushNodeNameEnd(_index - 1); if (_state != ParseState.Tag) continue; _state = ParseState.EmptyTag; continue; } if (_c == '>') { PushNodeNameEnd(_index - 1); if (_state != ParseState.Tag) continue; if (!PushNodeEnd(_index, false)) { // stop parsing _index = Text.Length; break; } if (_state != ParseState.Tag) continue; _state = ParseState.Text; PushNodeStart(HtmlNodeType.Text, _index); } break; case ParseState.BetweenAttributes: if (NewCheck()) continue; if (IsWhiteSpace(_c)) continue; if ((_c == '/') || (_c == '?')) { _state = ParseState.EmptyTag; continue; } if (_c == '>') { if (!PushNodeEnd(_index, false)) { // stop parsing _index = Text.Length; break; } if (_state != ParseState.BetweenAttributes) continue; _state = ParseState.Text; PushNodeStart(HtmlNodeType.Text, _index); continue; } PushAttributeNameStart(_index - 1); _state = ParseState.AttributeName; break; case ParseState.EmptyTag: if (NewCheck()) continue; if (_c == '>') { if (!PushNodeEnd(_index, true)) { // stop parsing _index = Text.Length; break; } if (_state != ParseState.EmptyTag) continue; _state = ParseState.Text; PushNodeStart(HtmlNodeType.Text, _index); continue; } _state = ParseState.BetweenAttributes; break; case ParseState.AttributeName: if (NewCheck()) continue; if (IsWhiteSpace(_c)) { PushAttributeNameEnd(_index - 1); _state = ParseState.AttributeBeforeEquals; continue; } if (_c == '=') { PushAttributeNameEnd(_index - 1); _state = ParseState.AttributeAfterEquals; continue; } if (_c == '>') { PushAttributeNameEnd(_index - 1); if (!PushNodeEnd(_index, false)) { // stop parsing _index = Text.Length; break; } if (_state != ParseState.AttributeName) continue; _state = ParseState.Text; PushNodeStart(HtmlNodeType.Text, _index); continue; } break; case ParseState.AttributeBeforeEquals: if (NewCheck()) continue; if (IsWhiteSpace(_c)) continue; if (_c == '>') { if (!PushNodeEnd(_index, false)) { // stop parsing _index = Text.Length; break; } if (_state != ParseState.AttributeBeforeEquals) continue; _state = ParseState.Text; PushNodeStart(HtmlNodeType.Text, _index); continue; } if (_c == '=') { _state = ParseState.AttributeAfterEquals; continue; } // no equals, no whitespace, it's a new attrribute starting _state = ParseState.BetweenAttributes; DecrementPosition(); break; case ParseState.AttributeAfterEquals: if (NewCheck()) continue; if (IsWhiteSpace(_c)) continue; if ((_c == '\'') || (_c == '"')) { _state = ParseState.QuotedAttributeValue; PushAttributeValueStart(_index, _c); lastquote = _c; continue; } if (_c == '>') { if (!PushNodeEnd(_index, false)) { // stop parsing _index = Text.Length; break; } if (_state != ParseState.AttributeAfterEquals) continue; _state = ParseState.Text; PushNodeStart(HtmlNodeType.Text, _index); continue; } PushAttributeValueStart(_index - 1); _state = ParseState.AttributeValue; break; case ParseState.AttributeValue: if (NewCheck()) continue; if (IsWhiteSpace(_c)) { PushAttributeValueEnd(_index - 1); _state = ParseState.BetweenAttributes; continue; } if (_c == '>') { PushAttributeValueEnd(_index - 1); if (!PushNodeEnd(_index, false)) { // stop parsing _index = Text.Length; break; } if (_state != ParseState.AttributeValue) continue; _state = ParseState.Text; PushNodeStart(HtmlNodeType.Text, _index); continue; } break; case ParseState.QuotedAttributeValue: if (_c == lastquote) { PushAttributeValueEnd(_index - 1); _state = ParseState.BetweenAttributes; continue; } if (_c == '<') { if (_index < Text.Length) { if (Text[_index] == '%') { _oldstate = _state; _state = ParseState.ServerSideCode; continue; } } } break; case ParseState.Comment: if (_c == '>') { if (_fullcomment) { if ((Text[_index - 2] != '-') || (Text[_index - 3] != '-')) { continue; } } if (!PushNodeEnd(_index, false)) { // stop parsing _index = Text.Length; break; } _state = ParseState.Text; PushNodeStart(HtmlNodeType.Text, _index); continue; } break; case ParseState.ServerSideCode: if (_c == '%') { if (_index < Text.Length) { if (Text[_index] == '>') { switch (_oldstate) { case ParseState.AttributeAfterEquals: _state = ParseState.AttributeValue; break; case ParseState.BetweenAttributes: PushAttributeNameEnd(_index + 1); _state = ParseState.BetweenAttributes; break; default: _state = _oldstate; break; } IncrementPosition(); } } } break; case ParseState.PcData: // look for </tag + 1 char // check buffer end if ((_currentnode._namelength + 3) <= (Text.Length - (_index - 1))) { if (string.Compare(Text.Substring(_index - 1, _currentnode._namelength + 2), "</" + _currentnode.Name, StringComparison.OrdinalIgnoreCase) == 0) { int c = Text[_index - 1 + 2 + _currentnode.Name.Length]; if ((c == '>') || (IsWhiteSpace(c))) { // add the script as a text node HtmlNode script = CreateNode(HtmlNodeType.Text, _currentnode._outerstartindex + _currentnode._outerlength); script._outerlength = _index - 1 - script._outerstartindex; _currentnode.AppendChild(script); PushNodeStart(HtmlNodeType.Element, _index - 1); PushNodeNameStart(false, _index - 1 + 2); _state = ParseState.Tag; IncrementPosition(); } } } break; } } // finish the current work if (_currentnode._namestartindex > 0) { PushNodeNameEnd(_index); } PushNodeEnd(_index, false); // we don't need this anymore Lastnodes.Clear(); } private void PushAttributeNameEnd(int index) { _currentattribute._namelength = index - _currentattribute._namestartindex; _currentnode.Attributes.Append(_currentattribute); } private void PushAttributeNameStart(int index) { _currentattribute = CreateAttribute(); _currentattribute._namestartindex = index; _currentattribute.Line = _line; _currentattribute._lineposition = _lineposition; _currentattribute._streamposition = index; } private void PushAttributeValueEnd(int index) { _currentattribute._valuelength = index - _currentattribute._valuestartindex; } private void PushAttributeValueStart(int index) { PushAttributeValueStart(index, 0); } private void PushAttributeValueStart(int index, int quote) { _currentattribute._valuestartindex = index; if (quote == '\'') _currentattribute.QuoteType = AttributeValueQuote.SingleQuote; } private bool PushNodeEnd(int index, bool close) { _currentnode._outerlength = index - _currentnode._outerstartindex; if ((_currentnode._nodetype == HtmlNodeType.Text) || (_currentnode._nodetype == HtmlNodeType.Comment)) { // forget about void nodes if (_currentnode._outerlength > 0) { _currentnode._innerlength = _currentnode._outerlength; _currentnode._innerstartindex = _currentnode._outerstartindex; if (_lastparentnode != null) { _lastparentnode.AppendChild(_currentnode); } } } else { if ((_currentnode._starttag) && (_lastparentnode != _currentnode)) { // add to parent node if (_lastparentnode != null) { _lastparentnode.AppendChild(_currentnode); } ReadDocumentEncoding(_currentnode); // remember last node of this kind HtmlNode prev = Utilities.GetDictionaryValueOrNull(Lastnodes, _currentnode.Name); _currentnode._prevwithsamename = prev; Lastnodes[_currentnode.Name] = _currentnode; // change parent? if ((_currentnode.NodeType == HtmlNodeType.Document) || (_currentnode.NodeType == HtmlNodeType.Element)) { _lastparentnode = _currentnode; } if (HtmlNode.IsCDataElement(CurrentNodeName())) { _state = ParseState.PcData; return true; } if ((HtmlNode.IsClosedElement(_currentnode.Name)) || (HtmlNode.IsEmptyElement(_currentnode.Name))) { close = true; } } } if ((close) || (!_currentnode._starttag)) { if ((OptionStopperNodeName != null) && (_remainder == null) && (string.Compare(_currentnode.Name, OptionStopperNodeName, StringComparison.OrdinalIgnoreCase) == 0)) { _remainderOffset = index; _remainder = Text.Substring(_remainderOffset); CloseCurrentNode(); return false; // stop parsing } CloseCurrentNode(); } return true; } private void PushNodeNameEnd(int index) { _currentnode._namelength = index - _currentnode._namestartindex; if (OptionFixNestedTags) { FixNestedTags(); } } private void PushNodeNameStart(bool starttag, int index) { _currentnode._starttag = starttag; _currentnode._namestartindex = index; } private void PushNodeStart(HtmlNodeType type, int index) { _currentnode = CreateNode(type, index); _currentnode._line = _line; _currentnode._lineposition = _lineposition; if (type == HtmlNodeType.Element) { _currentnode._lineposition--; } _currentnode._streamposition = index; } private void ReadDocumentEncoding(HtmlNode node) { if (!OptionReadEncoding) return; // format is // <meta http-equiv="content-type" content="text/html;charset=iso-8859-1" /> // when we append a child, we are in node end, so attributes are already populated if (node._namelength != 4) // quick check, avoids string alloc return; if (node.Name != "meta") // all nodes names are lowercase return; HtmlAttribute att = node.Attributes["http-equiv"]; if (att == null) return; if (string.Compare(att.Value, "content-type", StringComparison.OrdinalIgnoreCase) != 0) return; HtmlAttribute content = node.Attributes["content"]; if (content != null) { string charset = NameValuePairList.GetNameValuePairsValue(content.Value, "charset"); if (!string.IsNullOrEmpty(charset)) { // The following check fixes the the bug described at: http://htmlagilitypack.codeplex.com/WorkItem/View.aspx?WorkItemId=25273 if (string.Equals(charset, "utf8", StringComparison.OrdinalIgnoreCase)) charset = "utf-8"; try { _declaredencoding = Encoding.GetEncoding(charset); } catch (ArgumentException) { _declaredencoding = null; } if (_onlyDetectEncoding) { throw new EncodingFoundException(_declaredencoding); } if (_streamencoding != null) { if (_declaredencoding != null) if (_declaredencoding.CodePage != _streamencoding.CodePage) { AddError( HtmlParseErrorCode.CharsetMismatch, _line, _lineposition, _index, node.OuterHtml, "Encoding mismatch between StreamEncoding: " + _streamencoding.WebName + " and DeclaredEncoding: " + _declaredencoding.WebName); } } } } } #endregion #region Nested type: ParseState private enum ParseState { Text, WhichTag, Tag, BetweenAttributes, EmptyTag, AttributeName, AttributeBeforeEquals, AttributeAfterEquals, AttributeValue, Comment, QuotedAttributeValue, ServerSideCode, PcData } #endregion } }
25.189844
139
0.627274
[ "Apache-2.0" ]
noliar/HtmlAgilityPack.NetCore
src/DevZH.HtmlAgilityPack/HtmlDocument.cs
43,654
C#
namespace EF6TempTableKit.Test.Web.Entities { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("Purchasing.PurchaseOrderHeader")] public partial class PurchaseOrderHeader { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public PurchaseOrderHeader() { PurchaseOrderDetails = new HashSet<PurchaseOrderDetail>(); } [Key] public int PurchaseOrderID { get; set; } public byte RevisionNumber { get; set; } public byte Status { get; set; } public int EmployeeID { get; set; } public int VendorID { get; set; } public int ShipMethodID { get; set; } public DateTime OrderDate { get; set; } public DateTime? ShipDate { get; set; } [Column(TypeName = "money")] public decimal SubTotal { get; set; } [Column(TypeName = "money")] public decimal TaxAmt { get; set; } [Column(TypeName = "money")] public decimal Freight { get; set; } [Column(TypeName = "money")] [DatabaseGenerated(DatabaseGeneratedOption.Computed)] public decimal TotalDue { get; set; } public DateTime ModifiedDate { get; set; } public virtual Employee Employee { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<PurchaseOrderDetail> PurchaseOrderDetails { get; set; } public virtual ShipMethod ShipMethod { get; set; } public virtual Vendor Vendor { get; set; } } }
30.466667
128
0.65372
[ "MIT" ]
zblago/EF6TempTableKit
tests/EF6TempTableKit.Test.Web/Entities/PurchaseOrderHeader.cs
1,828
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright company="Aspose" file="SearchResponse.cs"> // Copyright (c) 2021 Aspose.Words for Cloud // </copyright> // <summary> // 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. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Aspose.Words.Cloud.Sdk.Model { using System; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Converters; /// <summary> /// The REST response with a regular expression pattern and a collection of search results. /// </summary> public class SearchResponse : WordsResponse { /// <summary> /// Gets or sets the regular expression pattern used to find matches. /// </summary> public string SearchingPattern { get; set; } /// <summary> /// Gets or sets the collection of search results. /// </summary> public SearchResultsCollection SearchResults { get; set; } /// <summary> /// Get 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 SearchResponse {\n"); sb.Append(" SearchingPattern: ").Append(this.SearchingPattern).Append("\n"); sb.Append(" SearchResults: ").Append(this.SearchResults).Append("\n"); sb.Append("}\n"); return sb.ToString(); } } }
44.090909
120
0.598625
[ "MIT" ]
aspose-words-cloud/aspose-words-cloud-dotne
Aspose.Words.Cloud.Sdk/Model/SearchResponse.cs
2,845
C#
using CourseLibrary.API.DbContexts; using CourseLibrary.API.Entities; using CourseLibrary.API.ResourseParameter; using System; using System.Collections.Generic; using System.Linq; namespace CourseLibrary.API.Services { public class CourseLibraryRepository : ICourseLibraryRepository, IDisposable { private readonly CourseLibraryContext _context; public CourseLibraryRepository(CourseLibraryContext context ) { _context = context ?? throw new ArgumentNullException(nameof(context)); } public void AddCourse(Guid authorId, Course course) { if (authorId == Guid.Empty) { throw new ArgumentNullException(nameof(authorId)); } if (course == null) { throw new ArgumentNullException(nameof(course)); } // always set the AuthorId to the passed-in authorId course.AuthorId = authorId; _context.Courses.Add(course); } public void DeleteCourse(Course course) { _context.Courses.Remove(course); } public Course GetCourse(Guid authorId, Guid courseId) { if (authorId == Guid.Empty) { throw new ArgumentNullException(nameof(authorId)); } if (courseId == Guid.Empty) { throw new ArgumentNullException(nameof(courseId)); } return _context.Courses .Where(c => c.AuthorId == authorId && c.Id == courseId).FirstOrDefault(); } public IEnumerable<Course> GetCourses(Guid authorId) { if (authorId == Guid.Empty) { throw new ArgumentNullException(nameof(authorId)); } return _context.Courses .Where(c => c.AuthorId == authorId) .OrderBy(c => c.Title).ToList(); } public void UpdateCourse(Course course) { // no code in this implementation } public void AddAuthor(Author author) { if (author == null) { throw new ArgumentNullException(nameof(author)); } // the repository fills the id (instead of using identity columns) author.Id = Guid.NewGuid(); foreach (var course in author.Courses) { course.Id = Guid.NewGuid(); } _context.Authors.Add(author); } public bool AuthorExists(Guid authorId) { if (authorId == Guid.Empty) { throw new ArgumentNullException(nameof(authorId)); } return _context.Authors.Any(a => a.Id == authorId); } public void DeleteAuthor(Author author) { if (author == null) { throw new ArgumentNullException(nameof(author)); } _context.Authors.Remove(author); } public Author GetAuthor(Guid authorId) { if (authorId == Guid.Empty) { throw new ArgumentNullException(nameof(authorId)); } return _context.Authors.FirstOrDefault(a => a.Id == authorId); } public IEnumerable<Author> GetAuthors() { return _context.Authors.ToList<Author>(); } public IEnumerable<Author> GetAuthors(AuthorsResourceParameters authorsResourceParameters) { if (string.IsNullOrWhiteSpace(authorsResourceParameters.MainCategory) && string.IsNullOrWhiteSpace(authorsResourceParameters.SearchQuery)) return GetAuthors(); var collection = _context.Authors as IQueryable<Author>; if (authorsResourceParameters == null) throw new ArgumentNullException(nameof(authorsResourceParameters)); if (!string.IsNullOrWhiteSpace(authorsResourceParameters.MainCategory)) { var mainCategory = authorsResourceParameters.MainCategory.Trim(); collection = collection.Where(a => a.MainCategory == mainCategory); } if (!string.IsNullOrWhiteSpace(authorsResourceParameters.SearchQuery)) { var searchQuery = authorsResourceParameters.SearchQuery.Trim(); collection = collection.Where(a => a.MainCategory.Contains(searchQuery) || a.FirstName.Contains(searchQuery) || a.LastName.Contains(searchQuery)); } return collection.ToList(); } public IEnumerable<Author> GetAuthors(IEnumerable<Guid> authorIds) { if (authorIds == null) { throw new ArgumentNullException(nameof(authorIds)); } return _context.Authors.Where(a => authorIds.Contains(a.Id)) .OrderBy(a => a.FirstName) .OrderBy(a => a.LastName) .ToList(); } public void UpdateAuthor(Author author) { // no code in this implementation } public bool Save() { return (_context.SaveChanges() >= 0); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { // dispose resources when needed } } } }
29.685864
105
0.543563
[ "MIT" ]
ancill/DotNet_CookBook
SImpleApi/SImpleApi/Services/CourseLibraryRepository.cs
5,672
C#
// ========================================================================= // Copyright 2020 EPAM Systems, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ========================================================================= using System; using System.Collections.ObjectModel; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Threading.Tasks; using Covi.Client.Services.Platform.Models; using Covi.Features.Recommendations.Services; using Covi.Features.UserProfile.Services; using Covi.Services.ErrorHandlers; using DynamicData; using ReactiveUI; namespace Covi.Features.Recommendations { public class RecommendationsViewModel : ComponentViewModelBase { private readonly IUserProfileContainer _userProfileContainer; private readonly IErrorHandler _errorHandler; private readonly IRecommendationsService _recommendationsService; private readonly ReadOnlyObservableCollection<RecommendationItemViewModel> _recommendations; private readonly SourceList<Recommendation> _models = new SourceList<Recommendation>(); public ReadOnlyObservableCollection<RecommendationItemViewModel> Recommendations => _recommendations; public RecommendationsViewModel( IUserProfileContainer userProfileContainer, IErrorHandler errorHandler, IRecommendationsService recommendationsService) { _userProfileContainer = userProfileContainer; _errorHandler = errorHandler; _recommendationsService = recommendationsService; _models.Connect() .SubscribeOn(RxApp.TaskpoolScheduler) .Transform(x => new RecommendationItemViewModel(x)) .ObserveOn(RxApp.MainThreadScheduler) .Bind(out _recommendations, 1) .Subscribe(); } public override void OnActivated(CompositeDisposable lifecycleDisposable) { base.OnActivated(lifecycleDisposable); SetRecommendationsAsync().FireAndForget(); } private async Task SetRecommendationsAsync() { try { var profile = await _userProfileContainer.GetAsync(); var statusId = profile?.StatusId; if (statusId != null) { IsBusy = true; var recommendationsList = await _recommendationsService.GetRecommendationsAsync(statusId.Value, LifecycleToken); _models.Edit((innerList) => { innerList.Clear(); innerList.AddRange(recommendationsList.Data); }); } } catch (Exception e) { await _errorHandler.HandleAsync(e); } finally { IsBusy = false; } } } }
36.428571
109
0.604482
[ "Apache-2.0" ]
epam/COVID-Resistance-Mobile
src/Covi/Features/Recommendations/RecommendationsViewModel.cs
3,572
C#
using BlazingCRM.Docker.Data; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace BlazingCRM.Docker { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(); services.AddServerSideBlazor(); services.AddEntityFrameworkSqlite().AddDbContext<SqlDbContext>(); services.AddScoped<IClienteService, ClienteService>(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapBlazorHub(); endpoints.MapFallbackToPage("/_Host"); }); } } }
29.132075
143
0.59715
[ "MIT" ]
EtabetaWeb/BlazingCRM.Docker
AppCode/BlazingCRM.Docker/Startup.cs
1,544
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SQLite; namespace SeuCanto { class Reserva_QuartoDAO { public void Create(Reserva_Quarto r) { // Instância de Database para gerenciar a conexão com o banco. // Essa instância é única para toda aplicação, // pois Database segue o padrão Singleton Database dbQuarto = Database.GetInstance(); //OBS!! string qry = string.Format("INSERT INTO reserva_quarto(cod_cli,cod_quarto,data_ini_aluguel, data_devol, preco_total,cod_func) " + "VALUES('{0}','{1}','{2}','{3}','{4}','{5}')", r.Cliente.Codigo,r.Quarto.Nro_quarto, r.DataIniAluguel.ToString("yyyy-MM-dd"), r.DataEntrega.ToString("yyyy-MM-dd"), r.PrecoTotal.ToString("F"), r.CodFunc); // Uso a instância de Database para executar o comando sql. dbQuarto.ExecuteSQL(qry); } public Reserva_Quarto Read(int codigo) { Reserva_Quarto reserva_quarto = null; SQLiteConnection conexao = Database.GetInstance().GetConnection(); string qry = "SELECT cod_cli,cod_quarto,data_ini_aluguel, data_devol, preco_total,cod_reserva, cod_func FROM reserva_quarto WHERE cod_reserva = " + codigo; if (conexao.State != System.Data.ConnectionState.Open) conexao.Open(); SQLiteCommand comm = new SQLiteCommand(qry, conexao); SQLiteDataReader dr = comm.ExecuteReader(); if (dr.Read()) // A busca por chave primária só retorna um objeto { // Cria um objeto reserva_quarto para transferir os dados // do banco para a aplicação (DTO) reserva_quarto = new Reserva_Quarto(); ClienteDAO clienteDao = new ClienteDAO(); reserva_quarto.Cliente = clienteDao.Read(dr.GetInt32(0)); QuartoDAO quartoDao = new QuartoDAO(); reserva_quarto.Quarto = quartoDao.Read(dr.GetInt32(1)); reserva_quarto.DataIniAluguel = DateTime.Parse(dr.GetString(2)); reserva_quarto.DataEntrega = DateTime.Parse(dr.GetString(3)); //reserva_quarto.PrecoTotal = dr.GetDecimal(4); reserva_quarto.PrecoTotal = decimal.Parse(dr.GetString(4)); reserva_quarto.CodReserva = dr.GetInt32(5); reserva_quarto.CodFunc = dr.GetInt32(6); } dr.Close(); conexao.Close(); return reserva_quarto; } public void Update(Reserva_Quarto r) { Database dbQuarto = Database.GetInstance(); string qry = string.Format("UPDATE reserva_quarto SET cod_cli ='{0}',cod_quarto='{1}',data_ini_aluguel='{2}', data_devol='{3}'," + "preco_total='{4}', cod_func ='{5}' WHERE cod_reserva={6}", r.Cliente.Codigo,r.Quarto.Nro_quarto, r.DataIniAluguel.ToString("yyy-MM-dd"), r.DataEntrega.ToString("yyyy-MM-dd"),r.PrecoTotal.ToString("F"),r.CodFunc,r.CodReserva); dbQuarto.ExecuteSQL(qry); } public void Delete(int codigo) { Database dbQuarto = Database.GetInstance(); string qry = "DELETE FROM reserva_quarto WHERE cod_reserva =" + codigo; dbQuarto.ExecuteSQL(qry); } public List<Reserva_Quarto> ListAll() { List<Reserva_Quarto> lista = new List<Reserva_Quarto>(); Reserva_Quarto reserva_quarto = null; SQLiteConnection conexao = Database.GetInstance().GetConnection(); string qry = "SELECT cod_cli,cod_quarto,data_ini_aluguel, data_devol, preco_total,cod_reserva, cod_func FROM reserva_quarto"; if (conexao.State != System.Data.ConnectionState.Open) conexao.Open(); SQLiteCommand comm = new SQLiteCommand(qry, conexao); SQLiteDataReader dr = comm.ExecuteReader(); while (dr.Read()) { // Cria um objeto reserva_quarto para transferir os dados // do banco para a aplicação (DTO) reserva_quarto = new Reserva_Quarto(); ClienteDAO clienteDao = new ClienteDAO(); reserva_quarto.Cliente = clienteDao.Read(dr.GetInt32(0)); if(reserva_quarto.Cliente==null) { reserva_quarto.NomeCliente = null; } else { reserva_quarto.NomeCliente = reserva_quarto.Cliente.Nome; } QuartoDAO quartoDao = new QuartoDAO(); reserva_quarto.Quarto = quartoDao.Read(dr.GetInt32(1)); if(reserva_quarto.Quarto==null) { reserva_quarto.PrecoQuarto = null; } else { reserva_quarto.PrecoQuarto = Convert.ToString(reserva_quarto.Quarto.PrecoDia); } reserva_quarto.DataIniAluguel = DateTime.Parse(dr.GetString(2)); reserva_quarto.DataEntrega = DateTime.Parse(dr.GetString(3)); //reserva_quarto.PrecoTotal = dr.GetDecimal(4); reserva_quarto.PrecoTotal = decimal.Parse(dr.GetString(4)); reserva_quarto.CodReserva = dr.GetInt32(5); reserva_quarto.CodFunc = dr.GetInt32(6); lista.Add(reserva_quarto); // Adiciona o objeto na lista de resultados } dr.Close(); conexao.Close(); // fechar a conexão return lista; } public List<Reserva_Quarto> FindByName(string nome) { List<Reserva_Quarto> lista = new List<Reserva_Quarto>(); Reserva_Quarto reserva_quarto = null; SQLiteConnection conexao = Database.GetInstance().GetConnection(); string qry; if (nome != "") // verifica se a consulta não é vazia qry = string.Format("SELECT rb.cod_cli,rb.cod_quarto,rb.data_ini_aluguel, rb.data_devol, rb.preco_total,rb.cod_reserva, rb.cod_func FROM reserva_quarto rb, cliente c" + " WHERE rb.cod_cli = c.codigo AND c.nome LIKE '%{0}%' ;", nome); else qry = "SELECT cod_cli,cod_quarto,data_ini_aluguel, data_devol, preco_total,cod_reserva, cod_func FROM reserva_quarto"; if (conexao.State != System.Data.ConnectionState.Open) conexao.Open(); SQLiteCommand comm = new SQLiteCommand(qry, conexao); SQLiteDataReader dr = comm.ExecuteReader(); while (dr.Read()) { // Cria um objeto reserva_quarto para transferir os dados // do banco para a aplicação (DTO) reserva_quarto = new Reserva_Quarto(); ClienteDAO clienteDao = new ClienteDAO(); reserva_quarto.Cliente = clienteDao.Read(dr.GetInt32(0)); if (reserva_quarto.Cliente == null) { reserva_quarto.NomeCliente = null; } else { reserva_quarto.NomeCliente = reserva_quarto.Cliente.Nome; } QuartoDAO quartoDao = new QuartoDAO(); reserva_quarto.Quarto = quartoDao.Read(dr.GetInt32(1)); if (reserva_quarto.Quarto == null) { reserva_quarto.PrecoQuarto = null; } else { reserva_quarto.PrecoQuarto = Convert.ToString(reserva_quarto.Quarto.PrecoDia); } reserva_quarto.DataIniAluguel = DateTime.Parse(dr.GetString(2)); reserva_quarto.DataEntrega = DateTime.Parse(dr.GetString(3)); //reserva_quarto.PrecoTotal = dr.GetDecimal(4); reserva_quarto.PrecoTotal = decimal.Parse(dr.GetString(4)); reserva_quarto.CodReserva = dr.GetInt32(5); reserva_quarto.CodFunc = dr.GetInt32(6); lista.Add(reserva_quarto); // Adiciona o objeto na lista de resultados } dr.Close(); conexao.Close(); // fechar a conexão return lista; } } }
41.440758
184
0.554209
[ "MIT" ]
Nany07/SeuCanto
SeuCanto/DAO/Reserva_QuartoDAO.cs
8,767
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace TargetApp { public partial class MainForm : Form { public MainForm() { InitializeComponent(); } private void ButtonFlexGridClick(object sender, EventArgs e) { using (var dlg = new FlexGridForm()) { dlg.ShowDialog(this); } } } }
19.666667
68
0.587571
[ "Apache-2.0" ]
Codeer-Software/Friendly.C1.Win
Project/TargetApp/MainForm.cs
533
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace DevProjWebApp.Models { public class GoalViewModel { [Required] public string Name { get; set; } [Required] public string Description { get; set; } [Required] public string GoalDueBy { get; set; } public string Id { get; set; } } }
20.714286
48
0.583908
[ "MIT" ]
Ara225/DevProj
DevProjWebApp/Models/GoalViewModel.cs
437
C#
//------------------------------------------------------------------------------ // <auto-generated /> // // This file was automatically generated by SWIG (http://www.swig.org). // Version 3.0.9 // // Do not make changes to this file unless you know what you are doing--modify // the SWIG interface file instead. //------------------------------------------------------------------------------ using System; using System.Runtime.InteropServices; using System.ComponentModel; namespace Tizen.NUI { internal class SWIGTYPE_p_Dali__CallbackBase { private global::System.Runtime.InteropServices.HandleRef swigCPtr; internal SWIGTYPE_p_Dali__CallbackBase(global::System.IntPtr cPtr, bool futureUse) { swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); } /// <summary> /// The Constructor. /// </summary> /// <since_tizen> 4 </since_tizen> protected SWIGTYPE_p_Dali__CallbackBase() { swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); } internal static global::System.Runtime.InteropServices.HandleRef getCPtr(SWIGTYPE_p_Dali__CallbackBase obj) { return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; } } }
34.439024
137
0.597734
[ "Apache-2.0" ]
EwoutH/TizenFX
src/Tizen.NUI/src/internal/SWIGTYPE_p_Dali__CallbackBase.cs
1,412
C#
// Copyright 2009-2014 Matvei Stefarov <me@matvei.org> using System; using JetBrains.Annotations; namespace fCraft { /// <summary> Provides TryParse method, for parsing enumerations. </summary> public static class EnumUtil { /// <summary> Tries to parse a given value as an enumeration. /// Even if value is numeric, this method still ensures that given number is among the enumerated constants. /// This differs in behavior from Enum.Parse, which accepts any valid numeric string (that fits into enumeration's base type). </summary> /// <typeparam name="TEnum"> Enumeration type. </typeparam> /// <param name="value"> Raw string value to parse. </param> /// <param name="output"> Parsed enumeration to output. Set to default(TEnum) on failure. </param> /// <param name="ignoreCase"> Whether parsing should be case-insensitive. </param> /// <returns> Whether parsing succeeded. </returns> /// <exception cref="ArgumentNullException"> value is null. </exception> public static bool TryParse<TEnum>( [NotNull] string value, out TEnum output, bool ignoreCase ) { if( value == null ) throw new ArgumentNullException( "value" ); try { output = (TEnum)Enum.Parse( typeof( TEnum ), value, ignoreCase ); return Enum.IsDefined( typeof( TEnum ), output ); } catch( ArgumentException ) { } catch( OverflowException ) { } output = default( TEnum ); return false; } /// <summary> Tries to parse a given value as an enumeration, with partial-name completion. /// If there is an exact name match, exact numeric match, or a single partial name match, completion succeeds. /// If there are no matches, multiple partial matches, or if value was an empty string, completion fails. /// Even if value is numeric, this method still ensures that given number is among the enumerated constants. /// This differs in behavior from Enum.Parse, which accepts any valid numeric string (that fits into enumeration's base type). </summary> /// <typeparam name="TEnum"> Enumeration type. </typeparam> /// <param name="value"> Raw string value to parse. </param> /// <param name="output"> Parsed enumeration to output. Set to default(TEnum) on failure. </param> /// <param name="ignoreCase"> Whether parsing should be case-insensitive. </param> /// <returns> Whether parsing/completion succeeded. </returns> /// <exception cref="ArgumentNullException"> value is null. </exception> public static bool TryComplete<TEnum>( [NotNull] string value, out TEnum output, bool ignoreCase ) { if( value == null ) throw new ArgumentNullException( "value" ); output = default(TEnum); // first, try to find an exact match try { output = (TEnum)Enum.Parse( typeof( TEnum ), value, ignoreCase ); if( Enum.IsDefined( typeof( TEnum ), output ) ) { return true; } } catch( ArgumentException ) { // No exact match found. Proceed unless value was an empty string. if( value.Length == 0 ) return false; } catch( OverflowException ) { // Value was a numeric string, beyond enum's scope. return false; } // Try name completion bool matchFound = false; StringComparison comparison = (ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); foreach( string name in Enum.GetNames( typeof( TEnum ) ) ) { if( name.StartsWith( value, comparison ) ) { if( matchFound ) { // Multiple matches found. Fail. output = default(TEnum); return false; } else { // First (and hopefully only) partial match found. output = (TEnum)Enum.Parse( typeof( TEnum ), name ); matchFound = true; } } } // Either 0 or 1 match found. return matchFound; } } }
54.243902
145
0.575315
[ "MIT", "Unlicense" ]
fragmer/fCraft
fCraft/Utils/EnumUtil.cs
4,448
C#
using System; using UnityEngine.Rendering; namespace UnityEngine.Experimental.Rendering.HDPipeline { [Serializable, VolumeComponentMenu("Post-processing/White Balance")] public sealed class WhiteBalance : VolumeComponent, IPostProcessComponent { [Tooltip("Sets the white balance to a custom color temperature.")] public ClampedFloatParameter temperature = new ClampedFloatParameter(0f, -100, 100f); [Tooltip("Sets the white balance to compensate for a green or magenta tint.")] public ClampedFloatParameter tint = new ClampedFloatParameter(0f, -100, 100f); public bool IsActive() { return !Mathf.Approximately(temperature.value, 0f) || !Mathf.Approximately(tint.value, 0f); } } }
35.590909
93
0.694764
[ "Apache-2.0", "BSD-3-Clause" ]
0x8BADFOOD/simulator
Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/WhiteBalance.cs
783
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace ProgramABB.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
34.354839
151
0.581221
[ "MIT" ]
rarcz29/ProgramABB
src/Properties/Settings.Designer.cs
1,067
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using CSC.Common.Infrastructure.Utilities; using CSC.CSClassroom.Model.Classrooms; using CSC.CSClassroom.Model.Users; using CSC.CSClassroom.Repository; using Microsoft.EntityFrameworkCore; using MoreLinq; namespace CSC.CSClassroom.Service.Classrooms { /// <summary> /// Performs section operations. /// </summary> public class SectionService : ISectionService { /// <summary> /// The database context. /// </summary> private readonly DatabaseContext _dbContext; /// <summary> /// Ensures that sections being created/modified are valid. /// </summary> private readonly ISectionValidator _sectionValidator; /// <summary> /// Constructor. /// </summary> public SectionService( DatabaseContext dbContext, ISectionValidator sectionValidator) { _dbContext = dbContext; _sectionValidator = sectionValidator; } /// <summary> /// Returns the section with the given name. /// </summary> public async Task<Section> GetSectionAsync(string classroomName, string sectionName) { var classroom = await LoadClassroomAsync(classroomName); if (classroom == null) { return null; } return await _dbContext.Sections .Where(section => section.ClassroomId == classroom.Id) .Include(section => section.SectionGradebooks) .Include(section => section.SectionRecipients) .SingleOrDefaultAsync(section => section.Name == sectionName); } /// <summary> /// Returns all section memberships for the given section. /// </summary> public async Task<IList<SectionMembership>> GetSectionStudentsAsync( string classroomName, string sectionName) { var classroom = await LoadClassroomAsync(classroomName); var section = classroom.Sections .Single(s => s.Name == sectionName); return await _dbContext.SectionMemberships .Where(sm => sm.ClassroomMembership.ClassroomId == section.ClassroomId) .Where(sm => sm.SectionId == section.Id) .Include(sm => sm.ClassroomMembership) .ThenInclude(cm => cm.User) .ToListAsync(); } /// <summary> /// Creates a section. /// </summary> public async Task<bool> CreateSectionAsync( string classroomName, Section section, IModelErrorCollection errors) { var classroom = await LoadClassroomAsync(classroomName); section.ClassroomId = classroom.Id; if (!await _sectionValidator.ValidateSectionAsync(section, errors)) { return false; } _dbContext.Add(section); await _dbContext.SaveChangesAsync(); return true; } /// <summary> /// Updates a section. /// </summary> public async Task<bool> UpdateSectionAsync( string classroomName, Section section, IModelErrorCollection errors) { var classroom = await LoadClassroomAsync(classroomName); section.ClassroomId = classroom.Id; var currentSection = await _dbContext.Sections .Where(s => s.Id == section.Id) .SingleOrDefaultAsync(); _dbContext.Entry(currentSection).State = EntityState.Detached; if (!await _sectionValidator.ValidateSectionAsync(section, errors)) { return false; } UpdateSection(section); _dbContext.Update(section); await _dbContext.SaveChangesAsync(); return true; } /// <summary> /// Removes a section. /// </summary> public async Task DeleteSectionAsync(string classroomName, string sectionName) { var section = await GetSectionAsync(classroomName, sectionName); _dbContext.Sections.Remove(section); await _dbContext.SaveChangesAsync(); } /// <summary> /// Updates a classroom. /// </summary> private void UpdateSection(Section section) { _dbContext.RemoveUnwantedObjects ( _dbContext.SectionGradebooks, sectionGradebook => sectionGradebook.Id, sectionGradebook => sectionGradebook.SectionId == section.Id, section.SectionGradebooks ); _dbContext.RemoveUnwantedObjects ( _dbContext.SectionRecipients, sectionRecipient => sectionRecipient.Id, sectionRecipient => sectionRecipient.SectionId == section.Id, section.SectionRecipients ); } /// <summary> /// Returns the classroom with the given name. /// </summary> private async Task<Classroom> LoadClassroomAsync(string classroomName) { return await _dbContext.Classrooms .Where(c => c.Name == classroomName) .Include(c => c.Sections) .SingleOrDefaultAsync(); } } }
25.397727
86
0.709396
[ "MIT" ]
CSClassroom/CSClassroom
Services/src/CSClassroom/CSClassroom.Service/Classrooms/SectionService.cs
4,472
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // // This file was autogenerated by a tool. // Do not modify it. // namespace Microsoft.Azure.Batch { using Models = Microsoft.Azure.Batch.Protocol.Models; using System; using System.Collections.Generic; using System.Linq; /// <summary> /// The compute node's task info class. /// </summary> public partial class TaskInformation : IPropertyMetadata { #region Constructors internal TaskInformation(Models.TaskInformation protocolObject) { this.ExecutionInformation = UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.ExecutionInfo, o => new TaskExecutionInformation(o).Freeze()); this.JobId = protocolObject.JobId; this.SubtaskId = protocolObject.SubtaskId; this.TaskId = protocolObject.TaskId; this.TaskState = UtilitiesInternal.MapEnum<Models.TaskState, Common.TaskState>(protocolObject.TaskState); this.TaskUrl = protocolObject.TaskUrl; } #endregion Constructors #region TaskInformation /// <summary> /// Gets the execution information for the task. /// </summary> public TaskExecutionInformation ExecutionInformation { get; } /// <summary> /// Gets the job id. /// </summary> public string JobId { get; } /// <summary> /// Gets the subtask id. /// </summary> public int? SubtaskId { get; } /// <summary> /// Gets the task id. /// </summary> public string TaskId { get; } /// <summary> /// Gets the task state. /// </summary> public Common.TaskState TaskState { get; } /// <summary> /// Gets the task URL. /// </summary> public string TaskUrl { get; } #endregion // TaskInformation #region IPropertyMetadata bool IModifiable.HasBeenModified { //This class is compile time readonly so it cannot have been modified get { return false; } } bool IReadOnly.IsReadOnly { get { return true; } set { // This class is compile time readonly already } } #endregion // IPropertyMetadata #region Internal/private methods /// <summary> /// Converts a collection of protocol layer objects to object layer collection objects. /// </summary> internal static IList<TaskInformation> ConvertFromProtocolCollection(IEnumerable<Models.TaskInformation> protoCollection) { ConcurrentChangeTrackedModifiableList<TaskInformation> converted = UtilitiesInternal.CollectionToThreadSafeCollectionIModifiable( items: protoCollection, objectCreationFunc: o => new TaskInformation(o)); return converted; } /// <summary> /// Converts a collection of protocol layer objects to object layer collection objects, in a frozen state. /// </summary> internal static IList<TaskInformation> ConvertFromProtocolCollectionAndFreeze(IEnumerable<Models.TaskInformation> protoCollection) { ConcurrentChangeTrackedModifiableList<TaskInformation> converted = UtilitiesInternal.CollectionToThreadSafeCollectionIModifiable( items: protoCollection, objectCreationFunc: o => new TaskInformation(o).Freeze()); converted = UtilitiesInternal.CreateObjectWithNullCheck(converted, o => o.Freeze()); return converted; } /// <summary> /// Converts a collection of protocol layer objects to object layer collection objects, with each object marked readonly /// and returned as a readonly collection. /// </summary> internal static IReadOnlyList<TaskInformation> ConvertFromProtocolCollectionReadOnly(IEnumerable<Models.TaskInformation> protoCollection) { IReadOnlyList<TaskInformation> converted = UtilitiesInternal.CreateObjectWithNullCheck( UtilitiesInternal.CollectionToNonThreadSafeCollection( items: protoCollection, objectCreationFunc: o => new TaskInformation(o).Freeze()), o => o.AsReadOnly()); return converted; } #endregion // Internal/private methods } }
34.514493
161
0.629645
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/batch/Microsoft.Azure.Batch/src/Generated/TaskInformation.cs
4,763
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace TOFSensorSampleCommon.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
35.677419
152
0.56962
[ "Apache-2.0" ]
omron-devhub/b5l_TOFsensor_distance_forCsharp
Properties/Settings.Designer.cs
1,108
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VariableNaming { class Program { static void Main(string[] args) { int num1 = 10; int num2 = 15; int resultAdd; int resultMinus; int resultDivide; int resultMultiply; int resultModulus; resultAdd = num1 + num2; resultMinus = num2 - num1; resultDivide = num2 / num1; resultMultiply = num2 * num1; resultModulus = num2 % num1; Console.WriteLine("The result of " + num1 + " + " + num2 + " = " + resultAdd); Console.WriteLine("The result of ${0} - ${1} = ${2}", num1, num2, resultMinus); Console.WriteLine("The result of ${1} / ${0} = ${2}", num2, num1, resultDivide); Console.WriteLine("The result of " + num2 + " * " + num1 + " = " + resultMultiply); Console.WriteLine("The result of " + num2 + " % " + num1 + " = " + resultModulus); //wanted to try using other form } } }
31.864865
95
0.517388
[ "MIT" ]
ac132998/Chapter-2
VariableNaming/VariableNaming/Program.cs
1,181
C#
using System; using System.Threading.Tasks; using Feature.Manager.Api.Models; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.Extensions.Logging; namespace Feature.Manager.Api.StartupExtensions { public static class Database { public static async Task MigrateOrFail(this DatabaseFacade db, ILogger<ApplicationContext> logger) { for (var i = 0; i <= 3; i++) { var waitTime = new[] {1, 3, 8, 10}[i]; logger.LogInformation($"Db connection attempt in {waitTime} seconds"); await Task.Delay(TimeSpan.FromSeconds(waitTime)); if (await TryMigrate(db)) { return; } logger.LogWarning("Connection failed..."); } throw new RetryLimitExceededException("Couldn't connect to database"); } private static async Task<bool> TryMigrate(DatabaseFacade db) { try { var canConnect = await db.CanConnectAsync(); if (!canConnect) { return false; } await db.MigrateAsync(); return true; } catch { return false; } } } }
30.680851
106
0.533981
[ "MIT" ]
fossapps/Feature.Manager
Feature.Manager.Api/StartupExtensions/Database.cs
1,442
C#
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Converters { /// <summary> /// Converts an <see cref="Enum"/> to and from its name string value. /// </summary> /// <summary> /// Converts an <see cref="Enum"/> to and from its name string value. /// </summary> public class StringEnumConverter : JsonConverter { private readonly Dictionary<Type, BidirectionalDictionary<string, string>> _enumMemberNamesPerType = new Dictionary<Type, BidirectionalDictionary<string, string>>(); /// <summary> /// Gets or sets a value indicating whether the written enum text should be camel case. /// </summary> /// <value><c>true</c> if the written enum text will be camel case; otherwise, <c>false</c>.</value> public bool CamelCaseText { get; set; } /// <summary> /// Writes the JSON representation of the object. /// </summary> /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param> /// <param name="value">The value.</param> /// <param name="serializer">The calling serializer.</param> public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value == null) { writer.WriteNull(); return; } Enum e = (Enum)value; string enumName = e.ToString("G"); if (char.IsNumber(enumName[0]) || enumName[0] == '-') { writer.WriteValue(value); } else { BidirectionalDictionary<string, string> map = GetEnumNameMap(e.GetType()); string resolvedEnumName; map.TryGetByFirst(enumName, out resolvedEnumName); resolvedEnumName = resolvedEnumName ?? enumName; if (CamelCaseText) resolvedEnumName = StringUtils.ToCamelCase(resolvedEnumName); writer.WriteValue(resolvedEnumName); } } /// <summary> /// Reads the JSON representation of the object. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> to read from.</param> /// <param name="objectType">Type of the object.</param> /// <param name="existingValue">The existing value of object being read.</param> /// <param name="serializer">The calling serializer.</param> /// <returns>The object value.</returns> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { Type t = (ReflectionUtils.IsNullableType(objectType)) ? Nullable.GetUnderlyingType(objectType) : objectType; if (reader.TokenType == JsonToken.Null) { if (!ReflectionUtils.IsNullableType(objectType)) throw new Exception("Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType)); return null; } if (reader.TokenType == JsonToken.String) { var map = GetEnumNameMap(t); string resolvedEnumName; map.TryGetBySecond(reader.Value.ToString(), out resolvedEnumName); resolvedEnumName = resolvedEnumName ?? reader.Value.ToString(); return Enum.Parse(t, resolvedEnumName, true); } if (reader.TokenType == JsonToken.Integer) return ConvertUtils.ConvertOrCast(reader.Value, CultureInfo.InvariantCulture, t); throw new Exception("Unexpected token when parsing enum. Expected String or Integer, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); } /// <summary> /// A cached representation of the Enum string representation to respect per Enum field name. /// </summary> /// <param name="t">The type of the Enum.</param> /// <returns>A map of enum field name to either the field name, or the configured enum member name (<see cref="EnumMemberAttribute"/>).</returns> private BidirectionalDictionary<string, string> GetEnumNameMap(Type t) { BidirectionalDictionary<string, string> map; if (!_enumMemberNamesPerType.TryGetValue(t, out map)) { lock (_enumMemberNamesPerType) { if (_enumMemberNamesPerType.TryGetValue(t, out map)) return map; map = new BidirectionalDictionary<string, string>( StringComparer.OrdinalIgnoreCase, StringComparer.OrdinalIgnoreCase); foreach (FieldInfo f in t.GetFields()) { string n1 = f.Name; string n2; #if !NET20 n2 = f.GetCustomAttributes(typeof (EnumMemberAttribute), true) .Cast<EnumMemberAttribute>() .Select(a => a.Value) .SingleOrDefault() ?? f.Name; #else n2 = f.Name; #endif string s; if (map.TryGetBySecond(n2, out s)) { throw new Exception("Enum name '{0}' already exists on enum '{1}'." .FormatWith(CultureInfo.InvariantCulture, n2, t.Name)); } map.Add(n1, n2); } _enumMemberNamesPerType[t] = map; } } return map; } /// <summary> /// Determines whether this instance can convert the specified object type. /// </summary> /// <param name="objectType">Type of the object.</param> /// <returns> /// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>. /// </returns> public override bool CanConvert(Type objectType) { Type t = (ReflectionUtils.IsNullableType(objectType)) ? Nullable.GetUnderlyingType(objectType) : objectType; return t.IsEnum; } } }
36.649485
170
0.63488
[ "MIT" ]
redarrowlabs/pubnub-c-sharp
monotouch/Newtonsoft.Json/Converters/StringEnumConverter.cs
7,110
C#
using Android.Runtime; namespace WoWonder.Helpers.Model { public static class Stickers { ///Get your stickers from here >>> https://chatsticker.com/ ///Get your stickers from here >>> https://store.line.me/ //############################# Stickers ############################# #region rappit public static string Sticker1 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1165013/android/stickers/6719608.png"; public static string Sticker2 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1165013/android/stickers/6719613.png"; public static string Sticker3 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1165013/android/stickers/6719615.png"; public static string Sticker4 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1165013/android/stickers/6719626.png"; public static string Sticker5 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1165013/android/stickers/6719628.png"; public static string Sticker6 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1165013/android/stickers/6719631.png"; public static string Sticker7 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1165013/android/stickers/6719633.png"; public static string Sticker8 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1165013/android/stickers/6719647.png"; public static string Sticker9 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1253330/android/stickers/10274057.png"; public static string Sticker10 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1253330/android/stickers/10274058.png"; public static string Sticker11 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1253330/android/stickers/10274071.png"; public static string Sticker12 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1253330/android/stickers/10274075.png"; public static string Sticker13 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1253330/android/stickers/10274081.png"; public static string Sticker14 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1253330/android/stickers/10274088.png"; public static string Sticker15 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1253330/android/stickers/10274089.png"; public static JavaList<string> StickerList1 = new JavaList<string> { Sticker1, Sticker2, Sticker3, Sticker4, Sticker5, Sticker6, Sticker7, Sticker8, Sticker9, Sticker10, Sticker11, Sticker12, Sticker13, Sticker14, Sticker15 }; #endregion #region Water Drop public static string Sticker16 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1156666/android/stickers/6382400.png"; public static string Sticker17 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1156666/android/stickers/6382401.png"; public static string Sticker18 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1156666/android/stickers/6382405.png"; public static string Sticker19 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1156666/android/stickers/6382403.png"; public static string Sticker20 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1156666/android/stickers/6382414.png"; public static string Sticker21 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1156666/android/stickers/6382409.png"; public static string Sticker22 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1156666/android/stickers/6382412.png"; public static string Sticker23 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1156666/android/stickers/6382417.png"; public static string Sticker24 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1156666/android/stickers/6382430.png"; public static string Sticker25 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1156666/android/stickers/6382428.png"; public static string Sticker26 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1156666/android/stickers/6382425.png"; public static string Sticker27 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1156666/android/stickers/6382433.png"; public static string Sticker28 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1156666/android/stickers/6382437.png"; public static string Sticker29 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1156666/android/stickers/6382435.png"; public static string Sticker30 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1156666/android/stickers/6382419.png"; public static string Sticker31 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1156666/android/stickers/6382422.png"; public static JavaList<string> StickerList2 = new JavaList<string> { Sticker16, Sticker17, Sticker18, Sticker19, Sticker20, Sticker21, Sticker22, Sticker23, Sticker24, Sticker25, Sticker26, Sticker27, Sticker28, Sticker29, Sticker30, Sticker31 }; #endregion #region Monster public static string Sticker32 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/5957/android/stickers/9913417.png"; public static string Sticker33 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/5957/android/stickers/9913416.png"; public static string Sticker34 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/5957/android/stickers/9913421.png"; public static string Sticker35 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/5957/android/stickers/9913424.png"; public static string Sticker36 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/5957/android/stickers/9913426.png"; public static string Sticker37 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/5957/android/stickers/9913427.png"; public static string Sticker38 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/5957/android/stickers/9913430.png"; public static string Sticker39 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/5957/android/stickers/9913436.png"; public static string Sticker40 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/5957/android/stickers/9913432.png"; public static string Sticker41 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/5957/android/stickers/9913420.png"; public static string Sticker42 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/5957/android/stickers/9913418.png"; public static string Sticker43 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/5957/android/stickers/9913422.png"; public static string Sticker44 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/5957/android/stickers/9913438.png"; public static string Sticker45 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/5957/android/stickers/9913429.png"; public static string Sticker46 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/5957/android/stickers/9913431.png"; public static string Sticker47 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/5957/android/stickers/9913439.png"; public static string Sticker48 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/5957/android/stickers/9913435.png"; public static JavaList<string> StickerList3 = new JavaList<string> { Sticker32, Sticker33, Sticker34, Sticker35, Sticker36, Sticker37, Sticker38, Sticker39, Sticker40, Sticker41, Sticker42, Sticker43, Sticker44, Sticker45, Sticker46, Sticker47, Sticker48 }; #endregion #region NINJA Nyankko public static string Sticker49 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1001463/android/stickers/116876.png"; public static string Sticker50 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1001463/android/stickers/116877.png"; public static string Sticker51 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1001463/android/stickers/116878.png"; public static string Sticker52 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1001463/android/stickers/116879.png"; public static string Sticker53 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1001463/android/stickers/116880.png"; public static string Sticker54 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1001463/android/stickers/116881.png"; public static string Sticker55 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1001463/android/stickers/116883.png"; public static string Sticker56 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1001463/android/stickers/116884.png"; public static string Sticker57 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1001463/android/stickers/116887.png"; public static string Sticker58 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1001463/android/stickers/116888.png"; public static string Sticker59 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1001463/android/stickers/116889.png"; public static string Sticker60 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1001463/android/stickers/116890.png"; public static string Sticker61 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1001463/android/stickers/116891.png"; public static string Sticker62 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1001463/android/stickers/116892.png"; public static string Sticker63 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1001463/android/stickers/116893.png"; public static string Sticker64 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1001463/android/stickers/116894.png"; public static string Sticker65 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1001463/android/stickers/116895.png"; public static string Sticker66 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1001463/android/stickers/116896.png"; public static string Sticker67 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1001463/android/stickers/116897.png"; public static string Sticker68 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1001463/android/stickers/116898.png"; public static string Sticker69 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1001463/android/stickers/116899.png"; public static string Sticker70 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1001463/android/stickers/116900.png"; public static string Sticker71 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1001463/android/stickers/116901.png"; public static string Sticker72 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1001463/android/stickers/116902.png"; public static string Sticker73 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1001463/android/stickers/116903.png"; public static string Sticker74 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1001463/android/stickers/116904.png"; public static string Sticker75 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1001463/android/stickers/116905.png"; public static string Sticker76 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1001463/android/stickers/116906.png"; public static string Sticker77 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1001463/android/stickers/116907.png"; public static string Sticker78 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1001463/android/stickers/116908.png"; public static string Sticker79 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1001463/android/stickers/116909.png"; public static string Sticker80 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1001463/android/stickers/116910.png"; public static string Sticker81 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1001463/android/stickers/116911.png;"; public static string Sticker82 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1001463/android/stickers/116912.png"; public static JavaList<string> StickerList4 = new JavaList<string> { Sticker49, Sticker50, Sticker51, Sticker52, Sticker53, Sticker54, Sticker55, Sticker56, Sticker57, Sticker58, Sticker59, Sticker60, Sticker61, Sticker62, Sticker63, Sticker64, Sticker65, Sticker66, Sticker67, Sticker68, Sticker69, Sticker70, Sticker71, Sticker72, Sticker73, Sticker74, Sticker75, Sticker76, Sticker77, Sticker78, Sticker79, Sticker80, Sticker81, Sticker82 }; #endregion #region So Much Love public static string Sticker83 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1210792/android/stickers/8561130.png"; public static string Sticker84 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1210792/android/stickers/8561131.png"; public static string Sticker85 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1210792/android/stickers/8561132.png"; public static string Sticker86 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1210792/android/stickers/8561133.png"; public static string Sticker87 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1210792/android/stickers/8561134.png"; public static string Sticker88 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1210792/android/stickers/8561135.png"; public static string Sticker89 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1210792/android/stickers/8561136.png"; public static string Sticker90 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1210792/android/stickers/8561137.png"; public static string Sticker91 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1210792/android/stickers/8561138.png"; public static string Sticker92 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1210792/android/stickers/8561139.png"; public static string Sticker93 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1210792/android/stickers/8561140.png"; public static string Sticker94 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1210792/android/stickers/8561141.png"; public static string Sticker95 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1210792/android/stickers/8561142.png"; public static string Sticker96 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1210792/android/stickers/8561143.png"; public static string Sticker97 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1210792/android/stickers/8561144.png"; public static string Sticker98 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1210792/android/stickers/8561145.png"; public static string Sticker99 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1210792/android/stickers/8561146.png"; public static string Sticker100 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1210792/android/stickers/8561147.png"; public static string Sticker101 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1210792/android/stickers/8561148.png"; public static string Sticker102 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1210792/android/stickers/8561149.png"; public static string Sticker103 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1210792/android/stickers/8561150.png"; public static string Sticker104 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1210792/android/stickers/8561151.png"; public static string Sticker105 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1210792/android/stickers/8561152.png"; public static string Sticker106 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1210792/android/stickers/8561155.png"; public static string Sticker107 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1210792/android/stickers/8561156.png"; public static string Sticker108 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1210792/android/stickers/8561157.png"; public static string Sticker109 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1210792/android/stickers/8561158.png"; public static string Sticker110 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1210792/android/stickers/8561159.png"; public static string Sticker111 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1210792/android/stickers/8561160.png"; public static string Sticker112 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1210792/android/stickers/8561161.png"; public static string Sticker113 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1210792/android/stickers/8561162.png"; public static string Sticker114 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1210792/android/stickers/8561163.png"; public static string Sticker115 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1210792/android/stickers/8561164.png"; public static string Sticker116 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1210792/android/stickers/8561165.png"; public static string Sticker117 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1210792/android/stickers/8561166.png"; public static string Sticker118 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1210792/android/stickers/8561167.png"; public static JavaList<string> StickerList5 = new JavaList<string> { Sticker83, Sticker84, Sticker85, Sticker86, Sticker87, Sticker88, Sticker89, Sticker90, Sticker91, Sticker92, Sticker93, Sticker94, Sticker95, Sticker96, Sticker97, Sticker98, Sticker99, Sticker100, Sticker101, Sticker102, Sticker103, Sticker104, Sticker105, Sticker106, Sticker107, Sticker108, Sticker109, Sticker110, Sticker111, Sticker112, Sticker113, Sticker114, Sticker115, Sticker116, Sticker117, Sticker118 }; #endregion #region Sukkara chan public static string Sticker119 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1062824/android/stickers/2599523.png"; public static string Sticker120 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1062824/android/stickers/2599524.png"; public static string Sticker121 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1062824/android/stickers/2599525.png"; public static string Sticker122 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1062824/android/stickers/2599526.png"; public static string Sticker123 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1062824/android/stickers/2599527.png"; public static string Sticker124 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1062824/android/stickers/2599528.png"; public static string Sticker125 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1062824/android/stickers/2599529.png"; public static string Sticker126 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1062824/android/stickers/2599530.png"; public static string Sticker127 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1062824/android/stickers/2599531.png"; public static string Sticker128 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1062824/android/stickers/2599532.png"; public static string Sticker129 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1062824/android/stickers/2599533.png"; public static string Sticker130 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1062824/android/stickers/2599536.png"; public static string Sticker131 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1062824/android/stickers/2599537.png"; public static string Sticker132 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1062824/android/stickers/2599538.png"; public static string Sticker133 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1062824/android/stickers/2599539.png"; public static string Sticker134 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1062824/android/stickers/2599540.png"; public static string Sticker135 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1062824/android/stickers/2599541.png"; public static string Sticker136 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1062824/android/stickers/2599542.png"; public static string Sticker137 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1062824/android/stickers/2599543.png"; public static string Sticker138 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1062824/android/stickers/2599544.png"; public static string Sticker139 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1062824/android/stickers/2599545.png"; public static string Sticker140 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1062824/android/stickers/2599546.png"; public static string Sticker141 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1062824/android/stickers/2599547.png"; public static string Sticker142 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1062824/android/stickers/2599548.png"; public static string Sticker143 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1062824/android/stickers/2599549.png"; public static string Sticker144 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1062824/android/stickers/2599550.png"; public static string Sticker145 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1062824/android/stickers/2599551.png"; public static string Sticker146 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1062824/android/stickers/2599552.png"; public static string Sticker147 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1062824/android/stickers/2599553.png"; public static string Sticker148 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1062824/android/stickers/2599554.png"; public static string Sticker149 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1062824/android/stickers/2599555.png"; public static string Sticker150 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1062824/android/stickers/2599556.png"; public static string Sticker151 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1062824/android/stickers/2599557.png"; public static string Sticker152 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1062824/android/stickers/2599558.png"; public static string Sticker153 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1062824/android/stickers/2599559.png"; public static string Sticker154 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1062824/android/stickers/2599560.png"; public static JavaList<string> StickerList6 = new JavaList<string> { Sticker119, Sticker120, Sticker121, Sticker122, Sticker123, Sticker124, Sticker125, Sticker126, Sticker127, Sticker128, Sticker129, Sticker130, Sticker131, Sticker132, Sticker133, Sticker134, Sticker135, Sticker136, Sticker137, Sticker138, Sticker139, Sticker140, Sticker141, Sticker142, Sticker143, Sticker144, Sticker145, Sticker146, Sticker147, Sticker148, Sticker149, Sticker150, Sticker151, Sticker152, Sticker153, Sticker154 }; #endregion #region Flower Hijab public static string Sticker155 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1003801/android/stickers/214293.png"; public static string Sticker156 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1003801/android/stickers/214294.png"; public static string Sticker157 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1003801/android/stickers/214295.png"; public static string Sticker158 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1003801/android/stickers/214296.png"; public static string Sticker159 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1003801/android/stickers/214297.png"; public static string Sticker160 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1003801/android/stickers/214298.png"; public static string Sticker161 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1003801/android/stickers/214299.png"; public static string Sticker162 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1003801/android/stickers/214300.png"; public static string Sticker163 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1003801/android/stickers/214301.png"; public static string Sticker164 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1003801/android/stickers/214302.png"; public static string Sticker165 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1003801/android/stickers/214303.png"; public static string Sticker166 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1003801/android/stickers/214304.png"; public static string Sticker167 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1003801/android/stickers/214305.png"; public static string Sticker168 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1003801/android/stickers/214306.png"; public static string Sticker169 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1003801/android/stickers/214307.png"; public static string Sticker170 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1003801/android/stickers/214308.png"; public static string Sticker171 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1003801/android/stickers/214309.png"; public static string Sticker172 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1003801/android/stickers/214310.png"; public static string Sticker173 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1003801/android/stickers/214311.png"; public static string Sticker174 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1003801/android/stickers/214312.png"; public static string Sticker175 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1003801/android/stickers/214313.png"; public static string Sticker176 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1003801/android/stickers/214314.png"; public static string Sticker177 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1003801/android/stickers/214315.png"; public static string Sticker178 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1003801/android/stickers/214316.png"; public static string Sticker179 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1003801/android/stickers/214317.png"; public static string Sticker180 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1003801/android/stickers/214318.png"; public static string Sticker181 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1003801/android/stickers/214319.png"; public static string Sticker182 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1003801/android/stickers/214320.png"; public static string Sticker183 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1003801/android/stickers/214321.png"; public static string Sticker184 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1003801/android/stickers/214322.png"; public static string Sticker185 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1003801/android/stickers/214323.png"; public static string Sticker186 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1003801/android/stickers/214324.png"; public static string Sticker187 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1003801/android/stickers/214325.png"; public static string Sticker188 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1003801/android/stickers/214326.png"; public static string Sticker189 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1003801/android/stickers/214327.png"; public static string Sticker190 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1003801/android/stickers/214328.png"; public static string Sticker191 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1003801/android/stickers/214329.png"; public static string Sticker192 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1003801/android/stickers/214330.png"; public static string Sticker193 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1003801/android/stickers/214331.png"; public static string Sticker194 = "https://sdl-stickershop.line.naver.jp/products/0/0/2/1003801/android/stickers/214332.png"; public static JavaList<string> StickerList7 = new JavaList<string> { Sticker155, Sticker156, Sticker157, Sticker158, Sticker159, Sticker160, Sticker161, Sticker162, Sticker163, Sticker164, Sticker165, Sticker166, Sticker167, Sticker168, Sticker169, Sticker170, Sticker171, Sticker172, Sticker173, Sticker175, Sticker176, Sticker177, Sticker178, Sticker179, Sticker180, Sticker181, Sticker182, Sticker183, Sticker184, Sticker185, Sticker186, Sticker187, Sticker188, Sticker189, Sticker190, Sticker191, Sticker192, Sticker193, Sticker194 }; #endregion #region Trendy boy public static string Sticker195 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1331246/android/stickers/13349166.png"; public static string Sticker196 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1331246/android/stickers/13349167.png"; public static string Sticker197 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1331246/android/stickers/13349168.png"; public static string Sticker198 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1331246/android/stickers/13349169.png"; public static string Sticker199 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1331246/android/stickers/13349170.png"; public static string Sticker200 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1331246/android/stickers/13349171.png"; public static string Sticker201 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1331246/android/stickers/13349172.png"; public static string Sticker202 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1331246/android/stickers/13349173.png"; public static string Sticker203 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1331246/android/stickers/13349174.png"; public static string Sticker204 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1331246/android/stickers/13349175.png"; public static string Sticker205 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1331246/android/stickers/13349176.png"; public static string Sticker206 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1331246/android/stickers/13349177.png"; public static string Sticker207 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1331246/android/stickers/13349178.png"; public static string Sticker208 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1331246/android/stickers/13349179.png"; public static string Sticker209 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1331246/android/stickers/13349180.png"; public static string Sticker210 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1331246/android/stickers/13349181.png"; public static string Sticker211 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1331246/android/stickers/13349182.png"; public static string Sticker212 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1331246/android/stickers/13349183.png"; public static string Sticker213 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1331246/android/stickers/13349184.png"; public static string Sticker214 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1331246/android/stickers/13349185.png"; public static string Sticker215 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1331246/android/stickers/13349186.png"; public static string Sticker216 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1331246/android/stickers/13349187.png"; public static string Sticker217 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1331246/android/stickers/13349188.png"; public static string Sticker218 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1331246/android/stickers/13349189.png"; public static string Sticker219 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1331246/android/stickers/13349190.png"; public static string Sticker220 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1331246/android/stickers/13349191.png"; public static string Sticker221 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1331246/android/stickers/13349192.png"; public static string Sticker222 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1331246/android/stickers/13349193.png"; public static string Sticker223 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1331246/android/stickers/13349194.png"; public static string Sticker224 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1331246/android/stickers/13349195.png"; public static string Sticker225 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1331246/android/stickers/13349196.png"; public static string Sticker226 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1331246/android/stickers/13349197.png"; public static string Sticker227 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1331246/android/stickers/13349198.png"; public static string Sticker228 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1331246/android/stickers/13349199.png"; public static string Sticker229 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1331246/android/stickers/13349200.png"; public static string Sticker230 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1331246/android/stickers/13349201.png"; public static string Sticker231 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1331246/android/stickers/13349202.png"; public static string Sticker232 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1331246/android/stickers/13349203.png"; public static string Sticker233 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1331246/android/stickers/13349204.png"; public static string Sticker234 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1331246/android/stickers/13349205.png"; public static JavaList<string> StickerList8 = new JavaList<string> { Sticker195, Sticker196, Sticker197, Sticker198, Sticker199, Sticker200, Sticker201, Sticker202, Sticker203, Sticker204, Sticker205, Sticker206, Sticker207, Sticker208, Sticker209, Sticker210, Sticker211, Sticker212, Sticker213, Sticker214, Sticker215, Sticker216, Sticker217, Sticker218, Sticker219, Sticker220, Sticker221, Sticker222, Sticker223, Sticker224, Sticker225, Sticker226, Sticker227, Sticker228, Sticker229, Sticker230, Sticker231, Sticker232, Sticker233, Sticker234 }; #endregion #region The stickman and the cat public static string Sticker235 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1191351/android/stickers/7779268.png"; public static string Sticker236 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1191351/android/stickers/7779269.png"; public static string Sticker237 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1191351/android/stickers/7779270.png"; public static string Sticker238 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1191351/android/stickers/7779271.png"; public static string Sticker239 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1191351/android/stickers/7779272.png"; public static string Sticker240 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1191351/android/stickers/7779273.png"; public static string Sticker241 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1191351/android/stickers/7779274.png"; public static string Sticker242 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1191351/android/stickers/7779275.png"; public static string Sticker243 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1191351/android/stickers/7779276.png"; public static string Sticker244 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1191351/android/stickers/7779277.png"; public static string Sticker245 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1191351/android/stickers/7779278.png"; public static string Sticker246 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1191351/android/stickers/7779279.png"; public static string Sticker247 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1191351/android/stickers/7779280.png"; public static string Sticker248 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1191351/android/stickers/7779281.png"; public static string Sticker249 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1191351/android/stickers/7779282.png"; public static string Sticker250 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1191351/android/stickers/7779283.png"; public static string Sticker251 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1191351/android/stickers/7779284.png"; public static string Sticker252 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1191351/android/stickers/7779285.png"; public static string Sticker253 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1191351/android/stickers/7779286.png"; public static string Sticker254 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1191351/android/stickers/7779287.png"; public static string Sticker255 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1191351/android/stickers/7779288.png"; public static string Sticker256 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1191351/android/stickers/7779289.png"; public static string Sticker257 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1191351/android/stickers/7779290.png"; public static string Sticker258 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1191351/android/stickers/7779291.png"; public static string Sticker259 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1191351/android/stickers/7779292.png"; public static string Sticker260 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1191351/android/stickers/7779293.png"; public static string Sticker261 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1191351/android/stickers/7779294.png"; public static string Sticker262 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1191351/android/stickers/7779295.png"; public static string Sticker263 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1191351/android/stickers/7779296.png"; public static string Sticker264 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1191351/android/stickers/7779297.png"; public static string Sticker265 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1191351/android/stickers/7779298.png"; public static string Sticker266 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1191351/android/stickers/7779299.png"; public static string Sticker267 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1191351/android/stickers/7779300.png"; public static string Sticker268 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1191351/android/stickers/7779301.png"; public static string Sticker269 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1191351/android/stickers/7779302.png"; public static string Sticker270 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1191351/android/stickers/7779303.png"; public static string Sticker271 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1191351/android/stickers/7779304.png"; public static string Sticker272 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1191351/android/stickers/7779305.png"; public static string Sticker273 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1191351/android/stickers/7779306.png"; public static string Sticker274 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/1191351/android/stickers/7779307.png"; public static JavaList<string> StickerList9 = new JavaList<string> { Sticker235, Sticker236, Sticker237, Sticker238, Sticker239, Sticker240, Sticker241, Sticker242, Sticker243, Sticker244, Sticker245, Sticker246, Sticker247, Sticker248, Sticker249, Sticker250, Sticker251, Sticker252, Sticker253, Sticker254, Sticker255, Sticker256, Sticker257, Sticker258, Sticker259, Sticker260, Sticker261, Sticker262, Sticker263, Sticker264, Sticker265, Sticker266, Sticker267, Sticker268, Sticker269, Sticker270, Sticker271, Sticker272, Sticker273, Sticker274 }; #endregion #region Chip 'n' Dale Animated public static string Sticker275 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/3296/android/stickers/1867901.png"; public static string Sticker276 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/3296/android/stickers/1867902.png"; public static string Sticker277 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/3296/android/stickers/1867903.png"; public static string Sticker278 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/3296/android/stickers/1867904.png"; public static string Sticker279 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/3296/android/stickers/1867905.png"; public static string Sticker280 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/3296/android/stickers/1867906.png"; public static string Sticker281 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/3296/android/stickers/1867907.png"; public static string Sticker282 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/3296/android/stickers/1867908.png"; public static string Sticker283 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/3296/android/stickers/1867909.png"; public static string Sticker284 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/3296/android/stickers/1867910.png"; public static string Sticker285 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/3296/android/stickers/1867911.png"; public static string Sticker286 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/3296/android/stickers/1867912.png"; public static string Sticker287 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/3296/android/stickers/1867913.png"; public static string Sticker288 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/3296/android/stickers/1867915.png"; public static string Sticker289 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/3296/android/stickers/1867916.png"; public static string Sticker290 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/3296/android/stickers/1867917.png"; public static string Sticker291 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/3296/android/stickers/1867918.png"; public static string Sticker292 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/3296/android/stickers/1867919.png"; public static string Sticker293 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/3296/android/stickers/1867920.png"; public static string Sticker294 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/3296/android/stickers/1867921.png"; public static string Sticker295 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/3296/android/stickers/1867922.png"; public static string Sticker296 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/3296/android/stickers/1867923.png"; public static string Sticker297 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/3296/android/stickers/1867924.png"; public static string Sticker298 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/3296/android/stickers/1867925.png"; public static string Sticker299 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/3296/android/stickers/1867926.png"; public static string Sticker300 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/3296/android/stickers/1867927.png"; public static string Sticker301 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/3296/android/stickers/1867928.png"; public static string Sticker302 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/3296/android/stickers/1867929.png"; public static string Sticker303 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/3296/android/stickers/1867930.png"; public static string Sticker304 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/3296/android/stickers/1867931.png"; public static string Sticker305 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/3296/android/stickers/1867932.png"; public static string Sticker306 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/3296/android/stickers/1867933.png"; public static string Sticker307 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/3296/android/stickers/1867934.png"; public static string Sticker308 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/3296/android/stickers/1867935.png"; public static string Sticker309 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/3296/android/stickers/1867936.png"; public static string Sticker310 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/3296/android/stickers/1867937.png"; public static string Sticker311 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/3296/android/stickers/1867938.png"; public static string Sticker312 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/3296/android/stickers/1867939.png"; public static string Sticker313 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/3296/android/stickers/1867941.png"; public static string Sticker314 = "https://sdl-stickershop.line.naver.jp/products/0/0/1/3296/android/stickers/1867942.png"; public static JavaList<string> StickerList10 = new JavaList<string> { Sticker275, Sticker276, Sticker277, Sticker278, Sticker279, Sticker280, Sticker281, Sticker282, Sticker283, Sticker284, Sticker285, Sticker286, Sticker287, Sticker288, Sticker289, Sticker290, Sticker291, Sticker292, Sticker293, Sticker294, Sticker295, Sticker296, Sticker297, Sticker298, Sticker299, Sticker300, Sticker301, Sticker302, Sticker303, Sticker304, Sticker305, Sticker306, Sticker307, Sticker308, Sticker309, Sticker310, Sticker311, Sticker312, Sticker313, Sticker314 }; #endregion #region Others public static string Sticker315 = "https://stickershop.line-scdn.net/stickershop/v1/sticker/68688564/ANDROID/sticker.png"; public static string Sticker316 = "https://stickershop.line-scdn.net/stickershop/v1/sticker/68688568/ANDROID/sticker.png"; public static string Sticker317 = "https://stickershop.line-scdn.net/stickershop/v1/sticker/68688570/ANDROID/sticker.png"; public static string Sticker318 = "https://stickershop.line-scdn.net/stickershop/v1/sticker/68688571/ANDROID/sticker.png"; public static string Sticker319 = "https://stickershop.line-scdn.net/stickershop/v1/sticker/68688578/ANDROID/sticker.png"; public static string Sticker320 = "https://stickershop.line-scdn.net/stickershop/v1/sticker/68688575/ANDROID/sticker.png"; public static string Sticker321 = "https://stickershop.line-scdn.net/stickershop/v1/sticker/68688576/ANDROID/sticker.png"; public static string Sticker322 = "https://stickershop.line-scdn.net/stickershop/v1/sticker/68688580/ANDROID/sticker.png"; public static string Sticker323 = "https://stickershop.line-scdn.net/stickershop/v1/sticker/22108/ANDROID/sticker.png"; public static string Sticker324 = "https://stickershop.line-scdn.net/stickershop/v1/sticker/22112/ANDROID/sticker.png"; public static string Sticker325 = "https://stickershop.line-scdn.net/stickershop/v1/sticker/22111/ANDROID/sticker.png"; public static string Sticker326 = "https://stickershop.line-scdn.net/stickershop/v1/sticker/13456187/ANDROID/sticker.png"; public static string Sticker327 = "https://stickershop.line-scdn.net/stickershop/v1/sticker/13456184/ANDROID/sticker.png"; public static string Sticker328 = "https://stickershop.line-scdn.net/stickershop/v1/sticker/13456186/ANDROID/sticker.png"; public static string Sticker329 = "https://stickershop.line-scdn.net/stickershop/v1/sticker/13456188/ANDROID/sticker.png"; public static string Sticker330 = "https://stickershop.line-scdn.net/stickershop/v1/sticker/13456182/ANDROID/sticker.png"; public static string Sticker331 = "https://stickershop.line-scdn.net/stickershop/v1/sticker/23944390/ANDROID/sticker.png"; public static string Sticker332 = "https://stickershop.line-scdn.net/stickershop/v1/sticker/23944368/ANDROID/sticker.png"; public static string Sticker333 = "https://stickershop.line-scdn.net/stickershop/v1/sticker/29135256/ANDROID/sticker.png"; public static string Sticker334 = "https://stickershop.line-scdn.net/stickershop/v1/sticker/29135257/ANDROID/sticker.png"; public static string Sticker335 = "https://stickershop.line-scdn.net/stickershop/v1/sticker/29135258/ANDROID/sticker.png"; public static string Sticker336 = "https://stickershop.line-scdn.net/stickershop/v1/sticker/29135259/ANDROID/sticker.png"; public static string Sticker337 = "https://stickershop.line-scdn.net/stickershop/v1/sticker/29135260/ANDROID/sticker.png"; public static string Sticker338 = "https://stickershop.line-scdn.net/stickershop/v1/sticker/29135261/ANDROID/sticker.png"; public static string Sticker339 = "https://stickershop.line-scdn.net/stickershop/v1/sticker/29135262/ANDROID/sticker.png"; public static string Sticker340 = "https://stickershop.line-scdn.net/stickershop/v1/sticker/29135263/ANDROID/sticker.png"; public static string Sticker341 = "https://stickershop.line-scdn.net/stickershop/v1/sticker/29135264/ANDROID/sticker.png"; public static string Sticker342 = "https://stickershop.line-scdn.net/stickershop/v1/sticker/29135265/ANDROID/sticker.png"; public static string Sticker343 = "https://stickershop.line-scdn.net/stickershop/v1/sticker/29135266/ANDROID/sticker.png"; public static string Sticker344 = "https://stickershop.line-scdn.net/stickershop/v1/sticker/29135267/ANDROID/sticker.png"; public static string Sticker345 = "https://stickershop.line-scdn.net/stickershop/v1/sticker/29135268/ANDROID/sticker.png"; public static string Sticker346 = "https://stickershop.line-scdn.net/stickershop/v1/product/1041829/LINEStorePC/main.png"; public static string Sticker347 = "https://stickershop.line-scdn.net/stickershop/v1/sticker/68688558/ANDROID/sticker.png"; public static string Sticker348 = "https://stickershop.line-scdn.net/stickershop/v1/sticker/68688559/ANDROID/sticker.png"; public static string Sticker349 = "https://stickershop.line-scdn.net/stickershop/v1/sticker/68688562/ANDROID/sticker.png"; public static string Sticker350 = "https://stickershop.line-scdn.net/stickershop/v1/sticker/68688563/ANDROID/sticker.png"; public static JavaList<string> StickerList11 = new JavaList<string> { Sticker315, Sticker316, Sticker317, Sticker318, Sticker319, Sticker320, Sticker321, Sticker322, Sticker323, Sticker324, Sticker325, Sticker326, Sticker327, Sticker328, Sticker329, Sticker330, Sticker331, Sticker332, Sticker333, Sticker334, Sticker335, Sticker336, Sticker337, Sticker338, Sticker339, Sticker340, Sticker341, Sticker342, Sticker343, Sticker344, Sticker345, Sticker346, Sticker347, Sticker348, Sticker349, Sticker350, }; #endregion //############################# End Stickers ############################# } }
72.165613
135
0.690994
[ "MIT" ]
arifahmedjoy/cornertable-android
WoWonder/Helpers/Model/Stickers.cs
57,083
C#